Repository navigation
2026 Swerve Base Changes - #21
Merged
Merged
Conversation
There was a problem hiding this comment.
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.
*
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ChangeLog
1. Package reorg —
frc.lib→ subpackagesFiles moved and all imports updated repo-wide:
frc.lib.FaultLogger→frc.lib.fault.FaultLoggerfrc.lib.FaultsTable→frc.lib.fault.FaultsTablefrc.lib.AdvancedSubsystem→frc.lib.subsystem.AdvancedSubsystemfrc.lib.SelfChecked→frc.lib.subsystem.SelfCheckedfrc.lib.CTREUtil→frc.lib.util.CTREUtilfrc.lib.UnitTestingUtil→frc.lib.util.UnitTestingUtilfrc.lib.FilteredPIDController→frc.lib.math.FilteredPIDControllerfrc.robot.utils.SysId→frc.lib.SysId2. New lib files
frc/lib/math/TimeoutLinearFilter.java(new) — wraps aLinearFilter, 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 onTimeoutLinearFilter. Fields renamed to_kP/_kD/_periodunderscore convention. Used byHolonomicControllerin place of rawPIDController.frc/lib/GcStatsCollector.java(new) — call.update()inrobotPeriodic(); logsGC/GCTime(seconds, not ms) andGC/GCCountsas deltas since last call usingManagementFactory.getGarbageCollectorMXBeans().3.
frc/lib/subsystem/AdvancedSubsystem.javaaddFault(...)visibility:protected final→public final."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"Faults"→"FaultLogger".register(PhotonCamera)message:photonCamera.getName() + ": Disconnected."→"PhotonCamera " + name + "- Disconnected."5.
frc/lib/util/CTREUtil.java"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.javaupdated to match.6.
frc/lib/util/UnitTestingUtil.java7.
frc/lib/InputStream.java.log(String key)switched from a rawNetworkTableInstanceDoublePublishertoDogLog.log(key, val).8.
HolonomicController.javaEnd state vs. original:
FilteredPIDController(period =Constants.robotPeriod.in(Seconds)), not rawPIDController.resetPID()no longer called implicitly insidereset(...); callers must explicitly manage it or rely on the filtering toggles._translationDirection.norm() == 0edge case handled: falls back to antiparallel-to-current-velocity, or(1,0)if velocity is also zero (previously would divide by zero / NaN).calculate(): newnextSetpoint(Rotation2d currentHeading)samples both profiles and stores_setpointSpeeds/_setpointPose(with getters), plus computes_wheelForcesvia the internalWheelForceCalculator.reset(Rotation2d, double)→resetRotation(...);calculateOmega(...)→nextSetpointRotation(...), then later removed in favor of computing omega feedforward manually inSwerve.driveFacingplus a plaincalculate(Pose2d desiredPose, Pose2d currentPose)overload (= calculate(zeroSpeeds, desiredPose, currentPose)).ChassisSpeedsfeedforward 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)."Auto/Controller Desired Pose"/"Auto/Controller Reference Pose"→"Swerve/Holonomic Controller/Controller Desired Pose"/"...Actual Pose".@Logged(name = "Holonomic Controller")when embedded inSwerve(moved off opt-in strategy).9.
Swerve.javaBug fixes:
driveTo()was feeding the raw profile setpoint speeds straight tosetControl(), 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 toif (failed).driveFacing/followTrajectoryFacing) switched from rawheading - previoussubtraction toMathUtil.inputModulus(delta, -PI, PI)to fix wraparound at ±180°.Rotation-facing improvements:
_previousRotationSetpoint(renamed from_previousRotationGoal) + omega feedforward computed manually and passed through aTimeoutLinearFilter:driveFacing()'s andfollowTrajectoryFacing()'s omega feedforward.driveFacing(velX, velY, heading): PID omega + filtered feedforward:beforeStarting:isOpenLoop = false, seed_previousRotationSetpoint = getHeading(),useFilteringHeading(true).followTrajectory(sample):useFilteringTranslation(false); useFilteringHeading(false);at top; sets_mustResetRotationController = true.followTrajectoryFacing(sample, heading): unconditionallyuseFilteringTranslation(false); useFilteringHeading(true);; computes omega from the modulus'd heading delta overConstants.robotPeriod, filters it, feeds it in place of the sample's own omega; wheel force FF computed withgetWheelForceCalculator().calculate(sample.ax, sample.ay, 0)(alpha assumed ~0).drive(InputStream, InputStream, InputStream)is now aCommand(wasvoid drive(double,double,double)), returned viarun(...). Per-loop driver-speed DogLog calls were added then explicitly removed ("no driver logging inst rlly needed") — logging is left toInputStream.log(key)at the call site instead.Timing/period:
Constructor:
super(Constants.robotPeriod.in(Seconds))(newConstants.robotPeriod = Seconds.of(0.02)), all manualTimer.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):
calculateWheelCOF()deleted entirely — replaced by settingcof: 100directly inconfig.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 aDoubleArraySubscribertunableangularkAPerModule(4-element array) instead of a single front-module-based estimate:calculateMotorMaxSpeedAndTorque(): headroom made tunable (DogLog.tunable("Calculator/Headroom", .8)), torque now averaged from each module's actual configuredStatorCurrentLimit(read back viaCTREUtil.attempt) instead ofTunerConstants.FrontLeft.SlipCurrent, with an early-return fault if any module fails to refresh.calculateMaxOmegaAtLinearVelocity().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)."SelfChecked"(matchesAdvancedSubsystem).10.
Constants.javapublic static final Time robotPeriod = Seconds.of(0.02);
frontSlipCurrent = Amps.of(40);11.
VisionPoseEstimator.javaapplied independently to
xStdDevs/yStdDevsvsthetaStdDevsin the estimate-validity math (previously one scaler multiplied all three).@Logged(strategy = Strategy.OPT_IN).12.
Robot.javasuper(Constants.robotPeriod.in(Seconds));_gcStatsCollector.update();called once perrobotPeriodic().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 underdeploy { targets { ... } artifacts { frcJavaArtifact { ... jvmArgs... } } } }— template should ship clean without dead commented config.