001/************************ PROJECT ZIXI ************************/ 002/* Copyright (c) 2026 StuyPulse Robotics. All rights reserved.*/ 003/* This work is licensed under the terms of the MIT license. */ 004/**************************************************************/ 005package com.stuypulse.robot.subsystems.swerve; 006 007import static org.wpilib.units.Units.*; 008 009import com.stuypulse.robot.constants.GlobalSettings; 010import com.stuypulse.robot.constants.GlobalSettings.RobotMode; 011import com.stuypulse.robot.subsystems.vision.Vision.VisionConsumer; 012import com.stuypulse.robot.util.PeriodicSubsystem; 013 014import org.wpilib.driverstation.RobotState; 015import org.wpilib.math.estimator.SwerveDrivePoseEstimator; 016import org.wpilib.math.geometry.Pose2d; 017import org.wpilib.math.geometry.Rotation2d; 018import org.wpilib.math.geometry.Translation2d; 019import org.wpilib.math.geometry.Twist2d; 020import org.wpilib.math.kinematics.ChassisVelocities; 021import org.wpilib.math.kinematics.SwerveDriveKinematics; 022import org.wpilib.math.kinematics.SwerveModulePosition; 023import org.wpilib.math.kinematics.SwerveModuleVelocity; 024import org.wpilib.util.Alert; 025import org.wpilib.util.UsageReporting; 026 027import java.util.Optional; 028import java.util.concurrent.locks.Lock; 029import java.util.concurrent.locks.ReentrantLock; 030import org.littletonrobotics.junction.AutoLogOutput; 031import org.littletonrobotics.junction.Logger; 032 033// import org.wpilib.wpilibj2.command.sysid.SysIdRoutine; 034 035public class Swerve extends PeriodicSubsystem { 036 // TunerConstants doesn't include these constants, so they are declared locally 037 static final double ODOMETRY_FREQUENCY = TunerConstants.kCANBus.isNetworkFD() ? 250.0 : 100.0; 038 public static final double DRIVE_BASE_RADIUS = 039 Math.max( 040 Math.max( 041 Math.hypot( 042 TunerConstants.FrontLeft.LocationX, 043 TunerConstants.FrontLeft.LocationY), 044 Math.hypot( 045 TunerConstants.FrontRight.LocationX, 046 TunerConstants.FrontRight.LocationY)), 047 Math.max( 048 Math.hypot( 049 TunerConstants.BackLeft.LocationX, 050 TunerConstants.BackLeft.LocationY), 051 Math.hypot( 052 TunerConstants.BackRight.LocationX, 053 TunerConstants.BackRight.LocationY))); 054 055 static final Lock odometryLock = new ReentrantLock(); 056 private final GyroIO gyroIO; 057 private final GyroIOInputsAutoLogged gyroInputs = new GyroIOInputsAutoLogged(); 058 private final Module[] modules = new Module[4]; // FL, FR, BL, BR 059 // private final SysIdRoutine sysId; 060 private final Alert gyroDisconnectedAlert = 061 new Alert( 062 "SwerveGyroDisconnect", 063 "Disconnected gyro, using kinematics as fallback.", 064 Alert.Level.HIGH); 065 066 private SwerveDriveKinematics kinematics = new SwerveDriveKinematics(getModuleTranslations()); 067 private Rotation2d rawGyroRotation = Rotation2d.ZERO; 068 private SwerveModulePosition[] lastModulePositions = // For delta tracking 069 new SwerveModulePosition[] { 070 new SwerveModulePosition(), 071 new SwerveModulePosition(), 072 new SwerveModulePosition(), 073 new SwerveModulePosition() 074 }; 075 private SwerveDrivePoseEstimator poseEstimator = 076 new SwerveDrivePoseEstimator( 077 kinematics, rawGyroRotation, lastModulePositions, Pose2d.ZERO); 078 079 public Swerve( 080 GyroIO gyroIO, 081 ModuleIO flModuleIO, 082 ModuleIO frModuleIO, 083 ModuleIO blModuleIO, 084 ModuleIO brModuleIO) { 085 this.gyroIO = gyroIO; 086 modules[0] = new Module(flModuleIO, 0, TunerConstants.FrontLeft); 087 modules[1] = new Module(frModuleIO, 1, TunerConstants.FrontRight); 088 modules[2] = new Module(blModuleIO, 2, TunerConstants.BackLeft); 089 modules[3] = new Module(brModuleIO, 3, TunerConstants.BackRight); 090 091 // Usage reporting for swerve template 092 UsageReporting.reportUsage("RobotDrive", "RobotDriveSwerve_AdvantageKit"); 093 094 // Start odometry thread 095 PhoenixOdometryThread.getInstance().start(); 096 097 // Configure AutoBuilder for PathPlanner 098 // AutoBuilder.configure( 099 // this::getPose, 100 // this::setPose, 101 // this::getChassisSpeeds, 102 // this::runVelocity, 103 // new PPHolonomicDriveController( 104 // new PIDConstants(5.0, 0.0, 0.0), new PIDConstants(5.0, 0.0, 0.0)), 105 // PP_CONFIG, 106 // () -> DriverStation.getAlliance().orElse(Alliance.Blue) == Alliance.Red, 107 // this); 108 // Pathfinding.setPathfinder(new LocalADStarAK()); 109 // PathPlannerLogging.setLogActivePathCallback( 110 // (activePath) -> { 111 // Logger.recordOutput("Odometry/Trajectory", activePath.toArray(new 112 // Pose2d[0])); 113 // }); 114 // PathPlannerLogging.setLogTargetPoseCallback( 115 // (targetPose) -> { 116 // Logger.recordOutput("Odometry/TrajectorySetpoint", targetPose); 117 // }); 118 119 // Configure SysId 120 // sysId = 121 // new SysIdRoutine( 122 // new SysIdRoutine.Config( 123 // null, 124 // null, 125 // null, 126 // (state) -> Logger.recordOutput("Drive/SysIdState", state.toString())), 127 // new SysIdRoutine.Mechanism( 128 // (voltage) -> runCharacterization(voltage.in(Volts)), null, this)); 129 } 130 131 @Override 132 public void periodic() { 133 odometryLock.lock(); // Prevents odometry updates while reading data 134 gyroIO.updateInputs(gyroInputs); 135 Logger.processInputs("Drive/Gyro", gyroInputs); 136 for (var module : modules) { 137 module.periodic(); 138 } 139 odometryLock.unlock(); 140 141 // Log empty setpoint states when disabled 142 if (RobotState.isDisabled() || !GlobalSettings.EnabledSubsystems.SWERVE.get()) { 143 stopModules(); 144 Logger.recordOutput("SwerveStates/Setpoints", new SwerveModuleVelocity[] {}); 145 Logger.recordOutput("SwerveStates/SetpointsOptimized", new SwerveModuleVelocity[] {}); 146 } 147 148 // Update odometry 149 double[] sampleTimestamps = 150 modules[0].getOdometryTimestamps(); // All signals are sampled together 151 int sampleCount = sampleTimestamps.length; 152 for (int i = 0; i < sampleCount; i++) { 153 // Read wheel positions and deltas from each module 154 SwerveModulePosition[] modulePositions = new SwerveModulePosition[4]; 155 SwerveModulePosition[] moduleDeltas = new SwerveModulePosition[4]; 156 for (int moduleIndex = 0; moduleIndex < 4; moduleIndex++) { 157 modulePositions[moduleIndex] = modules[moduleIndex].getOdometryPositions()[i]; 158 moduleDeltas[moduleIndex] = 159 new SwerveModulePosition( 160 modulePositions[moduleIndex].distance 161 - lastModulePositions[moduleIndex].distance, 162 modulePositions[moduleIndex].angle); 163 lastModulePositions[moduleIndex] = modulePositions[moduleIndex]; 164 } 165 166 // Update gyro angle 167 if (gyroInputs.connected) { 168 // Use the real gyro angle 169 rawGyroRotation = gyroInputs.odometryYawPositions[i]; 170 } else { 171 // Use the angle delta from the kinematics and module deltas 172 Twist2d twist = kinematics.toTwist2d(moduleDeltas); 173 rawGyroRotation = rawGyroRotation.plus(new Rotation2d(twist.dtheta)); 174 } 175 176 // Apply update 177 poseEstimator.updateWithTime(sampleTimestamps[i], rawGyroRotation, modulePositions); 178 } 179 180 // Update gyro alert 181 gyroDisconnectedAlert.set( 182 !gyroInputs.connected && GlobalSettings.CURRENT_MODE != RobotMode.SIM); 183 } 184 185 /** 186 * Runs the drive at the desired velocity. 187 * 188 * @param speeds Speeds in meters/sec 189 */ 190 public void runVelocity(ChassisVelocities speeds) { 191 if (!GlobalSettings.EnabledSubsystems.SWERVE.get()) { 192 stopModules(); 193 194 return; 195 } 196 197 // Calculate module setpoints 198 ChassisVelocities discreteSpeeds = speeds.discretize(0.02); 199 SwerveModuleVelocity[] setpointStates = kinematics.toSwerveModuleVelocities(discreteSpeeds); 200 setpointStates = 201 SwerveDriveKinematics.desaturateWheelVelocities( 202 setpointStates, TunerConstants.kSpeedAt12Volts); 203 204 // Log unoptimized setpoints and setpoint speeds 205 Logger.recordOutput("SwerveStates/Setpoints", setpointStates); 206 Logger.recordOutput("SwerveChassisSpeeds/Setpoints", discreteSpeeds); 207 208 // Send setpoints to modules 209 for (int i = 0; i < 4; i++) { 210 modules[i].runSetpoint(setpointStates[i]); 211 } 212 213 // Log optimized setpoints (runSetpoint mutates each state) 214 Logger.recordOutput("SwerveStates/SetpointsOptimized", setpointStates); 215 } 216 217 /** Runs the drive in a straight line with the specified drive output. */ 218 public void runCharacterization(double output) { 219 for (int i = 0; i < 4; i++) { 220 modules[i].runCharacterization(output); 221 } 222 } 223 224 public void runSteerCharacterization(double output) { 225 for (int i = 0; i < 4; i++) { 226 modules[i].runTurnCharacterization(output); 227 } 228 } 229 230 public double getSteerCharacterizationPositionRad() { 231 return modules[0].getAngle().getRadians(); 232 } 233 234 /** Stops the drive. */ 235 public void stop() { 236 runVelocity(new ChassisVelocities()); 237 } 238 239 public void stopModules() { 240 for (var module : modules) { 241 module.stop(); 242 } 243 } 244 245 /** 246 * Stops the drive and turns the modules to an X arrangement to resist movement. The modules 247 * will return to their normal orientations the next time a nonzero velocity is requested. 248 */ 249 public void stopWithX() { 250 Rotation2d[] headings = new Rotation2d[4]; 251 for (int i = 0; i < 4; i++) { 252 Optional<Rotation2d> rotation = getModuleTranslations()[i].getAngle(); 253 headings[i] = rotation.isPresent() ? rotation.get() : headings[i]; 254 } 255 kinematics.resetHeadings(headings); 256 stop(); 257 } 258 259 /** Returns a command to run a quasistatic test in the specified direction. */ 260 // public Command sysIdQuasistatic(SysIdRoutine.Direction direction) { 261 // return run(() -> runCharacterization(0.0)) 262 // .withTimeout(1.0) 263 // .andThen(sysId.quasistatic(direction)); 264 // } 265 266 // /** Returns a command to run a dynamic test in the specified direction. */ 267 // public Command sysIdDynamic(SysIdRoutine.Direction direction) { 268 // return run(() -> 269 // runCharacterization(0.0)).withTimeout(1.0).andThen(sysId.dynamic(direction)); 270 // } 271 272 /** Returns the module states (turn angles and drive velocities) for all of the modules. */ 273 @AutoLogOutput(key = "SwerveStates/Measured") 274 private SwerveModuleVelocity[] getModuleVelocities() { 275 SwerveModuleVelocity[] states = new SwerveModuleVelocity[4]; 276 for (int i = 0; i < 4; i++) { 277 states[i] = modules[i].getVelocity(); 278 } 279 return states; 280 } 281 282 /** Returns the module positions (turn angles and drive positions) for all of the modules. */ 283 private SwerveModulePosition[] getModulePositions() { 284 SwerveModulePosition[] states = new SwerveModulePosition[4]; 285 for (int i = 0; i < 4; i++) { 286 states[i] = modules[i].getPosition(); 287 } 288 return states; 289 } 290 291 /** Returns the measured chassis speeds of the robot. */ 292 @AutoLogOutput(key = "SwerveChassisSpeeds/Measured") 293 private ChassisVelocities getChassisSpeeds() { 294 return kinematics.toChassisVelocities(getModuleVelocities()); 295 } 296 297 /** Returns the position of each module in radians. */ 298 public double[] getWheelRadiusCharacterizationPositions() { 299 double[] values = new double[4]; 300 for (int i = 0; i < 4; i++) { 301 values[i] = modules[i].getWheelRadiusCharacterizationPosition(); 302 } 303 return values; 304 } 305 306 /** Returns the average velocity of the modules in rotations/sec (Phoenix native units). */ 307 public double getFFCharacterizationVelocity() { 308 double output = 0.0; 309 for (int i = 0; i < 4; i++) { 310 output += modules[i].getFFCharacterizationVelocity() / 4.0; 311 } 312 return output; 313 } 314 315 /** Returns the current odometry pose. */ 316 @AutoLogOutput(key = "Odometry/Robot") 317 public Pose2d getPose() { 318 return poseEstimator.getEstimatedPosition(); 319 } 320 321 /** Returns the current odometry rotation. */ 322 public Rotation2d getRotation() { 323 return getPose().getRotation(); 324 } 325 326 /** Resets the current odometry pose. */ 327 public void resetPose(Pose2d pose) { 328 poseEstimator.resetPosition(rawGyroRotation, getModulePositions(), pose); 329 } 330 331 public void resetRotation(Rotation2d rotation) { 332 poseEstimator.resetRotation(rotation); 333 } 334 335 public VisionConsumer visionConsumer = poseEstimator::addVisionMeasurement; 336 337 /** Returns the maximum linear speed in meters per sec. */ 338 public double getMaxLinearSpeedMetersPerSec() { 339 return TunerConstants.kSpeedAt12Volts.in(MetersPerSecond); 340 } 341 342 /** Returns the maximum angular speed in radians per sec. */ 343 public double getMaxAngularSpeedRadPerSec() { 344 return getMaxLinearSpeedMetersPerSec() / DRIVE_BASE_RADIUS; 345 } 346 347 /** Returns an array of module translations. */ 348 public static Translation2d[] getModuleTranslations() { 349 return new Translation2d[] { 350 new Translation2d( 351 TunerConstants.FrontLeft.LocationX, TunerConstants.FrontLeft.LocationY), 352 new Translation2d( 353 TunerConstants.FrontRight.LocationX, TunerConstants.FrontRight.LocationY), 354 new Translation2d(TunerConstants.BackLeft.LocationX, TunerConstants.BackLeft.LocationY), 355 new Translation2d( 356 TunerConstants.BackRight.LocationX, TunerConstants.BackRight.LocationY) 357 }; 358 } 359}