Skip to content

2026 Swerve Base Changes - #21

Merged
cherriae merged 2 commits into
mainfrom
r2026-changes
Nov 11, 2026
Merged

cherriae merged 2 commits into
mainfrom
r2026-changes

Conversation

@cherriae

@cherriae cherriae commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

ChangeLog

1. Package reorg — frc.lib → subpackages

Files moved and all imports updated repo-wide:

  • frc.lib.FaultLogger → frc.lib.fault.FaultLogger
  • frc.lib.FaultsTable → frc.lib.fault.FaultsTable
  • frc.lib.AdvancedSubsystem → frc.lib.subsystem.AdvancedSubsystem
  • frc.lib.SelfChecked → frc.lib.subsystem.SelfChecked
  • frc.lib.CTREUtil → frc.lib.util.CTREUtil
  • frc.lib.UnitTestingUtil → frc.lib.util.UnitTestingUtil
  • frc.lib.FilteredPIDController → frc.lib.math.FilteredPIDController
  • frc.robot.utils.SysId → frc.lib.SysId

2. New lib files

  • frc/lib/math/TimeoutLinearFilter.java (new) — wraps a LinearFilter, auto-resets it if .calculate() hasn't been called within a timeout.

  • frc/lib/math/FilteredPIDController.java (new) — PID controller with optional continuous-input wraparound and an optional low-pass filter on the setpoint velocity term (not measurement), built on TimeoutLinearFilter. Fields renamed to _kP/_kD/_period underscore convention. Used by HolonomicController in place of raw PIDController.

  • frc/lib/GcStatsCollector.java (new) — call .update() in robotPeriodic(); logs GC/GCTime (seconds, not ms) and GC/GCCounts as deltas since last call using ManagementFactory.getGarbageCollectorMXBeans().

3. frc/lib/subsystem/AdvancedSubsystem.java

  • addFault(...) visibility: protected final → public final.
  • FaultsTable NT table: "Self Check" → "SelfChecked".
  • DogLog.logFault(fault.toString()) → DogLog.logFault(fault.toString(), null) (signature gained a 2nd param).

4. frc/lib/fault/FaultLogger.java / FaultsTable.java

  • Base NT table: "Faults" → "FaultLogger".
  • register(PhotonCamera) message: photonCamera.getName() + ": Disconnected." → "PhotonCamera " + name + "- Disconnected."

5. frc/lib/util/CTREUtil.java

  • Fault messages generalized from config-specific to generic: "Config Apply Successful."/"Config Apply Failed - ..." → "Action Successful."/"Action Failed - ...".
  • getName(TalonFX/CANcoder/Pigeon2) now includes the CAN bus name: "TalonFX (" + id + " - " + device.getNetwork().getName() + ")".
  • CTREUtilTest.java updated to match.

6. frc/lib/util/UnitTestingUtil.java

  • Added:
public static void run(Command command, Time time) {
  CommandScheduler.getInstance().schedule(command);
  fastForward(time);
}

7. frc/lib/InputStream.java

  • .log(String key) switched from a raw NetworkTableInstance DoublePublisher to DogLog.log(key, val).

8. HolonomicController.java

End state vs. original:

  • Backing PID controllers are now FilteredPIDController (period = Constants.robotPeriod.in(Seconds)), not raw PIDController.
  • Added independent filtering toggles instead of always-on/off:
    public boolean isFilteringTranslation();      // @Logged
    public void useFilteringTranslation(boolean); // enables tau=0.2 setpoint-velocity filter on x/y
    public boolean isFilteringHeading();           // @Logged
    public void useFilteringHeading(boolean);      // enables tau=0.2 filter on heading
    
  • Split "reset profile state" from "reset PID state" — resetPID() no longer called implicitly inside reset(...); callers must explicitly manage it or rely on the filtering toggles.
  • _translationDirection.norm() == 0 edge case handled: falls back to antiparallel-to-current-velocity, or (1,0) if velocity is also zero (previously would divide by zero / NaN).
  • Setpoint-stepping split out of calculate(): new nextSetpoint(Rotation2d currentHeading) samples both profiles and stores _setpointSpeeds/_setpointPose (with getters), plus computes _wheelForces via the internal WheelForceCalculator.
  • Rotation-only convenience path renamed/cleaned: reset(Rotation2d, double) → resetRotation(...); calculateOmega(...) → nextSetpointRotation(...), then later removed in favor of computing omega feedforward manually in Swerve.driveFacing plus a plain calculate(Pose2d desiredPose, Pose2d currentPose) overload (= calculate(zeroSpeeds, desiredPose, currentPose)).
  • Added/then removed a ChassisSpeeds feedforward option (addFeedForward) — added in one pass, explicitly ripped back out later ("doesn't really make sense" — feedforward was being double-counted against the profile).
  • calculateWheelForces(ax, ay, alpha) replaced by exposing the calculator directly: public WheelForceCalculator getWheelForceCalculator().
  • _wheelForceCalculator.calculate(...) period arg: Robot.kDefaultPeriod → Constants.robotPeriod.in(Seconds).
  • Log keys: "Auto/Controller Desired Pose" / "Auto/Controller Reference Pose" → "Swerve/Holonomic Controller/Controller Desired Pose" / "...Actual Pose".
  • Class gained @Logged(name = "Holonomic Controller") when embedded in Swerve (moved off opt-in strategy).

9. Swerve.java

Bug fixes:

  • driveTo() was feeding the raw profile setpoint speeds straight to setControl(), bypassing PID correction entirely (pure open-loop). Fixed to route through _holonomicController.calculate(setpointSpeeds, setpointPose, getPose()) first.
  • calculateMotorMaxSpeedAndTorque(): CTREUtil.attempt(...) return value was being used inverted (if (!suc) treated success as failure). Fixed to if (failed).
  • Heading feedforward deltas (driveFacing/followTrajectoryFacing) switched from raw heading - previous subtraction to MathUtil.inputModulus(delta, -PI, PI) to fix wraparound at ±180°.

Rotation-facing improvements:

  • Added _previousRotationSetpoint (renamed from _previousRotationGoal) + omega feedforward computed manually and passed through a TimeoutLinearFilter:
    private final TimeoutLinearFilter _omegaFeedforwardFilter =
        new TimeoutLinearFilter(LinearFilter.singlePoleIIR(0.1, Constants.robotPeriod.in(Seconds)), 2);
    
    (started at tau=0.2, tuned down to 0.1). Filter applied to both driveFacing()'s and followTrajectoryFacing()'s omega feedforward.
  • driveFacing(velX, velY, heading): PID omega + filtered feedforward:
    double omega = _holonomicController.calculate(
          new Pose2d(getPose().getTranslation(), heading.get()), getPose()).omegaRadiansPerSecond
        + omegaFeedforward;
    
    beforeStarting: isOpenLoop = false, seed _previousRotationSetpoint = getHeading(), useFilteringHeading(true).
  • followTrajectory(sample): useFilteringTranslation(false); useFilteringHeading(false); at top; sets _mustResetRotationController = true.
  • followTrajectoryFacing(sample, heading): unconditionally useFilteringTranslation(false); useFilteringHeading(true);; computes omega from the modulus'd heading delta over Constants.robotPeriod, filters it, feeds it in place of the sample's own omega; wheel force FF computed with getWheelForceCalculator().calculate(sample.ax, sample.ay, 0) (alpha assumed ~0).
  • drive(InputStream, InputStream, InputStream) is now a Command (was void drive(double,double,double)), returned via run(...). Per-loop driver-speed DogLog calls were added then explicitly removed ("no driver logging inst rlly needed") — logging is left to InputStream.log(key) at the call site instead.

Timing/period:

  • Constructor: super(Constants.robotPeriod.in(Seconds)) (new Constants.robotPeriod = Seconds.of(0.02)), all manual Timer.getFPGATimestamp() deltas replaced by the fixed period.

  • periodic(): _lastLoopTime = Timer.getFPGATimestamp(); set at top (used only where still needed).

  • Current limits / calculators (front-module slip current):

final var currentLimitConfigs = new CurrentLimitsConfigs();
CTREUtil.attempt(() -> frontLeftDriveConfigurator.refresh(currentLimitConfigs), getModule(0).getDriveMotor());
currentLimitConfigs.StatorCurrentLimit = SwerveConstants.frontSlipCurrent.in(Amps);
CTREUtil.attempt(() -> frontLeftDriveConfigurator.apply(currentLimitConfigs), getModule(0).getDriveMotor());
// same for module(1) front right
  • calculateWheelCOF() deleted entirely — replaced by setting cof: 100 directly in config.chor (workaround since COF measurement wasn't reliable/needed once slip current handles traction).
  • calculateMOI() reworked to sum per-module torque × radius-to-center using a DoubleArraySubscriber tunable angularkAPerModule (4-element array) instead of a single front-module-based estimate:
    final DoubleArraySubscriber angularkAPerModule = DogLog.tunable("Calculator/Angular kA Per Module", new double[4]);
    for (int module = 0; module < 4; module++) {
      double moduleToCenter = getModuleLocations()[module].getNorm();
      double moduleForce = driveMotor.getTorque(driveMotor.getCurrent(0, angularkAPerModule.get()[module]))
          * GearRatio / WheelRadius;
      chassisTorque += moduleForce * moduleToCenter;
    }
    
  • calculateMotorMaxSpeedAndTorque(): headroom made tunable (DogLog.tunable("Calculator/Headroom", .8)), torque now averaged from each module's actual configured StatorCurrentLimit (read back via CTREUtil.attempt) instead of TunerConstants.FrontLeft.SlipCurrent, with an early-return fault if any module fails to refresh.
  • Dead code removed: calculateMaxOmegaAtLinearVelocity().
  • Default command added: setDefaultCommand(run(() -> setControl(new Idle())));

Logging/misc:

  • @Logged(strategy = Strategy.OPT_IN) removed from the class (switched to default logging everywhere; individual fields get explicit @Logged(name=...) where wanted).
  • periodic() end: DogLog.log(getName() + "/Current Command", currentCommandName()), DogLog.log(getName() + "/Has Error", _hasError).
  • FaultsTable NT root renamed to "SelfChecked" (matches AdvancedSubsystem).

10. Constants.java

  • ```java
    public static final Time robotPeriod = Seconds.of(0.02);
- [x]  ```java
public static class MotorConstants {
  public static final DCMotor krakenX60 =
      new DCMotor(12, 7.16, 374.4, 3, Units.rotationsPerMinuteToRadiansPerSecond(6065), 1);
}
  • frontSlipCurrent = Amps.of(40);

11. VisionPoseEstimator.java

  • Split the single shared std-dev scaler into separate translation/theta scalers:
public static final double translationStdDevsScaler = 1;
public static final double thetaStdDevsScaler = 1;

applied independently to xStdDevs/yStdDevs vs thetaStdDevs in the estimate-validity math (previously one scaler multiplied all three).

  • Class also dropped @Logged(strategy = Strategy.OPT_IN).

12. Robot.java

  • Constructor: super(Constants.robotPeriod.in(Seconds));
  • _gcStatsCollector.update(); called once per robotPeriodic().
  • SmartDashboard buttons for wheelRadiusCharacterization(), calculateMOI(), calculateMotorMaxSpeedAndTorque() (no COF button anymore).

13. Build/config

  • build.gradle: removed the commented-out remote-debug JVM args block and the GC-tuning JVM args block under deploy { targets { ... } artifacts { frcJavaArtifact { ... jvmArgs... } } } } — template should ship clean without dead commented config.

@cherriae
cherriae marked this pull request as ready for review August 10, 2026 17:44
@cherriae
cherriae requested a review from PGgit08 August 10, 2026 17:44
@cherriae cherriae self-assigned this Aug 10, 2026
@cherriae cherriae added the enhancement New feature or request label Aug 10, 2026
@cherriae
cherriae requested a balanced review from Copilot August 10, 2026 19:18

This comment was marked as off-topic.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 24 out of 26 changed files in this pull request and generated 1 comment.

Suppressed comments (10)

src/main/java/frc/robot/utils/HolonomicController.java:257

  • _prevSetpointSpeeds is reassigned to _setpointSpeeds, reintroducing aliasing between the "previous" and "current" setpoint objects. On the next loop this makes the wheel force calculation see identical prev/current speeds (or even mutate prev before the calc), producing incorrect feedforward forces.
        _wheelForceCalculator.calculate(
            Constants.robotPeriod.in(Seconds), _prevSetpointSpeeds, _setpointSpeeds);

    _prevSetpointSpeeds = _setpointSpeeds;
  }

src/main/java/frc/lib/util/CTREUtil.java:95

  • getName(...) always appends " - " + device.getNetwork().getName(). In sim/tests (and possibly on rio) the bus name may be empty, producing names like "TalonFX (1 - )" which are awkward and make logs/tests brittle.
    src/main/java/frc/lib/math/FilteredPIDController.java:77
  • In the non-continuous-input path, the measurement/setpoint derivatives are missing division by _period. This makes the D term depend on the loop period (and be off by a factor of ~50 at 20ms), causing unstable/incorrect control when kD != 0.
    } else {
      error = setpoint - measurement;

      measurementDerivative = measurement - _prevMeasurement;
      setpointDerivative = setpoint - _prevSetpoint;
    }

src/main/java/frc/robot/subsystems/Swerve.java:433

  • driveFacing() calls heading.get() multiple times in a single cycle (delta, assignment to _previousRotationSetpoint, and desired Pose2d). If the supplier isn't perfectly stable within the call, this can yield inconsistent omega feedforward vs controller reference, and it does extra work every loop.
            () -> {
              double omegaFeedforward =
                  MathUtil.inputModulus(
                          heading.get().getRadians() - _previousRotationSetpoint.getRadians(),
                          -Math.PI,

src/main/java/frc/robot/subsystems/Swerve.java:439

  • driveFacing() computes omega feedforward from the difference between the current target heading and _previousRotationSetpoint, but _previousRotationSetpoint is never initialized when the command starts. This can create a large first-step omegaFeedforward spike (e.g., if the target starts near π and the previous value is 0).
                () -> {
                  isOpenLoop = false;

                  _holonomicController.useFilteringHeading(true);

src/main/java/frc/robot/Robot.java:122

  • FaultLogger.update() is no longer scheduled, but FaultLogger.update() is documented as required to poll registered fault reporters and publish active/total faults. As-is, faults registered via FaultLogger.register(...) will never be evaluated during robot runtime.
    // addPeriodic(FaultLogger::update, 1);

src/test/java/frc/robot/RobotTest.java:17

  • The entire RobotTest is disabled without a reason string, which makes it easy for this to remain permanently disabled and silently reduce coverage. Prefer adding an explicit reason (and ideally a TODO/issue reference) or re-enabling once fixed.
@Disabled

src/main/java/frc/robot/Constants.java:44

  • determineBus(...) and determineID(...) are currently unused anywhere in the codebase (and will likely trigger IDE/lint warnings). If these are intended for simulation-safe IDs/bus selection, wire them into the relevant constants; otherwise delete them to avoid dead code.
  private static final CANBus determineBus(String bus) {
    if (Robot.isSimulation()) {
      return new CANBus("");
    }

src/main/java/frc/robot/Constants.java:111

  • PR description says SwerveConstants.frontSlipCurrent was set to 40A, but the code sets it to 120A. Either the constant value or the PR description needs to be updated so they match.
    public static final Current frontSlipCurrent =
        Amps.of(120); // TODO: tune front slip current, default is 120A

src/main/java/frc/robot/subsystems/Swerve.java:469

  • Javadoc typo: "overriden" -> "overridden".
  /**
   * Sets the chassis state to the given {@link SwerveSample} for trajectory following. Omega is
   * overriden by the omega generated from the holonomic controller to follow the supplied heading.
   *

@cherriae
cherriae merged commit 4b2e76a into main Nov 11, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants