diff --git a/build.gradle b/build.gradle index 81be854..e3b33e9 100644 --- a/build.gradle +++ b/build.gradle @@ -35,16 +35,6 @@ deploy { // jvmArgs.add("-Dcom.sun.management.jmxremote.ssl=false") // jvmArgs.add("-Dcom.sun.management.jmxremote.authenticate=false") // jvmArgs.add("-Djava.rmi.server.hostname=10.3.34.2") - - // jvmArgs.add("-XX:+UnlockExperimentalVMOptions") - // jvmArgs.add("-XX:GCTimeRatio=5") - // jvmArgs.add("-XX:+UseSerialGC") - // jvmArgs.add("-XX:MaxGCPauseMillis=50") - - // final MAX_JAVA_HEAP_SIZE_MB = 100; - // jvmArgs.add("-Xmx" + MAX_JAVA_HEAP_SIZE_MB + "M") - // jvmArgs.add("-Xms" + MAX_JAVA_HEAP_SIZE_MB + "M") - // jvmArgs.add("-XX:+AlwaysPreTouch") } // Static files artifact diff --git a/src/main/java/frc/lib/GcStatsCollector.java b/src/main/java/frc/lib/GcStatsCollector.java new file mode 100644 index 0000000..038aa0f --- /dev/null +++ b/src/main/java/frc/lib/GcStatsCollector.java @@ -0,0 +1,29 @@ +package frc.lib; + +import dev.doglog.DogLog; +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.util.List; + +public class GcStatsCollector { + private List gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); + private final long[] lastTimes = new long[gcBeans.size()]; + private final long[] lastCounts = new long[gcBeans.size()]; + + public void update() { + long accumTime = 0; + long accumCounts = 0; + for (int i = 0; i < gcBeans.size(); i++) { + long gcTime = gcBeans.get(i).getCollectionTime(); + long gcCount = gcBeans.get(i).getCollectionCount(); + accumTime += gcTime - lastTimes[i]; + accumCounts += gcCount - lastCounts[i]; + + lastTimes[i] = gcTime; + lastCounts[i] = gcCount; + } + + DogLog.log("GC/GCTime", accumTime / 1000.0); + DogLog.log("GC/GCCounts", (double) accumCounts); + } +} diff --git a/src/main/java/frc/lib/InputStream.java b/src/main/java/frc/lib/InputStream.java index aa4bc1d..bfa3088 100644 --- a/src/main/java/frc/lib/InputStream.java +++ b/src/main/java/frc/lib/InputStream.java @@ -4,11 +4,10 @@ package frc.lib; +import dev.doglog.DogLog; import edu.wpi.first.math.MathUtil; import edu.wpi.first.math.filter.LinearFilter; import edu.wpi.first.math.filter.SlewRateLimiter; -import edu.wpi.first.networktables.DoublePublisher; -import edu.wpi.first.networktables.NetworkTableInstance; import java.util.function.BooleanSupplier; import java.util.function.DoubleSupplier; import java.util.function.DoubleUnaryOperator; @@ -16,6 +15,8 @@ /** A functional interface to aid in modifying double suppliers, such as from a joystick. */ @FunctionalInterface public interface InputStream extends DoubleSupplier { + public static final InputStream zero = of(() -> 0); + /** * Creates an input stream from another. * @@ -186,13 +187,11 @@ public default InputStream rateLimit(double rate, BooleanSupplier enable) { * @return A stream with the same output as this one. */ public default InputStream log(String key) { - DoublePublisher pub = - NetworkTableInstance.getDefault() - .getDoubleTopic(key) - .publish(); // TODO: watch out unit tests return () -> { double val = this.get(); - pub.set(val); + + DogLog.log(key, val); + return val; }; } diff --git a/src/main/java/frc/robot/utils/SysId.java b/src/main/java/frc/lib/SysId.java similarity index 98% rename from src/main/java/frc/robot/utils/SysId.java rename to src/main/java/frc/lib/SysId.java index a5479bd..17e0a26 100644 --- a/src/main/java/frc/robot/utils/SysId.java +++ b/src/main/java/frc/lib/SysId.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package frc.robot.utils; +package frc.lib; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine; diff --git a/src/main/java/frc/lib/FaultLogger.java b/src/main/java/frc/lib/fault/FaultLogger.java similarity index 97% rename from src/main/java/frc/lib/FaultLogger.java rename to src/main/java/frc/lib/fault/FaultLogger.java index 3aae6c1..c412be9 100644 --- a/src/main/java/frc/lib/FaultLogger.java +++ b/src/main/java/frc/lib/fault/FaultLogger.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package frc.lib; +package frc.lib.fault; import com.ctre.phoenix6.BaseStatusSignal; import com.ctre.phoenix6.hardware.CANcoder; @@ -11,8 +11,9 @@ import dev.doglog.DogLog; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.DriverStation; -import frc.lib.FaultsTable.Fault; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultsTable.Fault; +import frc.lib.fault.FaultsTable.FaultType; +import frc.lib.util.CTREUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -53,7 +54,7 @@ public static interface FaultReporter { public static void setup(NetworkTableInstance ntInst) { if (_hasBeenSetup) return; - var base = ntInst.getTable("Faults"); + var base = ntInst.getTable("FaultLogger"); activeAlerts = new FaultsTable(base, "Active Faults"); totalAlerts = new FaultsTable(base, "Total Faults"); @@ -286,7 +287,7 @@ public static void register(Pigeon2 pigeon) { public static void register(PhotonCamera photonCamera) { register( () -> !photonCamera.isConnected(), - photonCamera.getName() + ": Disconnected.", + "PhotonCamera " + photonCamera.getName() + "- Disconnected.", FaultType.ERROR); } } diff --git a/src/main/java/frc/lib/FaultsTable.java b/src/main/java/frc/lib/fault/FaultsTable.java similarity index 98% rename from src/main/java/frc/lib/FaultsTable.java rename to src/main/java/frc/lib/fault/FaultsTable.java index c70c2bf..e33c4ac 100644 --- a/src/main/java/frc/lib/FaultsTable.java +++ b/src/main/java/frc/lib/fault/FaultsTable.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package frc.lib; +package frc.lib.fault; import edu.wpi.first.networktables.NetworkTable; import edu.wpi.first.networktables.StringArrayPublisher; diff --git a/src/main/java/frc/lib/math/FilteredPIDController.java b/src/main/java/frc/lib/math/FilteredPIDController.java new file mode 100644 index 0000000..4a8e6df --- /dev/null +++ b/src/main/java/frc/lib/math/FilteredPIDController.java @@ -0,0 +1,88 @@ +package frc.lib.math; + +import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.filter.LinearFilter; + +public final class FilteredPIDController { + private final double _kP; + private final double _kD; + + private final double _period; + + private boolean _filterSetpointVelocity; + private final TimeoutLinearFilter _setpointVelocityFilter; + + private double _prevSetpoint; + private double _prevMeasurement; + + private boolean _continuous; + private double _maximumInput; + private double _minimumInput; + + public FilteredPIDController(double kP, double kD, double period, double tau) { + this._kP = kP; + this._kD = kD; + + this._period = period; + + _setpointVelocityFilter = + new TimeoutLinearFilter(LinearFilter.singlePoleIIR(tau, this._period), 2); + } + + public boolean isFilteringSetpointVelocity() { + return _filterSetpointVelocity; + } + + public void enableSetpointVelocityFilter() { + _filterSetpointVelocity = true; + } + + public void disableSetpointVelocityFilter() { + _filterSetpointVelocity = false; + } + + public boolean isContinuousInput() { + return _continuous; + } + + public void enableContinuousInput(double minimumInput, double maximumInput) { + _continuous = true; + _minimumInput = minimumInput; + _maximumInput = maximumInput; + } + + public void disableContinuousInput() { + _continuous = false; + } + + public double calculate(double measurement, double setpoint) { + double error; + + double measurementDerivative; + double setpointDerivative; + + if (_continuous) { + double bound = (_maximumInput - _minimumInput) / 2.0; + + error = MathUtil.inputModulus(setpoint - measurement, -bound, bound); + + measurementDerivative = + MathUtil.inputModulus(measurement - _prevMeasurement, -bound, bound) / _period; + setpointDerivative = MathUtil.inputModulus(setpoint - _prevSetpoint, -bound, bound) / _period; + } else { + error = setpoint - measurement; + + measurementDerivative = measurement - _prevMeasurement; + setpointDerivative = setpoint - _prevSetpoint; + } + + if (_filterSetpointVelocity) { + setpointDerivative = _setpointVelocityFilter.calculate(setpointDerivative); + } + + _prevMeasurement = measurement; + _prevSetpoint = setpoint; + + return _kP * error + _kD * (setpointDerivative - measurementDerivative); + } +} diff --git a/src/main/java/frc/lib/math/TimeoutLinearFilter.java b/src/main/java/frc/lib/math/TimeoutLinearFilter.java new file mode 100644 index 0000000..1fa6785 --- /dev/null +++ b/src/main/java/frc/lib/math/TimeoutLinearFilter.java @@ -0,0 +1,50 @@ +package frc.lib.math; + +import edu.wpi.first.math.filter.LinearFilter; +import edu.wpi.first.wpilibj.Timer; + +/** + * Automatically resets a supplied LinearFilter after a given timeout has elapsed since the last + * call to the filter. + */ +public class TimeoutLinearFilter { + private final LinearFilter _filter; + + private final Timer _resetTimer = new Timer(); + private final double _timeout; + + /** + * @param filter The filter. + * @param timeout Timeout in seconds. + */ + public TimeoutLinearFilter(LinearFilter filter, double timeout) { + _filter = filter; + _timeout = timeout; + } + + /** Get the internal linear filter. */ + public LinearFilter getFilter() { + return _filter; + } + + /** Get the timeout in seconds. */ + public double getTimeout() { + return _timeout; + } + + /** + * Calls the internal filter's {@link LinearFilter#calculate(double)}. If the specified timeout + * has elapsed since the last calculate call, the internal filter is reset. + */ + public double calculate(double input) { + if (_resetTimer.hasElapsed(_timeout)) { + _filter.reset(); + } + + double output = _filter.calculate(input); + + _resetTimer.restart(); + + return output; + } +} diff --git a/src/main/java/frc/lib/AdvancedSubsystem.java b/src/main/java/frc/lib/subsystem/AdvancedSubsystem.java similarity index 87% rename from src/main/java/frc/lib/AdvancedSubsystem.java rename to src/main/java/frc/lib/subsystem/AdvancedSubsystem.java index 571f2e4..53355aa 100644 --- a/src/main/java/frc/lib/AdvancedSubsystem.java +++ b/src/main/java/frc/lib/subsystem/AdvancedSubsystem.java @@ -1,4 +1,4 @@ -package frc.lib; +package frc.lib.subsystem; import static edu.wpi.first.wpilibj2.command.Commands.*; @@ -8,8 +8,9 @@ import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SubsystemBase; -import frc.lib.FaultsTable.Fault; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultsTable; +import frc.lib.fault.FaultsTable.Fault; +import frc.lib.fault.FaultsTable.FaultType; import java.util.HashSet; import java.util.Set; @@ -27,7 +28,7 @@ public AdvancedSubsystem() { } public AdvancedSubsystem(NetworkTableInstance ntInst) { - _faultsTable = new FaultsTable(ntInst.getTable("Self Check"), getName() + " Faults"); + _faultsTable = new FaultsTable(ntInst.getTable("SelfChecked"), getName() + " Faults"); } /** @@ -43,12 +44,12 @@ public final String currentCommandName() { } /** Adds a new fault under this subsystem. */ - protected final void addFault(String description, FaultType faultType) { + public final void addFault(String description, FaultType faultType) { _hasError = (faultType == FaultType.ERROR); Fault fault = new Fault(description, faultType); - DogLog.logFault(fault.toString()); + DogLog.logFault(fault.toString(), null); _faults.add(fault); _faultsTable.set(_faults); diff --git a/src/main/java/frc/lib/SelfChecked.java b/src/main/java/frc/lib/subsystem/SelfChecked.java similarity index 86% rename from src/main/java/frc/lib/SelfChecked.java rename to src/main/java/frc/lib/subsystem/SelfChecked.java index 2dd3eae..1235d5a 100644 --- a/src/main/java/frc/lib/SelfChecked.java +++ b/src/main/java/frc/lib/subsystem/SelfChecked.java @@ -1,15 +1,15 @@ -package frc.lib; +package frc.lib.subsystem; import static edu.wpi.first.wpilibj2.command.Commands.*; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultsTable.FaultType; public interface SelfChecked { /** * Returns a Command that self checks this system. This command should utilize the advanced - * subsytem's {@link AdvancedSubsystem#addFault(String, FaultType)}. + * subsystem's {@link AdvancedSubsystem#addFault(String, FaultType)}. */ public default Command selfCheck() { return none(); diff --git a/src/main/java/frc/lib/CTREUtil.java b/src/main/java/frc/lib/util/CTREUtil.java similarity index 85% rename from src/main/java/frc/lib/CTREUtil.java rename to src/main/java/frc/lib/util/CTREUtil.java index bebc271..5481b99 100644 --- a/src/main/java/frc/lib/CTREUtil.java +++ b/src/main/java/frc/lib/util/CTREUtil.java @@ -2,13 +2,14 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package frc.lib; +package frc.lib.util; import com.ctre.phoenix6.StatusCode; import com.ctre.phoenix6.hardware.CANcoder; import com.ctre.phoenix6.hardware.Pigeon2; import com.ctre.phoenix6.hardware.TalonFX; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultLogger; +import frc.lib.fault.FaultsTable.FaultType; import java.util.function.Supplier; /** Utility class for CTRE devices. */ @@ -36,14 +37,14 @@ public static boolean attempt(Supplier action, String deviceName) { // successful attempt if (statusCode.isOK()) { - FaultLogger.report(deviceName + " - Config Apply Successful.", FaultType.INFO); + FaultLogger.report(deviceName + " - Action Successful.", FaultType.INFO); return false; } // failed attempt else { FaultLogger.report( - deviceName + " - Config Apply Failed - " + statusCode.getDescription(), FaultType.ERROR); + deviceName + " - Action Failed - " + statusCode.getDescription(), FaultType.ERROR); return true; } } @@ -89,16 +90,16 @@ public static boolean attempt(Supplier action, Pigeon2 pigeon) { /** Returns the name to use when displaying info about a TalonFX. */ public static String getName(TalonFX talonFX) { - return "TalonFX (" + talonFX.getDeviceID() + ")"; + return "TalonFX (" + talonFX.getDeviceID() + " - " + talonFX.getNetwork().getName() + ")"; } /** Returns the name to use when displaying info about a CANcoder. */ public static String getName(CANcoder cancoder) { - return "CANcoder (" + cancoder.getDeviceID() + ")"; + return "CANcoder (" + cancoder.getDeviceID() + " - " + cancoder.getNetwork().getName() + ")"; } /** Retunrs the name to use when displaying info about a Pigeon. */ public static String getName(Pigeon2 pigeon) { - return "Pigeon (" + pigeon.getDeviceID() + ")"; + return "Pigeon (" + pigeon.getDeviceID() + " - " + pigeon.getNetwork().getName() + ")"; } } diff --git a/src/main/java/frc/lib/UnitTestingUtil.java b/src/main/java/frc/lib/util/UnitTestingUtil.java similarity index 91% rename from src/main/java/frc/lib/UnitTestingUtil.java rename to src/main/java/frc/lib/util/UnitTestingUtil.java index 5120318..13fb116 100644 --- a/src/main/java/frc/lib/UnitTestingUtil.java +++ b/src/main/java/frc/lib/util/UnitTestingUtil.java @@ -1,4 +1,4 @@ -package frc.lib; +package frc.lib.util; import static edu.wpi.first.units.Units.Seconds; @@ -12,6 +12,7 @@ import edu.wpi.first.wpilibj.simulation.SimHooks; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.CommandScheduler; +import frc.lib.fault.FaultLogger; /** Provides helper methods that run a command when performing unit tests. */ public class UnitTestingUtil { @@ -89,7 +90,7 @@ public static void fastForward(int ticks) { /** * Fasts forward in time by running CommandScheduler and updating timer. * - * @param time + * @param time The time to run for. */ public static void fastForward(Time time) { fastForward((int) (time.in(Seconds) / TICK_RATE.in(Seconds))); @@ -124,6 +125,17 @@ public static void run(Command command, int runs) { fastForward(runs); } + /** + * Schedule and runs a command. + * + * @param command The command to run. + * @param time The time to run it for. + */ + public static void run(Command command, Time time) { + CommandScheduler.getInstance().schedule(command); + fastForward(time); + } + /** * Schedules a command and runs it until it ends. Be careful -- if the command you give never * ends, this will be an infinite loop! diff --git a/src/main/java/frc/robot/Constants.java b/src/main/java/frc/robot/Constants.java index 3f49a88..d7ed8b5 100644 --- a/src/main/java/frc/robot/Constants.java +++ b/src/main/java/frc/robot/Constants.java @@ -6,22 +6,27 @@ import static edu.wpi.first.units.Units.*; +import com.ctre.phoenix6.CANBus; import edu.wpi.first.apriltag.AprilTagFieldLayout; import edu.wpi.first.apriltag.AprilTagFields; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.system.plant.DCMotor; +import edu.wpi.first.math.util.Units; import edu.wpi.first.units.AngleUnit; import edu.wpi.first.units.AngularVelocityUnit; import edu.wpi.first.units.DistanceUnit; import edu.wpi.first.units.LinearVelocityUnit; import edu.wpi.first.units.measure.AngularAcceleration; import edu.wpi.first.units.measure.AngularVelocity; +import edu.wpi.first.units.measure.Current; import edu.wpi.first.units.measure.Frequency; import edu.wpi.first.units.measure.LinearAcceleration; import edu.wpi.first.units.measure.LinearVelocity; import edu.wpi.first.units.measure.Mass; import edu.wpi.first.units.measure.MomentOfInertia; import edu.wpi.first.units.measure.Per; +import edu.wpi.first.units.measure.Time; /** * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean @@ -32,12 +37,38 @@ * constants are needed, to reduce verbosity. */ public final class Constants { + private static final CANBus determineBus(String bus) { + if (Robot.isSimulation()) { + return new CANBus(""); + } + + return new CANBus(bus); + } + + private static final int determineID(int id) { + if (Robot.isSimulation()) { + return 20 + id; + } + + return id; + } + + public static final Time robotPeriod = Seconds.of(0.02); + public static final Frequency simNotifierFrequency = Hertz.of(200); public static class Ports { public static final int driverController = 0; } + public static class MotorConstants { + public static final DCMotor krakenX60 = + new DCMotor(12, 7.16, 374.4, 3, Units.rotationsPerMinuteToRadiansPerSecond(6065), 1); + + public static final DCMotor krakenX44 = + new DCMotor(12, 4.11, 279.1, 3, Units.rotationsPerMinuteToRadiansPerSecond(7758), 1); + } + public static class FieldConstants { public static final AprilTagFieldLayout tagLayout = AprilTagFieldLayout.loadField(AprilTagFields.k2026RebuiltWelded); @@ -58,8 +89,12 @@ public static class FieldConstants { public static class VisionConstants { public static final double singleTagStdDevsScaler = 5; + public static final double translationStdDevsScaler = 1; + public static final double thetaStdDevsScaler = 1; + public static final double ambiguityThreshold = 0.2; + // TODO: tune margins gains if time allows public static final double xBoundMargin = 0.01; public static final double yBoundMargin = 0.01; public static final double zBoundMargin = 0.01; @@ -68,8 +103,12 @@ public static class VisionConstants { public static class SwerveConstants { public static final Frequency odometryFrequency = Hertz.of(250); - public static final Mass mass = Pounds.of(136.38); - public static final MomentOfInertia moi = KilogramSquareMeters.of(0); + public static final Mass mass = Pounds.of(133.7); + public static final MomentOfInertia moi = + KilogramSquareMeters.of(0); // TODO: tune moment of inertia via smartdashboard button + + public static final Current frontSlipCurrent = + Amps.of(120); // TODO: tune front slip current, default is 120A public static final LinearVelocity driverTranslationalVelocity = MetersPerSecond.of(4); public static final AngularVelocity driverAngularVelocity = RadiansPerSecond.of(Math.PI); @@ -83,9 +122,14 @@ public static class SwerveConstants { RadiansPerSecondPerSecond.of(Math.PI * 2); public static final Per poseTranslationalkP = - MetersPerSecond.per(Meter).ofNative(0); + MetersPerSecond.per(Meter).ofNative(0); // TODO: tune pose translation kP + public static final Per poseTranslationalkD = + MetersPerSecond.per(MetersPerSecond).ofNative(0.0); + public static final Per poseRotationkP = RadiansPerSecond.per(Radian).ofNative(0); + public static final Per poseRotationkD = + RadiansPerSecond.per(RadiansPerSecond).ofNative(0); // TODO: tune pose rotation kD public static final boolean ignorePoseTolerance = true; diff --git a/src/main/java/frc/robot/Robot.java b/src/main/java/frc/robot/Robot.java index 3d19e92..159301a 100644 --- a/src/main/java/frc/robot/Robot.java +++ b/src/main/java/frc/robot/Robot.java @@ -4,9 +4,12 @@ package frc.robot; -import static edu.wpi.first.units.Units.*; -import static edu.wpi.first.wpilibj2.command.Commands.*; -import static edu.wpi.first.wpilibj2.command.button.RobotModeTriggers.*; +import static edu.wpi.first.units.Units.MetersPerSecond; +import static edu.wpi.first.units.Units.RadiansPerSecond; +import static edu.wpi.first.units.Units.Seconds; +import static edu.wpi.first.wpilibj2.command.Commands.runOnce; +import static edu.wpi.first.wpilibj2.command.Commands.sequence; +import static edu.wpi.first.wpilibj2.command.button.RobotModeTriggers.autonomous; import choreo.auto.AutoChooser; import com.ctre.phoenix6.SignalLogger; @@ -17,19 +20,22 @@ import edu.wpi.first.epilogue.logging.EpilogueBackend; import edu.wpi.first.epilogue.logging.FileBackend; import edu.wpi.first.epilogue.logging.NTEpilogueBackend; +import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.util.ClassPreloader; import edu.wpi.first.wpilibj.DataLogManager; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobotBase; +import edu.wpi.first.wpilibj.PowerDistribution; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.Watchdog; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandScheduler; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; -import frc.lib.FaultLogger; -import frc.lib.FaultsTable.FaultType; +import frc.lib.GcStatsCollector; import frc.lib.InputStream; +import frc.lib.fault.FaultLogger; +import frc.lib.fault.FaultsTable.FaultType; import frc.robot.Constants.Ports; import frc.robot.Constants.SwerveConstants; import frc.robot.commands.Autos; @@ -56,6 +62,8 @@ public class Robot extends TimedRobot { private final NetworkTableInstance _ntInst; + private final GcStatsCollector _gcStatsCollector = new GcStatsCollector(); + private boolean _fileOnlySet = false; /** @@ -71,16 +79,17 @@ public Robot() { * initialization code. */ public Robot(NetworkTableInstance ntInst) { + super(Constants.robotPeriod.in(Seconds)); _ntInst = ntInst; // set up loggers - DogLog.setOptions(DogLog.getOptions().withCaptureDs(true)); - // DogLog.setPdh(new PowerDistribution()); // TODO: get ts to work + DogLog.setOptions(DogLog.getOptions().withCaptureDs(true).withNtTunables(true)); + DogLog.setPdh(new PowerDistribution()); setFileOnly(false); // file-only once connected to fms Epilogue.bind(this); - SignalLogger.start(); // TODO: log canivore can data as well + SignalLogger.start(); DriverStation.silenceJoystickConnectionWarning(isSimulation()); @@ -88,8 +97,14 @@ public Robot(NetworkTableInstance ntInst) { configureDriverBindings(); + SmartDashboard.putData( + "Reset Pose", runOnce(() -> _swerve.resetPose(Pose2d.kZero)).ignoringDisable(true)); + SmartDashboard.putData("Reset Heading", _swerve.resetHeading()); + + SmartDashboard.putData("Toggle Field Oriented", _swerve.toggleFieldOriented()); + SmartDashboard.putData("Wheel Radius Characterization", _swerve.wheelRadiusCharacterization()); - SmartDashboard.putData("Calculate Wheel COF", _swerve.calculateWheelCOF()); + SmartDashboard.putData("Calculate Chassis MOI", _swerve.calculateMOI()); SmartDashboard.putData( "Calculate Motor Max Speed And Torque", _swerve.calculateMotorMaxSpeedAndTorque()); @@ -104,13 +119,10 @@ public Robot(NetworkTableInstance ntInst) { SmartDashboard.putData( runOnce(FaultLogger::clear).ignoringDisable(true).withName("Clear Faults")); - - addPeriodic(FaultLogger::update, 1); + // addPeriodic(FaultLogger::update, 1); AutoChooser chooser = new AutoChooser(); - chooser.addRoutine("Example", _autos::example); - SmartDashboard.putData("Auto Chooser", chooser); autonomous().whileTrue(chooser.selectedCommandScheduler()); @@ -161,25 +173,23 @@ private void setFileOnly(boolean fileOnly) { } private void configureDriverBindings() { + final InputStream baseVelX = + InputStream.of(_driverController::getLeftY).deadband(0.02, 1).negate().signedPow(2); + + final InputStream baseVelY = + InputStream.of(_driverController::getLeftX).deadband(0.02, 1).negate().signedPow(2); + + final InputStream baseVelOmega = + InputStream.of(_driverController::getRightX).deadband(0.02, 1).negate().signedPow(2); + _swerve.setDefaultCommand( _swerve .drive( - InputStream.of(_driverController::getLeftY) - .deadband(0.02, 1) - .negate() - .signedPow(2) - .scale(SwerveConstants.driverTranslationalVelocity.in(MetersPerSecond)), - InputStream.of(_driverController::getLeftX) - .deadband(0.02, 1) - .negate() - .signedPow(2) - .scale(SwerveConstants.driverTranslationalVelocity.in(MetersPerSecond)), - InputStream.of(_driverController::getRightX) - .deadband(0.02, 1) - .negate() - .signedPow(2) - .scale(SwerveConstants.driverAngularVelocity.in(RadiansPerSecond))) - .beforeStarting(() -> _swerve.isOpenLoop = true)); + baseVelX.scale(SwerveConstants.driverTranslationalVelocity.in(MetersPerSecond)), + baseVelY.scale(SwerveConstants.driverTranslationalVelocity.in(MetersPerSecond)), + baseVelOmega.scale(SwerveConstants.driverAngularVelocity.in(RadiansPerSecond))) + .beforeStarting(() -> _swerve.isOpenLoop = true) + .withName("Drive")); _driverController.x().whileTrue(_swerve.brake()); _driverController.a().onTrue(_swerve.toggleFieldOriented()); @@ -209,6 +219,8 @@ public void robotPeriodic() { _fileOnlySet = true; } + _gcStatsCollector.update(); + DogLog.timeEnd("Timing/Robot/robotPeriodic()"); DogLog.timeEnd("Timing/Robot/Full Loop"); diff --git a/src/main/java/frc/robot/generated/TunerConstants.java b/src/main/java/frc/robot/generated/TunerConstants.java index 9421859..29beea2 100644 --- a/src/main/java/frc/robot/generated/TunerConstants.java +++ b/src/main/java/frc/robot/generated/TunerConstants.java @@ -14,7 +14,7 @@ import edu.wpi.first.units.measure.*; import frc.robot.subsystems.Swerve; -// Generated by the Tuner X Swerve Project Generator +// Generated by the 2026 Tuner X Swerve Project Generator // https://v6.docs.ctr-electronics.com/en/stable/docs/tuner/tuner-swerve/index.html public class TunerConstants { // Both sets of gains need to be tuned to your individual robot. @@ -23,17 +23,22 @@ public class TunerConstants { // output type specified by SwerveModuleConstants.SteerMotorClosedLoopOutput private static final SlotConfigs steerGains = new SlotConfigs() - .withKP(100) + .withKP(190) .withKI(0) - .withKD(0.5) - .withKS(0.1) - .withKV(1.91) + .withKD(2) + .withKS(0.31) + .withKV(2.49) .withKA(0) .withStaticFeedforwardSign(StaticFeedforwardSignValue.UseClosedLoopSign); // When using closed-loop control, the drive motor uses the control // output type specified by SwerveModuleConstants.DriveMotorClosedLoopOutput private static final Slot0Configs driveGains = - new Slot0Configs().withKP(0.1).withKI(0).withKD(0).withKS(0).withKV(0.124); + new Slot0Configs() + .withKP(0.1) + .withKI(0) + .withKD(0) + .withKS(0.07311) + .withKV(0.11683); // TODO: Tune drive gains // The closed-loop output type to use for the steer motors; // This affects the PID/FF gains for the steer motors @@ -51,46 +56,62 @@ public class TunerConstants { // The remote sensor feedback type to use for the steer motors; // When not Pro-licensed, Fused*/Sync* automatically fall back to Remote* - private static final SteerFeedbackType kSteerFeedbackType = SteerFeedbackType.FusedCANcoder; + private static final SteerFeedbackType kSteerFeedbackType = SteerFeedbackType.RemoteCANcoder; - // The stator current at which the wheels start to slip; + // The stator current at which the wheelskim start to slip; // This needs to be tuned to your individual robot - private static final Current kSlipCurrent = Amps.of(120.0); + private static final Current kSlipCurrent = Amps.of(80); // TODO: Tune slip current, default 120A // Initial configs for the drive and steer motors and the azimuth encoder; these cannot be null. // Some configs will be overwritten; check the `with*InitialConfigs()` API documentation. - private static final TalonFXConfiguration driveInitialConfigs = new TalonFXConfiguration(); + private static final TalonFXConfiguration driveInitialConfigs = + new TalonFXConfiguration() + .withCurrentLimits( + new CurrentLimitsConfigs() + .withSupplyCurrentLimit( + Amps.of(40)) // TODO: Tune drive supply current limit, default is 70A + .withSupplyCurrentLowerTime(0) + .withSupplyCurrentLimitEnable(true)); private static final TalonFXConfiguration steerInitialConfigs = new TalonFXConfiguration() .withCurrentLimits( new CurrentLimitsConfigs() // Swerve azimuth does not require much torque output, so we can set a relatively // low - // stator current limit to help avoid brownouts without impacting performance. - .withStatorCurrentLimit(Amps.of(60.0)) - .withStatorCurrentLimitEnable(true)) + .withSupplyCurrentLimit( + Amps.of(25)) // TODO: Tune steer supply current limit, default is 70A + .withSupplyCurrentLowerTime(0) + .withSupplyCurrentLimitEnable(true)) .withClosedLoopGeneral( - new ClosedLoopGeneralConfigs().withGainSchedErrorThreshold(Degrees.of(0.1))) - .withSlot1(Slot1Configs.from(steerGains).withKS(0)); // kS=0 at gear backlash range + new ClosedLoopGeneralConfigs() + .withGainSchedErrorThreshold( + Degrees.of( + 0.5))) // TODO: tune gain schedule error threshold, default is 0.5 degrees + .withSlot1( + Slot1Configs.from(steerGains) + .withKS(0) + .withKP(0) + .withKD(0)); // kS=0 at gear backlash range + private static final CANcoderConfiguration encoderInitialConfigs = new CANcoderConfiguration(); // Configs for the Pigeon 2; leave this null to skip applying Pigeon 2 configs private static final Pigeon2Configuration pigeonConfigs = null; // CAN bus that the devices are located on; // All swerve devices must share the same CAN bus - public static final CANBus kCANBus = new CANBus("canivore", "./logs/example.hoot"); + public static final CANBus kCANBus = new CANBus("swerve"); // Theoretical free speed (m/s) at 12 V applied output; // This needs to be tuned to your individual robot - public static final LinearVelocity kSpeedAt12Volts = MetersPerSecond.of(4.54); + public static final LinearVelocity kSpeedAt12Volts = MetersPerSecond.of(5.12); // Every 1 rotation of the azimuth results in kCoupleRatio drive motor turns; // This may need to be tuned to your individual robot - private static final double kCoupleRatio = 3.8181818181818183; + private static final double kCoupleRatio = 3.857142857142857; - private static final double kDriveGearRatio = 7.363636363636365; - private static final double kSteerGearRatio = 15.42857142857143; - private static final Distance kWheelRadius = Inches.of(2.167); + private static final double kDriveGearRatio = 6.026785714285714; + private static final double kSteerGearRatio = 26.09090909090909; + private static final Distance kWheelRadius = Inches.of(1.9447); private static final boolean kInvertLeftSide = false; private static final boolean kInvertRightSide = true; @@ -139,48 +160,48 @@ public class TunerConstants { .withDriveFrictionVoltage(kDriveFrictionVoltage); // Front Left - private static final int kFrontLeftDriveMotorId = 3; + private static final int kFrontLeftDriveMotorId = 1; private static final int kFrontLeftSteerMotorId = 2; private static final int kFrontLeftEncoderId = 1; - private static final Angle kFrontLeftEncoderOffset = Rotations.of(0.15234375); - private static final boolean kFrontLeftSteerMotorInverted = true; + private static final Angle kFrontLeftEncoderOffset = Rotations.of(0.146973); + private static final boolean kFrontLeftSteerMotorInverted = false; private static final boolean kFrontLeftEncoderInverted = false; - private static final Distance kFrontLeftXPos = Inches.of(10); - private static final Distance kFrontLeftYPos = Inches.of(10); + private static final Distance kFrontLeftXPos = Inches.of(8.875); + private static final Distance kFrontLeftYPos = Inches.of(8.875); // Front Right - private static final int kFrontRightDriveMotorId = 1; - private static final int kFrontRightSteerMotorId = 0; - private static final int kFrontRightEncoderId = 0; - private static final Angle kFrontRightEncoderOffset = Rotations.of(-0.4873046875); - private static final boolean kFrontRightSteerMotorInverted = true; + private static final int kFrontRightDriveMotorId = 3; + private static final int kFrontRightSteerMotorId = 4; + private static final int kFrontRightEncoderId = 2; + private static final Angle kFrontRightEncoderOffset = Rotations.of(0.188477); + private static final boolean kFrontRightSteerMotorInverted = false; private static final boolean kFrontRightEncoderInverted = false; - private static final Distance kFrontRightXPos = Inches.of(10); - private static final Distance kFrontRightYPos = Inches.of(-10); + private static final Distance kFrontRightXPos = Inches.of(8.875); + private static final Distance kFrontRightYPos = Inches.of(-8.875); // Back Left - private static final int kBackLeftDriveMotorId = 7; + private static final int kBackLeftDriveMotorId = 5; private static final int kBackLeftSteerMotorId = 6; private static final int kBackLeftEncoderId = 3; - private static final Angle kBackLeftEncoderOffset = Rotations.of(-0.219482421875); - private static final boolean kBackLeftSteerMotorInverted = true; + private static final Angle kBackLeftEncoderOffset = Rotations.of(-0.005127); + private static final boolean kBackLeftSteerMotorInverted = false; private static final boolean kBackLeftEncoderInverted = false; - private static final Distance kBackLeftXPos = Inches.of(-10); - private static final Distance kBackLeftYPos = Inches.of(10); + private static final Distance kBackLeftXPos = Inches.of(-8.875); + private static final Distance kBackLeftYPos = Inches.of(8.875); // Back Right - private static final int kBackRightDriveMotorId = 5; - private static final int kBackRightSteerMotorId = 4; - private static final int kBackRightEncoderId = 2; - private static final Angle kBackRightEncoderOffset = Rotations.of(0.17236328125); - private static final boolean kBackRightSteerMotorInverted = true; + private static final int kBackRightDriveMotorId = 7; + private static final int kBackRightSteerMotorId = 8; + private static final int kBackRightEncoderId = 4; + private static final Angle kBackRightEncoderOffset = Rotations.of(-0.392334); + private static final boolean kBackRightSteerMotorInverted = false; private static final boolean kBackRightEncoderInverted = false; - private static final Distance kBackRightXPos = Inches.of(-10); - private static final Distance kBackRightYPos = Inches.of(-10); + private static final Distance kBackRightXPos = Inches.of(-8.875); + private static final Distance kBackRightYPos = Inches.of(-8.875); public static final SwerveModuleConstants< TalonFXConfiguration, TalonFXConfiguration, CANcoderConfiguration> @@ -290,9 +311,9 @@ public TunerSwerveDrivetrain( * @param odometryUpdateFrequency The frequency to run the odometry loop. If unspecified or set * to 0 Hz, this is 250 Hz on CAN FD, and 100 Hz on CAN 2.0. * @param odometryStandardDeviation The standard deviation for odometry calculation in the form - * [x, y, theta]ᵀ, with units in meters and radians + * [x, y, theta]áµ€, with units in meters and radians * @param visionStandardDeviation The standard deviation for vision calculation in the form [x, - * y, theta]ᵀ, with units in meters and radians + * y, theta]áµ€, with units in meters and radians * @param modules Constants for each specific module */ public TunerSwerveDrivetrain( diff --git a/src/main/java/frc/robot/subsystems/Swerve.java b/src/main/java/frc/robot/subsystems/Swerve.java index 27efcff..0c04b96 100644 --- a/src/main/java/frc/robot/subsystems/Swerve.java +++ b/src/main/java/frc/robot/subsystems/Swerve.java @@ -10,19 +10,20 @@ import choreo.trajectory.SwerveSample; import com.ctre.phoenix6.SignalLogger; import com.ctre.phoenix6.Utils; +import com.ctre.phoenix6.configs.CurrentLimitsConfigs; import com.ctre.phoenix6.hardware.CANcoder; import com.ctre.phoenix6.hardware.TalonFX; import com.ctre.phoenix6.swerve.SwerveDrivetrainConstants; import com.ctre.phoenix6.swerve.SwerveModule; import com.ctre.phoenix6.swerve.SwerveModule.DriveRequestType; import com.ctre.phoenix6.swerve.SwerveModuleConstants; -import com.ctre.phoenix6.swerve.SwerveRequest; import com.ctre.phoenix6.swerve.SwerveRequest.*; import com.ctre.phoenix6.swerve.utility.WheelForceCalculator.Feedforwards; import dev.doglog.DogLog; import edu.wpi.first.epilogue.Logged; -import edu.wpi.first.epilogue.Logged.Strategy; +import edu.wpi.first.math.MathUtil; import edu.wpi.first.math.VecBuilder; +import edu.wpi.first.math.filter.LinearFilter; import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Pose3d; @@ -31,6 +32,7 @@ import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.util.Units; +import edu.wpi.first.networktables.DoubleArraySubscriber; import edu.wpi.first.networktables.DoubleSubscriber; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.units.measure.AngularAcceleration; @@ -44,20 +46,23 @@ import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.Subsystem; import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine; -import frc.lib.FaultLogger; -import frc.lib.FaultsTable; -import frc.lib.FaultsTable.Fault; -import frc.lib.FaultsTable.FaultType; import frc.lib.InputStream; -import frc.lib.SelfChecked; +import frc.lib.SysId; +import frc.lib.fault.FaultLogger; +import frc.lib.fault.FaultsTable; +import frc.lib.fault.FaultsTable.Fault; +import frc.lib.fault.FaultsTable.FaultType; +import frc.lib.math.TimeoutLinearFilter; +import frc.lib.subsystem.SelfChecked; +import frc.lib.util.CTREUtil; import frc.robot.Constants; import frc.robot.Constants.FieldConstants; +import frc.robot.Constants.MotorConstants; import frc.robot.Constants.SwerveConstants; import frc.robot.Robot; import frc.robot.generated.TunerConstants; import frc.robot.generated.TunerConstants.TunerSwerveDrivetrain; import frc.robot.utils.HolonomicController; -import frc.robot.utils.SysId; import frc.robot.utils.VisionPoseEstimator; import frc.robot.utils.VisionPoseEstimator.VisionPoseEstimate; import java.util.ArrayList; @@ -67,7 +72,6 @@ import java.util.function.Supplier; import org.photonvision.simulation.VisionSystemSim; -@Logged(strategy = Strategy.OPT_IN) public class Swerve extends TunerSwerveDrivetrain implements Subsystem, SelfChecked { // teleop requests private final RobotCentric _robotCentricRequest = new RobotCentric(); @@ -78,9 +82,18 @@ public class Swerve extends TunerSwerveDrivetrain implements Subsystem, SelfChec // auton request for choreo / pose controller private final ApplyFieldSpeeds _fieldSpeedsRequest = new ApplyFieldSpeeds(); - private final HolonomicController _poseController = + @Logged(name = "Holonomic Controller") + private final HolonomicController _holonomicController = new HolonomicController(getKinematics().getModules()); + // for drive facing / follow-trajectory-facing: a fixed-timestep omega feedforward, damped so a + // stale or discontinuous heading target doesn't cause a spike. The filter self-resets if it + // hasn't been called in 2 seconds, so no explicit reset is needed when these commands start. + private final TimeoutLinearFilter _omegaFeedforwardFilter = + new TimeoutLinearFilter( + LinearFilter.singlePoleIIR(0.1, Constants.robotPeriod.in(Seconds)), 2); + private Rotation2d _previousRotationSetpoint = Rotation2d.kZero; + private double _lastSimTime = 0; private Notifier _simNotifier; @@ -88,17 +101,12 @@ public class Swerve extends TunerSwerveDrivetrain implements Subsystem, SelfChec private Set _faults = new HashSet(); private FaultsTable _faultsTable = new FaultsTable( - NetworkTableInstance.getDefault().getTable("Self Check"), - getName() + " Faults"); // TODO: watch out unit tests - + NetworkTableInstance.getDefault().getTable("SelfChecked"), getName() + " Faults"); private boolean _hasError = false; - private final SwerveRequest.SysIdSwerveTranslation _translationCharacterization = - new SwerveRequest.SysIdSwerveTranslation(); - private final SwerveRequest.SysIdSwerveSteerGains _steerCharacterization = - new SwerveRequest.SysIdSwerveSteerGains(); - private final SwerveRequest.SysIdSwerveRotation _rotationCharacterization = - new SwerveRequest.SysIdSwerveRotation(); + private final SysIdSwerveTranslation _translationCharacterization = new SysIdSwerveTranslation(); + private final SysIdSwerveSteerGains _steerCharacterization = new SysIdSwerveSteerGains(); + private final SysIdSwerveRotation _rotationCharacterization = new SysIdSwerveRotation(); private final SysIdRoutine _translationRoutine = new SysIdRoutine( @@ -148,9 +156,6 @@ public class Swerve extends TunerSwerveDrivetrain implements Subsystem, SelfChec @Logged(name = "Is Open Loop") public boolean isOpenLoop = true; - @Logged(name = "Driver Chassis Speeds") - private final ChassisSpeeds _driverChassisSpeeds = new ChassisSpeeds(); - @Logged(name = "Ignore Vision Estimates") private boolean _ignoreVisionEstimates = false; @@ -181,6 +186,28 @@ public Swerve( SwerveModuleConstants... moduleConstants) { super(drivetrainConstants, SwerveConstants.odometryFrequency.in(Hertz), moduleConstants); + // front modules see the most weight transfer under acceleration and are prone to slipping + // before the rest of the chassis; give them a tighter stator current limit than tuner's + // shared slip current so they don't overpower the rear modules under hard starts + final var frontLeftDriveConfigurator = getModule(0).getDriveMotor().getConfigurator(); + final var frontRightDriveConfigurator = getModule(1).getDriveMotor().getConfigurator(); + + 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()); + + CTREUtil.attempt( + () -> frontRightDriveConfigurator.refresh(currentLimitConfigs), + getModule(1).getDriveMotor()); + currentLimitConfigs.StatorCurrentLimit = SwerveConstants.frontSlipCurrent.in(Amps); + CTREUtil.attempt( + () -> frontRightDriveConfigurator.apply(currentLimitConfigs), getModule(1).getDriveMotor()); + _robotCentricRequest .withDeadband(SwerveConstants.translationalDeadband) .withRotationalDeadband(SwerveConstants.rotationalDeadband); @@ -242,12 +269,12 @@ public final String currentCommandName() { } /** Adds a new fault under this subsystem. */ - private final void addFault(String description, FaultType faultType) { + public final void addFault(String description, FaultType faultType) { _hasError = (faultType == FaultType.ERROR); Fault fault = new Fault(description, faultType); - DogLog.logFault(fault.toString()); + DogLog.logFault(fault.toString(), null); _faults.add(fault); _faultsTable.set(_faults); @@ -330,20 +357,23 @@ public Command brake() { /** Resets the heading to face away from the alliance wall. */ public Command resetHeading() { return runOnce( - () -> { - Rotation2d rotation = - DriverStation.getAlliance() - .map( - allianceColor -> - allianceColor == Alliance.Red ? Rotation2d.k180deg : Rotation2d.kZero) - .orElse(Rotation2d.kZero); - - resetPose(new Pose2d(getPose().getTranslation(), rotation)); - }); + () -> { + Rotation2d rotation = + DriverStation.getAlliance() + .map( + allianceColor -> + allianceColor == Alliance.Red ? Rotation2d.k180deg : Rotation2d.kZero) + .orElse(Rotation2d.kZero); + + resetPose(new Pose2d(getPose().getTranslation(), rotation)); + }) + .ignoringDisable(true) + .withName("Reset Heading"); } /** - * Creates a new command that drives the chassis in teleop. + * Drives the chassis in teleop. Open loop / field oriented behavior is configured with {@link + * #isOpenLoop} and {@link #isFieldOriented}. * * @param velX The x velocity in meters per second. * @param velY The y velocity in meters per second. @@ -351,41 +381,64 @@ public Command resetHeading() { */ public Command drive(InputStream velX, InputStream velY, InputStream velOmega) { return run(() -> { - drive(velX.get(), velY.get(), velOmega.get()); + if (isFieldOriented) { + setControl( + _fieldCentricRequest + .withVelocityX(velX.get()) + .withVelocityY(velY.get()) + .withRotationalRate(velOmega.get()) + .withDriveRequestType( + isOpenLoop ? DriveRequestType.OpenLoopVoltage : DriveRequestType.Velocity)); + } else { + setControl( + _robotCentricRequest + .withVelocityX(velX.get()) + .withVelocityY(velY.get()) + .withRotationalRate(velOmega.get()) + .withDriveRequestType( + isOpenLoop ? DriveRequestType.OpenLoopVoltage : DriveRequestType.Velocity)); + } }) .withName("Drive"); } /** - * Drives the chassis in teleop. Open loop / field oriented behavior is configured with {@link - * #isOpenLoop} and {@link #isFieldOriented}. + * Drives the chassis in teleop, with the chassis fixed at a supplied heading. Open loop / field + * oriented behavior is configured with {@link #isOpenLoop} and {@link #isFieldOriented}. * * @param velX The x velocity in meters per second. * @param velY The y velocity in meters per second. - * @param velOmega The rotational velocity in radians per second. + * @param heading The heading the chassis should drive at. */ - public void drive(double velX, double velY, double velOmega) { - _driverChassisSpeeds.vxMetersPerSecond = velX; - _driverChassisSpeeds.vyMetersPerSecond = velY; - _driverChassisSpeeds.omegaRadiansPerSecond = velOmega; - - if (isFieldOriented) { - setControl( - _fieldCentricRequest - .withVelocityX(velX) - .withVelocityY(velY) - .withRotationalRate(velOmega) - .withDriveRequestType( - isOpenLoop ? DriveRequestType.OpenLoopVoltage : DriveRequestType.Velocity)); - } else { - setControl( - _robotCentricRequest - .withVelocityX(velX) - .withVelocityY(velY) - .withRotationalRate(velOmega) - .withDriveRequestType( - isOpenLoop ? DriveRequestType.OpenLoopVoltage : DriveRequestType.Velocity)); - } + public Command driveFacing(InputStream velX, InputStream velY, Supplier heading) { + return drive( + velX, + velY, + () -> { + double omegaFeedforward = + MathUtil.inputModulus( + heading.get().getRadians() - _previousRotationSetpoint.getRadians(), + -Math.PI, + Math.PI) + / Constants.robotPeriod.in(Seconds); + + // filter out spikes in heading.get() derivative + omegaFeedforward = _omegaFeedforwardFilter.calculate(omegaFeedforward); + _previousRotationSetpoint = heading.get(); + + return _holonomicController.calculate( + new Pose2d(getPose().getTranslation(), heading.get()), getPose()) + .omegaRadiansPerSecond + + omegaFeedforward; + }) + .beforeStarting( + runOnce( + () -> { + isOpenLoop = false; + + _holonomicController.useFilteringHeading(true); + })) + .withName("Drive Facing"); } /** @@ -394,10 +447,13 @@ public void drive(double velX, double velY, double velOmega) { * @param sample The SwerveSample. */ public void followTrajectory(SwerveSample sample) { - var desiredSpeeds = sample.getChassisSpeeds(); - var desiredPose = sample.getPose(); + _holonomicController.useFilteringTranslation(false); + _holonomicController.useFilteringHeading(false); - desiredSpeeds = _poseController.calculate(desiredSpeeds, desiredPose, getPose()); + ChassisSpeeds desiredSpeeds = sample.getChassisSpeeds(); + Pose2d desiredPose = sample.getPose(); + + desiredSpeeds = _holonomicController.calculate(desiredSpeeds, desiredPose, getPose()); setControl( _fieldSpeedsRequest @@ -406,6 +462,44 @@ public void followTrajectory(SwerveSample sample) { .withWheelForceFeedforwardsY(sample.moduleForcesY())); } + /** + * 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. + * + * @param sample The SwerveSample. + * @param heading Heading to follow. + */ + public void followTrajectoryFacing(SwerveSample sample, Rotation2d heading) { + _holonomicController.useFilteringTranslation(false); + _holonomicController.useFilteringHeading(true); + + ChassisSpeeds desiredSpeeds = sample.getChassisSpeeds(); + + desiredSpeeds.omegaRadiansPerSecond = + MathUtil.inputModulus( + heading.getRadians() - _previousRotationSetpoint.getRadians(), -Math.PI, Math.PI) + / Constants.robotPeriod.in(Seconds); + + // filter out spikes in heading derivative + desiredSpeeds.omegaRadiansPerSecond = + _omegaFeedforwardFilter.calculate(desiredSpeeds.omegaRadiansPerSecond); + _previousRotationSetpoint = heading; + + desiredSpeeds = + _holonomicController.calculate( + desiredSpeeds, new Pose2d(sample.x, sample.y, heading), getPose()); + + // assume shot heading second deriv is low (and choreo accel is low) and set alpha to 0 + Feedforwards sampleLinearForces = + _holonomicController.getWheelForceCalculator().calculate(sample.ax, sample.ay, 0); + + setControl( + _fieldSpeedsRequest + .withSpeeds(desiredSpeeds) + .withWheelForceFeedforwardsX(sampleLinearForces.x_newtons) + .withWheelForceFeedforwardsY(sampleLinearForces.y_newtons)); + } + /** Drives the robot in a straight line to some given goal pose. */ public Command driveTo(Pose2d goalPose) { return driveTo(() -> goalPose); @@ -414,22 +508,31 @@ public Command driveTo(Pose2d goalPose) { /** Drives the robot in a straight line to some given goal pose. */ public Command driveTo(Supplier goalPose) { return run(() -> { - ChassisSpeeds speeds = _poseController.calculate(getPose()); - Feedforwards wheelForces = _poseController.getWheelForces(); + _holonomicController.nextSetpoint(getHeading()); + + ChassisSpeeds desiredSpeeds = + _holonomicController.calculate( + _holonomicController.getSetpointSpeeds(), + _holonomicController.getSetpointPose(), + getPose()); setControl( _fieldSpeedsRequest - .withSpeeds(speeds) - .withWheelForceFeedforwardsX(wheelForces.x_newtons) - .withWheelForceFeedforwardsY(wheelForces.y_newtons)); + .withSpeeds(desiredSpeeds) + .withWheelForceFeedforwardsX(_holonomicController.getWheelForces().x_newtons) + .withWheelForceFeedforwardsY(_holonomicController.getWheelForces().y_newtons)); }) .beforeStarting( - () -> - _poseController.reset( - getPose(), - goalPose.get(), - ChassisSpeeds.fromRobotRelativeSpeeds(getChassisSpeeds(), getHeading()))) - .until(_poseController::isFinished) + () -> { + _holonomicController.useFilteringTranslation(false); + _holonomicController.useFilteringHeading(false); + + _holonomicController.reset( + getPose(), + goalPose.get(), + ChassisSpeeds.fromRobotRelativeSpeeds(getChassisSpeeds(), getHeading())); + }) + .until(_holonomicController::isFinished) .withName("Drive To"); } @@ -524,60 +627,45 @@ public void periodic() { }); } + DogLog.log(getName() + "/Current Command", currentCommandName()); + DogLog.log(getName() + "/Has Error", _hasError); + DogLog.timeEnd("Timing/Swerve/periodic()"); } @Override public void simulationPeriodic() { - _visionSystemSim.update(getPose()); // TODO: odom only? + _visionSystemSim.update(getPose()); } - /** Calculates the chassis MOI given angular chassis kA in volts/rad/s^2. */ + /** Calculates the chassis MOI given angular chassis kA in volts/rad/s^2 per each module. */ public Command calculateMOI() { - final Distance driveRadius = - Meters.of( - Math.sqrt( - Math.pow(TunerConstants.FrontLeft.LocationX, 2) - + Math.pow(TunerConstants.FrontLeft.LocationY, 2))); + // volts/rad/s^2 for each individual drive motor in the correct order + final DoubleArraySubscriber angularkAPerModule = + DogLog.tunable("Calculator/Angular kA Per Module", new double[4]); - final DoubleSubscriber angularkA = DogLog.tunable("Angular kA", 1.0); + final DCMotor driveMotor = MotorConstants.krakenX60; return Commands.runOnce( () -> { - DCMotor driveMotor = DCMotor.getKrakenX60(1); + double chassisTorque = 0; - double chassisTorque = - (driveMotor.getTorque(driveMotor.getCurrent(0, angularkA.get())) - * TunerConstants.FrontLeft.DriveMotorGearRatio - / TunerConstants.FrontLeft.WheelRadius) - * driveRadius.in(Meters) - * 4; - double MOI = chassisTorque / 1.0; + for (int module = 0; module < 4; module++) { + double moduleToCenter = getModuleLocations()[module].getNorm(); + double moduleForce = + driveMotor.getTorque(driveMotor.getCurrent(0, angularkAPerModule.get()[module])) + * TunerConstants.FrontLeft.DriveMotorGearRatio + / TunerConstants.FrontLeft.WheelRadius; - FaultLogger.report("Chassis MOI: " + MOI, FaultType.INFO); - }) - .ignoringDisable(true) - .withName("Calculate Chassis MOI"); - } - - /** Calculates the drive wheel coefficient of static friction. */ - public Command calculateWheelCOF() { - return Commands.runOnce( - () -> { - DCMotor driveMotor = DCMotor.getKrakenX60(1); - - double totalFrictionForce = - (driveMotor.getTorque(TunerConstants.FrontLeft.SlipCurrent) - * TunerConstants.FrontLeft.DriveMotorGearRatio - / TunerConstants.FrontLeft.WheelRadius) - * 4; + chassisTorque += moduleForce * moduleToCenter; + } - double cof = totalFrictionForce / (SwerveConstants.mass.in(Kilograms) * 9.81); + double MOI = chassisTorque; // since α = 1, I = τ - FaultLogger.report("Drive Wheel COF: " + cof, FaultType.INFO); + FaultLogger.report("Chassis MOI: " + MOI, FaultType.INFO); }) .ignoringDisable(true) - .withName("Calculate Wheel COF"); + .withName("Calculate Chassis MOI"); } /** @@ -586,17 +674,39 @@ public Command calculateWheelCOF() { */ public Command calculateMotorMaxSpeedAndTorque() { // percentage of max achievable speed and torque, leaving headroom for pose PID - final double headroom = 0.80; + final DoubleSubscriber headroom = DogLog.tunable("Calculator/Headroom", .8); + + final DCMotor driveMotor = MotorConstants.krakenX60; + + final CurrentLimitsConfigs currentLimitsConfigs = new CurrentLimitsConfigs(); return Commands.runOnce( () -> { - DCMotor driveMotor = DCMotor.getKrakenX60(1); - double maxSpeed = Units.radiansPerSecondToRotationsPerMinute( - driveMotor.freeSpeedRadPerSec * headroom); - double maxTorque = - driveMotor.getTorque(TunerConstants.FrontLeft.SlipCurrent) * headroom; + driveMotor.freeSpeedRadPerSec * headroom.get()); + + double maxTorque = 0; + + for (var module : getModules()) { + var failed = + CTREUtil.attempt( + () -> + module.getDriveMotor().getConfigurator().refresh(currentLimitsConfigs), + module.getDriveMotor()); + + if (failed) { + FaultLogger.report( + "Failed to calculate motor max torque! Make sure all drive motors are connected.", + FaultType.ERROR); + return; + } + + maxTorque += + driveMotor.getTorque(currentLimitsConfigs.StatorCurrentLimit) * headroom.get(); + } + + maxTorque /= 4; FaultLogger.report( "Motor Max Speed (rpm): " + maxSpeed + ", Motor Max Torque: " + maxTorque, @@ -696,7 +806,6 @@ public Command wheelRadiusCharacterization() { .withName("Wheel Radius Characterization"); } - // TODO: add self check routines private Command selfCheckModule(String name, SwerveModule module) { return shiftSequence(); } diff --git a/src/main/java/frc/robot/utils/HolonomicController.java b/src/main/java/frc/robot/utils/HolonomicController.java index d3ec532..8bece58 100644 --- a/src/main/java/frc/robot/utils/HolonomicController.java +++ b/src/main/java/frc/robot/utils/HolonomicController.java @@ -5,9 +5,9 @@ import com.ctre.phoenix6.swerve.utility.WheelForceCalculator; import com.ctre.phoenix6.swerve.utility.WheelForceCalculator.Feedforwards; import dev.doglog.DogLog; +import edu.wpi.first.epilogue.Logged; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.Vector; -import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.controller.ProfiledPIDController; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; @@ -15,10 +15,19 @@ import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.numbers.N2; import edu.wpi.first.math.trajectory.TrapezoidProfile.Constraints; +import frc.lib.math.FilteredPIDController; +import frc.robot.Constants; import frc.robot.Constants.SwerveConstants; -import frc.robot.Robot; +/** + * Combines two things that both bring the chassis toward a desired pose: a motion-profiled + * "setpoint stepper" (used for straight-line driveTo moves) and a set of PID controllers that + * correct against whatever pose is actually desired at the moment (used for trajectory following + * and pose correction in general). + */ public class HolonomicController { + // pid part of these controllers is UNUSED, this class is just used since it already + // manages updating the profile setpoint and goal internally private final ProfiledPIDController _translationProfile = new ProfiledPIDController( 0, @@ -40,19 +49,37 @@ public class HolonomicController { private Vector _translationDirection = VecBuilder.fill(0, 0); private Pose2d _startPose = Pose2d.kZero; - private double _goalHeading = 0; - private final PIDController _xController = - new PIDController(SwerveConstants.poseTranslationalkP.in(MetersPerSecond.per(Meter)), 0, 0); - private final PIDController _yController = - new PIDController(SwerveConstants.poseTranslationalkP.in(MetersPerSecond.per(Meter)), 0, 0); - - private final PIDController _headingController = - new PIDController(SwerveConstants.poseRotationkP.in(RadiansPerSecond.per(Radian)), 0, 0); + private final FilteredPIDController _xController = + new FilteredPIDController( + SwerveConstants.poseTranslationalkP.in(MetersPerSecond.per(Meter)), + SwerveConstants.poseTranslationalkD.in(MetersPerSecond.per(MetersPerSecond)), + Constants.robotPeriod.in(Seconds), + 0.1); + private final FilteredPIDController _yController = + new FilteredPIDController( + SwerveConstants.poseTranslationalkP.in(MetersPerSecond.per(Meter)), + SwerveConstants.poseTranslationalkD.in(MetersPerSecond.per(MetersPerSecond)), + Constants.robotPeriod.in(Seconds), + 0.1); + + private final FilteredPIDController _headingController = + new FilteredPIDController( + SwerveConstants.poseRotationkP.in(RadiansPerSecond.per(Radian)), + SwerveConstants.poseRotationkD.in(RadiansPerSecond.per(RadiansPerSecond)), + Constants.robotPeriod.in(Seconds), + 0.1); + + // reused instead of allocating a new ChassisSpeeds every call + private final ChassisSpeeds _pidSpeeds = new ChassisSpeeds(); + private final ChassisSpeeds _zeroSpeeds = new ChassisSpeeds(); private final WheelForceCalculator _wheelForceCalculator; private Feedforwards _wheelForces = new Feedforwards(4); + private ChassisSpeeds _setpointSpeeds = new ChassisSpeeds(); + private Pose2d _setpointPose = Pose2d.kZero; + private ChassisSpeeds _prevSetpointSpeeds = new ChassisSpeeds(); /** @@ -68,27 +95,66 @@ public HolonomicController(Translation2d[] moduleLocations) { new WheelForceCalculator(moduleLocations, SwerveConstants.mass, SwerveConstants.moi); } + /** Whether r'(t) on the translation PID controllers is being filtered. */ + @Logged(name = "Is Filtering Translation") + public boolean isFilteringTranslation() { + return _xController.isFilteringSetpointVelocity() && _yController.isFilteringSetpointVelocity(); + } + + /** Sets r'(t) low-pass filtering on the translation pid controllers. */ + public void useFilteringTranslation(boolean use) { + if (use) { + _xController.enableSetpointVelocityFilter(); + _yController.enableSetpointVelocityFilter(); + } else { + _xController.disableSetpointVelocityFilter(); + _yController.disableSetpointVelocityFilter(); + } + } + + /** Whether r'(t) on the heading PID controller is being filtered. */ + @Logged(name = "Is Filtering Heading") + public boolean isFilteringHeading() { + return _headingController.isFilteringSetpointVelocity(); + } + + /** Sets r'(t) low-pass filtering on the heading pid controller. */ + public void useFilteringHeading(boolean use) { + if (use) { + _headingController.enableSetpointVelocityFilter(); + } else { + _headingController.disableSetpointVelocityFilter(); + } + } + + /** Wheel force calculator for any external calculations. */ + public WheelForceCalculator getWheelForceCalculator() { + return _wheelForceCalculator; + } + /** The wheel forces based on the acceleration of the profiles. */ public Feedforwards getWheelForces() { return _wheelForces; } + /** Profile setpoint speeds. */ + public ChassisSpeeds getSetpointSpeeds() { + return _setpointSpeeds; + } + + /** Profile setpoint pose. */ + public Pose2d getSetpointPose() { + return _setpointPose; + } + /** Whether the profiles have been completed or not. */ public boolean isFinished() { return _translationProfile.getSetpoint().equals(_translationProfile.getGoal()) && _headingProfile.getSetpoint().equals(_headingProfile.getGoal()); } - /** Resets the PID controllers. */ - public void reset() { - _xController.reset(); - _yController.reset(); - - _headingController.reset(); - } - /** - * Resets the profiles and the PID controllers. + * Resets the profiles. * * @param currentPose The current pose. * @param goalPose The goal pose. @@ -96,6 +162,7 @@ public void reset() { */ public void reset(Pose2d currentPose, Pose2d goalPose, ChassisSpeeds currentSpeeds) { if (!SwerveConstants.ignorePoseTolerance) { + // if the goal pose is very close to current pose on a certain axis, don't move on that axis Translation2d translationError = goalPose.getTranslation().minus(currentPose.getTranslation()); Rotation2d rotationError = goalPose.getRotation().minus(currentPose.getRotation()); @@ -121,59 +188,84 @@ public void reset(Pose2d currentPose, Pose2d goalPose, ChassisSpeeds currentSpee _translationDirection = VecBuilder.fill(goalPose.getX() - currentPose.getX(), goalPose.getY() - currentPose.getY()); + // set profile goals + _translationProfile.setGoal(_translationDirection.norm()); + _headingProfile.setGoal(goalPose.getRotation().getRadians()); + + if (_translationDirection.norm() == 0) { + // if the goal translation IS the starting translation: + // 1) if current translational speeds is not 0, direction is antiparallel to speeds + // 2) if current translational speeds is 0, profile will also be empty, so an arbitrary + // direction is used + _translationDirection = + (currentSpeeds.vxMetersPerSecond == 0 && currentSpeeds.vyMetersPerSecond == 0) + ? VecBuilder.fill(1, 0) + : VecBuilder.fill(currentSpeeds.vxMetersPerSecond, currentSpeeds.vyMetersPerSecond) + .times(-1); + } + + // reset profile setpoints _translationProfile.reset( 0, _translationDirection.dot( VecBuilder.fill(currentSpeeds.vxMetersPerSecond, currentSpeeds.vyMetersPerSecond)) / _translationDirection.norm()); + _headingProfile.reset( currentPose.getRotation().getRadians(), currentSpeeds.omegaRadiansPerSecond); - _prevSetpointSpeeds = currentSpeeds; + _setpointSpeeds = currentSpeeds; + _setpointPose = currentPose; - reset(); + _prevSetpointSpeeds = _setpointSpeeds; _startPose = currentPose; - _goalHeading = goalPose.getRotation().getRadians(); } /** - * Samples the motions profiles at the next timestep, finding chassis speeds based on the profiles - * and PID correction. + * Samples the motion profiles at the next setpoint, updating {@link #getSetpointSpeeds()}, {@link + * #getSetpointPose()}, and {@link #getWheelForces()}. * - * @param currentPose The current pose. - * @return Field-relative speeds for the chassis. + * @param currentHeading The current heading, needed for heading profile continuous-input + * calculations. */ - public ChassisSpeeds calculate(Pose2d currentPose) { - _translationProfile.calculate( - 0, - _translationDirection.norm()); // measurement doesn't matter, handled by xy PID controllers + public void nextSetpoint(Rotation2d currentHeading) { + _translationProfile.calculate(0); // measurement doesn't matter, handled by xy PID controllers _headingProfile.calculate( - currentPose.getRotation().getRadians(), _goalHeading); // TODO: why does measurement matter? + currentHeading.getRadians()); // measurement matters for cont input calculations Vector setpointPosition = _translationDirection.unit().times(_translationProfile.getSetpoint().position); Vector setpointVelocity = _translationDirection.unit().times(_translationProfile.getSetpoint().velocity); - Pose2d setpointPose = + _setpointPose = new Pose2d( _startPose.getX() + setpointPosition.get(0), _startPose.getY() + setpointPosition.get(1), new Rotation2d(_headingProfile.getSetpoint().position)); - ChassisSpeeds setpointSpeeds = - new ChassisSpeeds( - setpointVelocity.get(0), - setpointVelocity.get(1), - _headingProfile.getSetpoint().velocity); + _setpointSpeeds.vxMetersPerSecond = setpointVelocity.get(0); + _setpointSpeeds.vyMetersPerSecond = setpointVelocity.get(1); + _setpointSpeeds.omegaRadiansPerSecond = _headingProfile.getSetpoint().velocity; _wheelForces = - _wheelForceCalculator.calculate(Robot.kDefaultPeriod, _prevSetpointSpeeds, setpointSpeeds); + _wheelForceCalculator.calculate( + Constants.robotPeriod.in(Seconds), _prevSetpointSpeeds, _setpointSpeeds); - _prevSetpointSpeeds = setpointSpeeds; + _prevSetpointSpeeds = _setpointSpeeds; + } - return calculate(setpointSpeeds, setpointPose, currentPose); + /** + * Finds field-relative chassis speeds that bring the chassis closer to the desired pose, with no + * base speed to build on top of. + * + * @param desiredPose The desired pose. + * @param currentPose The current pose. + * @return New field-relative speeds. + */ + public ChassisSpeeds calculate(Pose2d desiredPose, Pose2d currentPose) { + return calculate(_zeroSpeeds, desiredPose, currentPose); } /** @@ -183,13 +275,14 @@ public ChassisSpeeds calculate(Pose2d currentPose) { * @param baseSpeeds The field-relative speed the chassis is already traveling at. * @param desiredPose The desired pose. * @param currentPose The current pose. - * @return New modified field-relative speeds. + * @return New field-relative speeds. */ public ChassisSpeeds calculate(ChassisSpeeds baseSpeeds, Pose2d desiredPose, Pose2d currentPose) { - DogLog.log("Auto/Controller Desired Pose", desiredPose); - DogLog.log("Auto/Controller Reference Pose", currentPose); + DogLog.log("Swerve/Holonomic Controller/Controller Desired Pose", desiredPose); + DogLog.log("Swerve/Holonomic Controller/Controller Actual Pose", currentPose); if (!SwerveConstants.ignorePoseTolerance) { + // if error is very small on a certain axis, don't move on that axis Translation2d translationError = desiredPose.getTranslation().minus(currentPose.getTranslation()); Rotation2d rotationError = desiredPose.getRotation().minus(currentPose.getRotation()); @@ -208,14 +301,17 @@ public ChassisSpeeds calculate(ChassisSpeeds baseSpeeds, Pose2d desiredPose, Pos : _headingController.calculate( currentPose.getRotation().getRadians(), desiredPose.getRotation().getRadians()); - return baseSpeeds.plus(new ChassisSpeeds(velX, velY, velOmega)); + _pidSpeeds.vxMetersPerSecond = velX; + _pidSpeeds.vyMetersPerSecond = velY; + _pidSpeeds.omegaRadiansPerSecond = velOmega; + } else { + _pidSpeeds.vxMetersPerSecond = _xController.calculate(currentPose.getX(), desiredPose.getX()); + _pidSpeeds.vyMetersPerSecond = _yController.calculate(currentPose.getY(), desiredPose.getY()); + _pidSpeeds.omegaRadiansPerSecond = + _headingController.calculate( + currentPose.getRotation().getRadians(), desiredPose.getRotation().getRadians()); } - return baseSpeeds.plus( - new ChassisSpeeds( - _xController.calculate(currentPose.getX(), desiredPose.getX()), - _yController.calculate(currentPose.getY(), desiredPose.getY()), - _headingController.calculate( - currentPose.getRotation().getRadians(), desiredPose.getRotation().getRadians()))); + return baseSpeeds.plus(_pidSpeeds); } } diff --git a/src/main/java/frc/robot/utils/VisionPoseEstimator.java b/src/main/java/frc/robot/utils/VisionPoseEstimator.java index 13a870c..7f3870f 100644 --- a/src/main/java/frc/robot/utils/VisionPoseEstimator.java +++ b/src/main/java/frc/robot/utils/VisionPoseEstimator.java @@ -7,12 +7,11 @@ import dev.doglog.DogLog; import edu.wpi.first.apriltag.AprilTagFieldLayout; import edu.wpi.first.epilogue.Logged; -import edu.wpi.first.epilogue.Logged.Strategy; import edu.wpi.first.math.geometry.Pose3d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Transform3d; import edu.wpi.first.networktables.NetworkTableInstance; -import frc.lib.FaultLogger; +import frc.lib.fault.FaultLogger; import frc.robot.Constants.FieldConstants; import frc.robot.Constants.VisionConstants; import frc.robot.Robot; @@ -28,7 +27,6 @@ import org.photonvision.targeting.PhotonTrackedTarget; /** Handles pose estimation coming from a single PhotonVision camera. */ -@Logged(strategy = Strategy.OPT_IN) public class VisionPoseEstimator implements AutoCloseable { /** The camera's NT name. */ @Logged(name = "Camera Name") @@ -381,10 +379,21 @@ private VisionPoseEstimate processEstimate(EstimatedRobotPose estimate, Rotation if (isValid) { double tagAmountStdDevsScaler = tagAmount == 1 ? VisionConstants.singleTagStdDevsScaler : 1; - double xStdDevs = Math.pow(avgTagDistance, 2) * tagAmountStdDevsScaler * cameraStdDevsScaler; - double yStdDevs = Math.pow(avgTagDistance, 2) * tagAmountStdDevsScaler * cameraStdDevsScaler; + double xStdDevs = + Math.pow(avgTagDistance, 2) + * tagAmountStdDevsScaler + * VisionConstants.translationStdDevsScaler + * cameraStdDevsScaler; + double yStdDevs = + Math.pow(avgTagDistance, 2) + * tagAmountStdDevsScaler + * VisionConstants.translationStdDevsScaler + * cameraStdDevsScaler; double thetaStdDevs = - Math.pow(avgTagDistance, 2) * tagAmountStdDevsScaler * cameraStdDevsScaler; + Math.pow(avgTagDistance, 2) + * tagAmountStdDevsScaler + * VisionConstants.thetaStdDevsScaler + * cameraStdDevsScaler; if (ignoreThetaEstimate) thetaStdDevs = 999999999; @@ -407,6 +416,8 @@ private VisionPoseEstimate processEstimate(EstimatedRobotPose estimate, Rotation /** Reads from the camera and generates an array of new latest {@link VisionPoseEstimate}(s). */ public void update() { + DogLog.log("Is " + camName + " Connected", _camera.isConnected()); + _newEstimates.clear(); // reset new estimates var results = _camera.getAllUnreadResults(); diff --git a/src/test/java/frc/lib/AdvancedSubsystemTest.java b/src/test/java/frc/lib/AdvancedSubsystemTest.java index d206b1c..188dd3c 100644 --- a/src/test/java/frc/lib/AdvancedSubsystemTest.java +++ b/src/test/java/frc/lib/AdvancedSubsystemTest.java @@ -5,17 +5,56 @@ package frc.lib; import static edu.wpi.first.wpilibj2.command.Commands.*; -import static frc.lib.UnitTestingUtil.*; +import static frc.lib.util.UnitTestingUtil.*; import static org.junit.jupiter.api.Assertions.*; import edu.wpi.first.wpilibj2.command.Command; -import frc.lib.FaultsTable.Fault; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultsTable.Fault; +import frc.lib.fault.FaultsTable.FaultType; +import frc.lib.subsystem.AdvancedSubsystem; +import frc.lib.util.UnitTestingUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class AdvancedSubsystemTest { + private class TestImpl extends AdvancedSubsystem { + public TestImpl() { + super(UnitTestingUtil.getNtInst()); + } + + public double speed() { + return 0; + } + + @Override + public Command selfCheck() { + return shiftSequence( + // check devices first + runOnce( + () -> { + if (true) addFault("FAULT 1", FaultType.WARNING); + }), + runOnce( + () -> { + if (true) addFault("FAULT 2", FaultType.WARNING); + }), + runOnce( + () -> { + if (true) addFault("FAULT 3", FaultType.ERROR); + }), + + // then check the subsystem + runOnce( + () -> { + if (speed() < 2) addFault("TOO SLOW", FaultType.WARNING); + })); + } + + @Override + public void close() {} + } + private TestImpl _sub; @BeforeEach @@ -95,41 +134,4 @@ public void currentCommandName() { assertEquals("Test Command", _sub.currentCommandName()); } - - public class TestImpl extends AdvancedSubsystem { - public TestImpl() { - super(UnitTestingUtil.getNtInst()); - } - - public double speed() { - return 0; - } - - @Override - public Command selfCheck() { - return shiftSequence( - // check devices first - runOnce( - () -> { - if (true) addFault("FAULT 1", FaultType.WARNING); - }), - runOnce( - () -> { - if (true) addFault("FAULT 2", FaultType.WARNING); - }), - runOnce( - () -> { - if (true) addFault("FAULT 3", FaultType.ERROR); - }), - - // then check the subsystem - runOnce( - () -> { - if (speed() < 2) addFault("TOO SLOW", FaultType.WARNING); - })); - } - - @Override - public void close() {} - } } diff --git a/src/test/java/frc/lib/CTREUtilTest.java b/src/test/java/frc/lib/CTREUtilTest.java index 346312c..ef805a1 100644 --- a/src/test/java/frc/lib/CTREUtilTest.java +++ b/src/test/java/frc/lib/CTREUtilTest.java @@ -1,14 +1,16 @@ package frc.lib; -import static frc.lib.UnitTestingUtil.*; +import static frc.lib.util.UnitTestingUtil.*; import static org.junit.jupiter.api.Assertions.*; import com.ctre.phoenix6.StatusCode; import com.ctre.phoenix6.hardware.CANcoder; import com.ctre.phoenix6.hardware.Pigeon2; import com.ctre.phoenix6.hardware.TalonFX; -import frc.lib.FaultsTable.Fault; -import frc.lib.FaultsTable.FaultType; +import frc.lib.fault.FaultLogger; +import frc.lib.fault.FaultsTable.Fault; +import frc.lib.fault.FaultsTable.FaultType; +import frc.lib.util.CTREUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,27 +42,27 @@ public void close() { public void motorName() { var name = CTREUtil.getName(_motor); - assertEquals("TalonFX (1)", name); + assertEquals("TalonFX (1 - )", name); } @Test public void gyroName() { var name = CTREUtil.getName(_gyro); - assertEquals("Pigeon (2)", name); + assertEquals("Pigeon (2 - )", name); } @Test public void encoderName() { var name = CTREUtil.getName(_encoder); - assertEquals("CANcoder (3)", name); + assertEquals("CANcoder (3 - )", name); } @Test public void attempt() { // if all names work then, attempt will work for any device - var name = "TalonFX (3)"; + var name = "TalonFX (3 - )"; var failed1 = CTREUtil.attempt(() -> StatusCode.ConfigFailed, name); var failed2 = CTREUtil.attempt(() -> StatusCode.OK, name); @@ -73,10 +75,10 @@ public void attempt() { assert FaultLogger.totalFaults() .contains( new Fault( - name + " - Config Apply Failed - " + StatusCode.ConfigFailed.getDescription(), + name + " - Action Failed - " + StatusCode.ConfigFailed.getDescription(), FaultType.ERROR)); assert FaultLogger.totalFaults() - .contains(new Fault(name + " - Config Apply Successful.", FaultType.INFO)); + .contains(new Fault(name + " - Action Successful.", FaultType.INFO)); } } diff --git a/src/test/java/frc/robot/RobotTest.java b/src/test/java/frc/robot/RobotTest.java index 16293c5..ff5de8e 100644 --- a/src/test/java/frc/robot/RobotTest.java +++ b/src/test/java/frc/robot/RobotTest.java @@ -1,6 +1,6 @@ package frc.robot; -import static frc.lib.UnitTestingUtil.*; +import static frc.lib.util.UnitTestingUtil.*; import static org.junit.jupiter.api.Assertions.*; import dev.doglog.DogLog; @@ -11,8 +11,10 @@ import edu.wpi.first.wpilibj.simulation.DriverStationSim; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +@Disabled public class RobotTest { private Robot _robot; diff --git a/src/test/java/frc/robot/VisionPoseEstimatorTest.java b/src/test/java/frc/robot/VisionPoseEstimatorTest.java index 2ab0a02..6533594 100644 --- a/src/test/java/frc/robot/VisionPoseEstimatorTest.java +++ b/src/test/java/frc/robot/VisionPoseEstimatorTest.java @@ -1,6 +1,6 @@ package frc.robot; -import static frc.lib.UnitTestingUtil.*; +import static frc.lib.util.UnitTestingUtil.*; import static org.junit.jupiter.api.Assertions.*; import edu.wpi.first.apriltag.AprilTag; diff --git a/vendordeps/ChoreoLib2026.json b/vendordeps/ChoreoLib2026.json index 322c9e2..9a106ab 100644 --- a/vendordeps/ChoreoLib2026.json +++ b/vendordeps/ChoreoLib2026.json @@ -1,7 +1,7 @@ { "fileName": "ChoreoLib2026.json", "name": "ChoreoLib", - "version": "2026.0.1", + "version": "2026.0.3", "uuid": "b5e23f0a-dac9-4ad2-8dd6-02767c520aca", "frcYear": "2026", "mavenUrls": [ @@ -13,7 +13,7 @@ { "groupId": "choreo", "artifactId": "ChoreoLib-java", - "version": "2026.0.1" + "version": "2026.0.3" }, { "groupId": "com.google.code.gson", @@ -26,7 +26,7 @@ { "groupId": "choreo", "artifactId": "ChoreoLib-cpp", - "version": "2026.0.1", + "version": "2026.0.3", "libName": "ChoreoLib", "headerClassifier": "headers", "sharedLibrary": false, diff --git a/vendordeps/DogLog.json b/vendordeps/DogLog.json index 73503e0..7201ed0 100644 --- a/vendordeps/DogLog.json +++ b/vendordeps/DogLog.json @@ -3,7 +3,7 @@ { "groupId": "com.github.jonahsnider", "artifactId": "doglog", - "version": "2026.3.1" + "version": "2026.5.0" } ], "fileName": "DogLog.json", @@ -15,6 +15,6 @@ "https://jitpack.io" ], "cppDependencies": [], - "version": "2026.3.1", + "version": "2026.5.0", "uuid": "65592ce1-2251-4a31-8e4b-2df20dacebe4" } \ No newline at end of file diff --git a/vendordeps/Phoenix6-26.1.0.json b/vendordeps/Phoenix6-26.3.0.json similarity index 92% rename from vendordeps/Phoenix6-26.1.0.json rename to vendordeps/Phoenix6-26.3.0.json index dc5dc62..0567ab3 100644 --- a/vendordeps/Phoenix6-26.1.0.json +++ b/vendordeps/Phoenix6-26.3.0.json @@ -1,7 +1,7 @@ { - "fileName": "Phoenix6-26.1.0.json", + "fileName": "Phoenix6-26.3.0.json", "name": "CTRE-Phoenix (v6)", - "version": "26.1.0", + "version": "26.3.0", "frcYear": "2026", "uuid": "e995de00-2c64-4df5-8831-c1441420ff19", "mavenUrls": [ @@ -19,14 +19,14 @@ { "groupId": "com.ctre.phoenix6", "artifactId": "wpiapi-java", - "version": "26.1.0" + "version": "26.3.0" } ], "jniDependencies": [ { "groupId": "com.ctre.phoenix6", "artifactId": "api-cpp", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -40,7 +40,7 @@ { "groupId": "com.ctre.phoenix6", "artifactId": "tools", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -54,7 +54,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "api-cpp-sim", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -68,7 +68,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "tools-sim", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -82,7 +82,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simTalonSRX", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -96,7 +96,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simVictorSPX", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -110,7 +110,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simPigeonIMU", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -124,7 +124,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProTalonFX", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -138,7 +138,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProTalonFXS", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -152,7 +152,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANcoder", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -166,7 +166,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProPigeon2", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -180,7 +180,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANrange", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -194,7 +194,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANdi", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -208,7 +208,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANdle", - "version": "26.1.0", + "version": "26.3.0", "isJar": false, "skipInvalidPlatforms": true, "validPlatforms": [ @@ -224,7 +224,7 @@ { "groupId": "com.ctre.phoenix6", "artifactId": "wpiapi-cpp", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_Phoenix6_WPI", "headerClassifier": "headers", "sharedLibrary": true, @@ -240,7 +240,7 @@ { "groupId": "com.ctre.phoenix6", "artifactId": "tools", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_PhoenixTools", "headerClassifier": "headers", "sharedLibrary": true, @@ -256,7 +256,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "wpiapi-cpp-sim", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_Phoenix6_WPISim", "headerClassifier": "headers", "sharedLibrary": true, @@ -272,7 +272,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "tools-sim", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_PhoenixTools_Sim", "headerClassifier": "headers", "sharedLibrary": true, @@ -288,7 +288,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simTalonSRX", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimTalonSRX", "headerClassifier": "headers", "sharedLibrary": true, @@ -304,7 +304,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simVictorSPX", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimVictorSPX", "headerClassifier": "headers", "sharedLibrary": true, @@ -320,7 +320,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simPigeonIMU", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimPigeonIMU", "headerClassifier": "headers", "sharedLibrary": true, @@ -336,7 +336,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProTalonFX", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProTalonFX", "headerClassifier": "headers", "sharedLibrary": true, @@ -352,7 +352,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProTalonFXS", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProTalonFXS", "headerClassifier": "headers", "sharedLibrary": true, @@ -368,7 +368,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANcoder", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProCANcoder", "headerClassifier": "headers", "sharedLibrary": true, @@ -384,7 +384,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProPigeon2", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProPigeon2", "headerClassifier": "headers", "sharedLibrary": true, @@ -400,7 +400,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANrange", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProCANrange", "headerClassifier": "headers", "sharedLibrary": true, @@ -416,7 +416,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANdi", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProCANdi", "headerClassifier": "headers", "sharedLibrary": true, @@ -432,7 +432,7 @@ { "groupId": "com.ctre.phoenix6.sim", "artifactId": "simProCANdle", - "version": "26.1.0", + "version": "26.3.0", "libName": "CTRE_SimProCANdle", "headerClassifier": "headers", "sharedLibrary": true, diff --git a/vendordeps/photonlib.json b/vendordeps/photonlib.json index a1bc5a5..6d1e817 100644 --- a/vendordeps/photonlib.json +++ b/vendordeps/photonlib.json @@ -1,7 +1,7 @@ { "fileName": "photonlib.json", "name": "photonlib", - "version": "v2026.1.1", + "version": "v2026.3.4", "uuid": "515fe07e-bfc6-11fa-b3de-0242ac130004", "frcYear": "2026", "mavenUrls": [ @@ -13,7 +13,7 @@ { "groupId": "org.photonvision", "artifactId": "photontargeting-cpp", - "version": "v2026.1.1", + "version": "v2026.3.4", "skipInvalidPlatforms": true, "isJar": false, "validPlatforms": [ @@ -28,7 +28,7 @@ { "groupId": "org.photonvision", "artifactId": "photonlib-cpp", - "version": "v2026.1.1", + "version": "v2026.3.4", "libName": "photonlib", "headerClassifier": "headers", "sharedLibrary": true, @@ -43,7 +43,7 @@ { "groupId": "org.photonvision", "artifactId": "photontargeting-cpp", - "version": "v2026.1.1", + "version": "v2026.3.4", "libName": "photontargeting", "headerClassifier": "headers", "sharedLibrary": true, @@ -60,12 +60,12 @@ { "groupId": "org.photonvision", "artifactId": "photonlib-java", - "version": "v2026.1.1" + "version": "v2026.3.4" }, { "groupId": "org.photonvision", "artifactId": "photontargeting-java", - "version": "v2026.1.1" + "version": "v2026.3.4" } ] } \ No newline at end of file