-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwerveSubsystem.java
793 lines (727 loc) · 29.5 KB
/
SwerveSubsystem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
// Copyright (c) FIRST and other WPILib contributors.
// 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.subsystems.swervedrive;
import static edu.wpi.first.units.Units.Meter;
import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.commands.PathPlannerAuto;
import com.pathplanner.lib.commands.PathfindingCommand;
import com.pathplanner.lib.config.PIDConstants;
import com.pathplanner.lib.config.RobotConfig;
import com.pathplanner.lib.controllers.PPHolonomicDriveController;
import com.pathplanner.lib.path.PathConstraints;
import com.pathplanner.lib.path.PathPlannerPath;
import com.pathplanner.lib.util.DriveFeedforwards;
import com.pathplanner.lib.util.swerve.SwerveSetpoint;
import com.pathplanner.lib.util.swerve.SwerveSetpointGenerator;
import edu.wpi.first.apriltag.AprilTagFieldLayout;
import edu.wpi.first.apriltag.AprilTagFields;
import edu.wpi.first.math.controller.SimpleMotorFeedforward;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Pose3d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.trajectory.Trajectory;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine.Config;
import frc.robot.Constants;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.DoubleSupplier;
import java.util.function.Supplier;
import org.json.simple.parser.ParseException;
// import org.photonvision.targeting.PhotonPipelineResult;
import swervelib.SwerveController;
import swervelib.SwerveDrive;
import swervelib.SwerveDriveTest;
import swervelib.math.SwerveMath;
import swervelib.parser.SwerveControllerConfiguration;
import swervelib.parser.SwerveDriveConfiguration;
import swervelib.parser.SwerveParser;
import swervelib.telemetry.SwerveDriveTelemetry;
import swervelib.telemetry.SwerveDriveTelemetry.TelemetryVerbosity;
public class SwerveSubsystem extends SubsystemBase
{
/**
* Swerve drive object.
*/
private final SwerveDrive swerveDrive;
/**
* AprilTag field layout.
*/
// private final AprilTagFieldLayout aprilTagFieldLayout = AprilTagFieldLayout.loadField(AprilTagFields.k2024Crescendo);
/**
* Enable vision odometry updates while driving.
*/
// private final boolean visionDriveTest = false;
/**
* PhotonVision class to keep an accurate odometry.
*/
// private Vision vision;
/**
* Initialize {@link SwerveDrive} with the directory provided.
*
* @param directory Directory of swerve drive config files.
*/
public SwerveSubsystem(File directory)
{
// Angle conversion factor is 360 / (GEAR RATIO * ENCODER RESOLUTION)
// In this case the gear ratio is 12.8 motor revolutions per wheel rotation.
// The encoder resolution per motor revolution is 1 per motor revolution.
double angleConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(12.8);
// Motor conversion factor is (PI * WHEEL DIAMETER IN METERS) / (GEAR RATIO * ENCODER RESOLUTION).
// In this case the wheel diameter is 4 inches, which must be converted to meters to get meters/second.
// The gear ratio is 6.75 motor revolutions per wheel rotation.
// The encoder resolution per motor revolution is 1 per motor revolution.
double driveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(4), 6.75);
System.out.println("\"conversionFactors\": {");
System.out.println("\t\"angle\": {\"factor\": " + angleConversionFactor + " },");
System.out.println("\t\"drive\": {\"factor\": " + driveConversionFactor + " }");
System.out.println("}");
// Configure the Telemetry before creating the SwerveDrive to avoid unnecessary objects being created.
SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH;
try
{
swerveDrive = new SwerveParser(directory).createSwerveDrive(Constants.MAX_SPEED,
new Pose2d(new Translation2d(Meter.of(1),
Meter.of(4)),
Rotation2d.fromDegrees(0)));
// Alternative method if you don't want to supply the conversion factor via JSON files.
// swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed, angleConversionFactor, driveConversionFactor);
} catch (Exception e)
{
throw new RuntimeException(e);
}
swerveDrive.setHeadingCorrection(false); // Heading correction should only be used while controlling the robot via angle.
swerveDrive.setCosineCompensator(false);//!SwerveDriveTelemetry.isSimulation); // Disables cosine compensation for simulations since it causes discrepancies not seen in real life.
swerveDrive.setAngularVelocityCompensation(true,
true,
0.1); //Correct for skew that gets worse as angular velocity increases. Start with a coefficient of 0.1.
swerveDrive.setModuleEncoderAutoSynchronize(false,
1); // Enable if you want to resynchronize your absolute encoders and motor encoders periodically when they are not moving.
swerveDrive.pushOffsetsToEncoders(); // Set the absolute encoder to be used over the internal encoder and push the offsets onto it. Throws warning if not possible
// if (visionDriveTest)
// {
// setupPhotonVision();
// // Stop the odometry thread if we are using vision that way we can synchronize updates better.
// swerveDrive.stopOdometryThread();
// }
setupPathPlanner();
}
/**
* Construct the swerve drive.
*
* @param driveCfg SwerveDriveConfiguration for the swerve.
* @param controllerCfg Swerve Controller.
*/
public SwerveSubsystem(SwerveDriveConfiguration driveCfg, SwerveControllerConfiguration controllerCfg)
{
swerveDrive = new SwerveDrive(driveCfg,
controllerCfg,
Constants.MAX_SPEED,
new Pose2d(new Translation2d(Meter.of(2), Meter.of(0)),
Rotation2d.fromDegrees(0)));
}
/**
* Setup the photon vision class.
*/
// public void setupPhotonVision()
// {
// vision = new Vision(swerveDrive::getPose, swerveDrive.field);
// }
@Override
public void periodic()
{
// When vision is enabled we must manually update odometry in SwerveDrive
// if (visionDriveTest)
// {
// swerveDrive.updateOdometry();
// vision.updatePoseEstimation(swerveDrive);
// }
}
@Override
public void simulationPeriodic()
{
}
/**
* Setup AutoBuilder for PathPlanner.
*/
public void setupPathPlanner()
{
// Load the RobotConfig from the GUI settings. You should probably
// store this in your Constants file
RobotConfig config;
try
{
config = RobotConfig.fromGUISettings();
final boolean enableFeedforward = true;
// Configure AutoBuilder last
AutoBuilder.configure(
this::getPose,
// Robot pose supplier
this::resetOdometry,
// Method to reset odometry (will be called if your auto has a starting pose)
this::getRobotVelocity,
// ChassisSpeeds supplier. MUST BE ROBOT RELATIVE
(speedsRobotRelative, moduleFeedForwards) -> {
if (enableFeedforward)
{
swerveDrive.drive(
speedsRobotRelative,
swerveDrive.kinematics.toSwerveModuleStates(speedsRobotRelative),
moduleFeedForwards.linearForces()
);
} else
{
swerveDrive.setChassisSpeeds(speedsRobotRelative);
}
},
// Method that will drive the robot given ROBOT RELATIVE ChassisSpeeds. Also optionally outputs individual module feedforwards
new PPHolonomicDriveController(
// PPHolonomicController is the built in path following controller for holonomic drive trains
new PIDConstants(5.0, 0.0, 0.0),
// Translation PID constants
new PIDConstants(5.0, 0.0, 0.0)
// Rotation PID constants
),
config,
// The robot configuration
() -> {
// Boolean supplier that controls when the path will be mirrored for the red alliance
// This will flip the path being followed to the red side of the field.
// THE ORIGIN WILL REMAIN ON THE BLUE SIDE
var alliance = DriverStation.getAlliance();
if (alliance.isPresent())
{
return alliance.get() == DriverStation.Alliance.Red;
}
return false;
},
this
// Reference to this subsystem to set requirements
);
} catch (Exception e)
{
// Handle exception as needed
e.printStackTrace();
}
//Preload PathPlanner Path finding
// IF USING CUSTOM PATHFINDER ADD BEFORE THIS LINE
PathfindingCommand.warmupCommand().schedule();
}
/**
* Get the distance to the speaker.
*
* @return Distance to speaker in meters.
*/
// public double getDistanceToSpeaker()
// {
// int allianceAprilTag = DriverStation.getAlliance().get() == Alliance.Blue ? 7 : 4;
// // Taken from PhotonUtils.getDistanceToPose
// Pose3d speakerAprilTagPose = aprilTagFieldLayout.getTagPose(allianceAprilTag).get();
// return getPose().getTranslation().getDistance(speakerAprilTagPose.toPose2d().getTranslation());
// }
/**
* Get the yaw to aim at the speaker.
*
* @return {@link Rotation2d} of which you need to achieve.
*/
// public Rotation2d getSpeakerYaw()
// {
// int allianceAprilTag = DriverStation.getAlliance().get() == Alliance.Blue ? 7 : 4;
// // Taken from PhotonUtils.getYawToPose()
// Pose3d speakerAprilTagPose = aprilTagFieldLayout.getTagPose(allianceAprilTag).get();
// Translation2d relativeTrl = speakerAprilTagPose.toPose2d().relativeTo(getPose()).getTranslation();
// return new Rotation2d(relativeTrl.getX(), relativeTrl.getY()).plus(swerveDrive.getOdometryHeading());
// }
/**
* Aim the robot at the speaker.
*
* @param tolerance Tolerance in degrees.
* @return Command to turn the robot to the speaker.
*/
// public Command aimAtSpeaker(double tolerance)
// {
// SwerveController controller = swerveDrive.getSwerveController();
// return run(
// () -> {
// ChassisSpeeds speeds = new ChassisSpeeds(0, 0,
// controller.headingCalculate(getHeading().getRadians(),
// getSpeakerYaw().getRadians()));
// speeds.toRobotRelativeSpeeds(getHeading());
// drive(speeds);
// }).until(() -> Math.abs(getSpeakerYaw().minus(getHeading()).getDegrees()) < tolerance);
// }
/**
* Aim the robot at the target returned by PhotonVision.
*
* @return A {@link Command} which will run the alignment.
*/
// public Command aimAtTarget(Cameras camera)
// {
// return run(() -> {
// Optional<PhotonPipelineResult> resultO = camera.getBestResult();
// if (resultO.isPresent())
// {
// var result = resultO.get();
// if (result.hasTargets())
// {
// drive(getTargetSpeeds(0,
// 0,
// Rotation2d.fromDegrees(result.getBestTarget()
// .getYaw()))); // Not sure if this will work, more math may be required.
// }
// }
// });
// }
/**
* Get the path follower with events.
*
* @param pathName PathPlanner path name.
* @return {@link AutoBuilder#followPath(PathPlannerPath)} path command.
*/
public Command getAutonomousCommand(String pathName)
{
// Create a path following command using AutoBuilder. This will also trigger event markers.
return new PathPlannerAuto(pathName);
}
/**
* Use PathPlanner Path finding to go to a point on the field.
*
* @param pose Target {@link Pose2d} to go to.
* @return PathFinding command
*/
public Command driveToPose(Pose2d pose)
{
// Create the constraints to use while pathfinding
PathConstraints constraints = new PathConstraints(
swerveDrive.getMaximumChassisVelocity(), 4.0,
swerveDrive.getMaximumChassisAngularVelocity(), Units.degreesToRadians(720));
// Since AutoBuilder is configured, we can use it to build pathfinding commands
return AutoBuilder.pathfindToPose(
pose,
constraints,
edu.wpi.first.units.Units.MetersPerSecond.of(0) // Goal end velocity in meters/sec
);
}
/**
* Drive with {@link SwerveSetpointGenerator} from 254, implemented by PathPlanner.
*
* @param robotRelativeChassisSpeed Robot relative {@link ChassisSpeeds} to achieve.
* @return {@link Command} to run.
* @throws IOException If the PathPlanner GUI settings is invalid
* @throws ParseException If PathPlanner GUI settings is nonexistent.
*/
private Command driveWithSetpointGenerator(Supplier<ChassisSpeeds> robotRelativeChassisSpeed)
throws IOException, ParseException
{
SwerveSetpointGenerator setpointGenerator = new SwerveSetpointGenerator(RobotConfig.fromGUISettings(),
swerveDrive.getMaximumChassisAngularVelocity());
AtomicReference<SwerveSetpoint> prevSetpoint
= new AtomicReference<>(new SwerveSetpoint(swerveDrive.getRobotVelocity(),
swerveDrive.getStates(),
DriveFeedforwards.zeros(swerveDrive.getModules().length)));
AtomicReference<Double> previousTime = new AtomicReference<>();
return startRun(() -> previousTime.set(Timer.getFPGATimestamp()),
() -> {
double newTime = Timer.getFPGATimestamp();
SwerveSetpoint newSetpoint = setpointGenerator.generateSetpoint(prevSetpoint.get(),
robotRelativeChassisSpeed.get(),
newTime - previousTime.get());
swerveDrive.drive(newSetpoint.robotRelativeSpeeds(),
newSetpoint.moduleStates(),
newSetpoint.feedforwards().linearForces());
prevSetpoint.set(newSetpoint);
previousTime.set(newTime);
});
}
/**
* Drive with 254's Setpoint generator; port written by PathPlanner.
*
* @param fieldRelativeSpeeds Field-Relative {@link ChassisSpeeds}
* @return Command to drive the robot using the setpoint generator.
*/
public Command driveWithSetpointGeneratorFieldRelative(Supplier<ChassisSpeeds> fieldRelativeSpeeds)
{
try
{
return driveWithSetpointGenerator(() -> {
ChassisSpeeds robotRelativeSpeeds = ChassisSpeeds.fromFieldRelativeSpeeds(fieldRelativeSpeeds.get(), getHeading());
return robotRelativeSpeeds;
});
} catch (Exception e)
{
DriverStation.reportError(e.toString(), true);
}
return Commands.none();
}
/**
* Command to characterize the robot drive motors using SysId
*
* @return SysId Drive Command
*/
public Command sysIdDriveMotorCommand()
{
return SwerveDriveTest.generateSysIdCommand(
SwerveDriveTest.setDriveSysIdRoutine(
new Config(),
this, swerveDrive, 12),
3.0, 5.0, 3.0);
}
/**
* Command to characterize the robot angle motors using SysId
*
* @return SysId Angle Command
*/
public Command sysIdAngleMotorCommand()
{
return SwerveDriveTest.generateSysIdCommand(
SwerveDriveTest.setAngleSysIdRoutine(
new Config(),
this, swerveDrive),
3.0, 5.0, 3.0);
}
/**
* Returns a Command that centers the modules of the SwerveDrive subsystem.
*
* @return a Command that centers the modules of the SwerveDrive subsystem
*/
public Command centerModulesCommand()
{
return run(() -> Arrays.asList(swerveDrive.getModules())
.forEach(it -> it.setAngle(0.0)));
}
/**
* Returns a Command that drives the swerve drive to a specific distance at a given speed.
*
* @param distanceInMeters the distance to drive in meters
* @param speedInMetersPerSecond the speed at which to drive in meters per second
* @return a Command that drives the swerve drive to a specific distance at a given speed
*/
public Command driveToDistanceCommand(double distanceInMeters, double speedInMetersPerSecond)
{
return run(() -> drive(new ChassisSpeeds(speedInMetersPerSecond, 0, 0)))
.until(() -> swerveDrive.getPose().getTranslation().getDistance(new Translation2d(0, 0)) >
distanceInMeters);
}
/**
* Replaces the swerve module feedforward with a new SimpleMotorFeedforward object.
*
* @param kS the static gain of the feedforward
* @param kV the velocity gain of the feedforward
* @param kA the acceleration gain of the feedforward
*/
public void replaceSwerveModuleFeedforward(double kS, double kV, double kA)
{
swerveDrive.replaceSwerveModuleFeedforward(new SimpleMotorFeedforward(kS, kV, kA));
}
/**
* Command to drive the robot using translative values and heading as angular velocity.
*
* @param translationX Translation in the X direction. Cubed for smoother controls.
* @param translationY Translation in the Y direction. Cubed for smoother controls.
* @param angularRotationX Angular velocity of the robot to set. Cubed for smoother controls.
* @return Drive command.
*/
public Command driveCommand(DoubleSupplier translationX, DoubleSupplier translationY, DoubleSupplier angularRotationX)
{
return run(() -> {
// Make the robot move
swerveDrive.drive(SwerveMath.scaleTranslation(new Translation2d(
translationX.getAsDouble() * swerveDrive.getMaximumChassisVelocity(),
translationY.getAsDouble() * swerveDrive.getMaximumChassisVelocity()), 0.8),
Math.pow(angularRotationX.getAsDouble(), 3) * swerveDrive.getMaximumChassisAngularVelocity(),
true,
false);
});
}
/**
* Command to drive the robot using translative values and heading as a setpoint.
*
* @param translationX Translation in the X direction. Cubed for smoother controls.
* @param translationY Translation in the Y direction. Cubed for smoother controls.
* @param headingX Heading X to calculate angle of the joystick.
* @param headingY Heading Y to calculate angle of the joystick.
* @return Drive command.
*/
public Command driveCommand(DoubleSupplier translationX, DoubleSupplier translationY, DoubleSupplier headingX,
DoubleSupplier headingY)
{
// swerveDrive.setHeadingCorrection(true); // Normally you would want heading correction for this kind of control.
return run(() -> {
Translation2d scaledInputs = SwerveMath.scaleTranslation(new Translation2d(translationX.getAsDouble(),
translationY.getAsDouble()), 0.8);
// Make the robot move
driveFieldOriented(swerveDrive.swerveController.getTargetSpeeds(scaledInputs.getX(), scaledInputs.getY(),
headingX.getAsDouble(),
headingY.getAsDouble(),
swerveDrive.getOdometryHeading().getRadians(),
swerveDrive.getMaximumChassisVelocity()));
});
}
/**
* The primary method for controlling the drivebase. Takes a {@link Translation2d} and a rotation rate, and
* calculates and commands module states accordingly. Can use either open-loop or closed-loop velocity control for
* the wheel velocities. Also has field- and robot-relative modes, which affect how the translation vector is used.
*
* @param translation {@link Translation2d} that is the commanded linear velocity of the robot, in meters per
* second. In robot-relative mode, positive x is torwards the bow (front) and positive y is
* torwards port (left). In field-relative mode, positive x is away from the alliance wall
* (field North) and positive y is torwards the left wall when looking through the driver station
* glass (field West).
* @param rotation Robot angular rate, in radians per second. CCW positive. Unaffected by field/robot
* relativity.
* @param fieldRelative Drive mode. True for field-relative, false for robot-relative.
*/
public void drive(Translation2d translation, double rotation, boolean fieldRelative)
{
swerveDrive.drive(translation,
rotation,
fieldRelative,
false); // Open loop is disabled since it shouldn't be used most of the time.
}
/**
* Drive the robot given a chassis field oriented velocity.
*
* @param velocity Velocity according to the field.
*/
public void driveFieldOriented(ChassisSpeeds velocity)
{
swerveDrive.driveFieldOriented(velocity);
}
/**
* Drive the robot given a chassis field oriented velocity.
*
* @param velocity Velocity according to the field.
*/
public Command driveFieldOriented(Supplier<ChassisSpeeds> velocity)
{
return run(() -> {
swerveDrive.driveFieldOriented(velocity.get());
});
}
/**
* Drive according to the chassis robot oriented velocity.
*
* @param velocity Robot oriented {@link ChassisSpeeds}
*/
public void drive(ChassisSpeeds velocity)
{
swerveDrive.drive(velocity);
}
/**
* Get the swerve drive kinematics object.
*
* @return {@link SwerveDriveKinematics} of the swerve drive.
*/
public SwerveDriveKinematics getKinematics()
{
return swerveDrive.kinematics;
}
/**
* Resets odometry to the given pose. Gyro angle and module positions do not need to be reset when calling this
* method. However, if either gyro angle or module position is reset, this must be called in order for odometry to
* keep working.
*
* @param initialHolonomicPose The pose to set the odometry to
*/
public void resetOdometry(Pose2d initialHolonomicPose)
{
swerveDrive.resetOdometry(initialHolonomicPose);
}
/**
* Gets the current pose (position and rotation) of the robot, as reported by odometry.
*
* @return The robot's pose
*/
public Pose2d getPose()
{
return swerveDrive.getPose();
}
/**
* Set chassis speeds with closed-loop velocity control.
*
* @param chassisSpeeds Chassis Speeds to set.
*/
public void setChassisSpeeds(ChassisSpeeds chassisSpeeds)
{
swerveDrive.setChassisSpeeds(chassisSpeeds);
}
/**
* Post the trajectory to the field.
*
* @param trajectory The trajectory to post.
*/
public void postTrajectory(Trajectory trajectory)
{
swerveDrive.postTrajectory(trajectory);
}
/**
* Resets the gyro angle to zero and resets odometry to the same position, but facing toward 0.
*/
public void zeroGyro()
{
swerveDrive.zeroGyro();
}
/**
* Checks if the alliance is red, defaults to false if alliance isn't available.
*
* @return true if the red alliance, false if blue. Defaults to false if none is available.
*/
private boolean isRedAlliance()
{
var alliance = DriverStation.getAlliance();
return alliance.isPresent() ? alliance.get() == DriverStation.Alliance.Red : false;
}
/**
* This will zero (calibrate) the robot to assume the current position is facing forward
* <p>
* If red alliance rotate the robot 180 after the drviebase zero command
*/
public void zeroGyroWithAlliance()
{
if (isRedAlliance())
{
zeroGyro();
//Set the pose 180 degrees
resetOdometry(new Pose2d(getPose().getTranslation(), Rotation2d.fromDegrees(180)));
} else
{
zeroGyro();
}
}
/**
* Sets the drive motors to brake/coast mode.
*
* @param brake True to set motors to brake mode, false for coast.
*/
public void setMotorBrake(boolean brake)
{
swerveDrive.setMotorIdleMode(brake);
}
/**
* Gets the current yaw angle of the robot, as reported by the swerve pose estimator in the underlying drivebase.
* Note, this is not the raw gyro reading, this may be corrected from calls to resetOdometry().
*
* @return The yaw angle
*/
public Rotation2d getHeading()
{
return getPose().getRotation();
}
/**
* Get the chassis speeds based on controller input of 2 joysticks. One for speeds in which direction. The other for
* the angle of the robot.
*
* @param xInput X joystick input for the robot to move in the X direction.
* @param yInput Y joystick input for the robot to move in the Y direction.
* @param headingX X joystick which controls the angle of the robot.
* @param headingY Y joystick which controls the angle of the robot.
* @return {@link ChassisSpeeds} which can be sent to the Swerve Drive.
*/
public ChassisSpeeds getTargetSpeeds(double xInput, double yInput, double headingX, double headingY)
{
Translation2d scaledInputs = SwerveMath.cubeTranslation(new Translation2d(xInput, yInput));
return swerveDrive.swerveController.getTargetSpeeds(scaledInputs.getX(),
scaledInputs.getY(),
headingX,
headingY,
getHeading().getRadians(),
Constants.MAX_SPEED);
}
/**
* Get the chassis speeds based on controller input of 1 joystick and one angle. Control the robot at an offset of
* 90deg.
*
* @param xInput X joystick input for the robot to move in the X direction.
* @param yInput Y joystick input for the robot to move in the Y direction.
* @param angle The angle in as a {@link Rotation2d}.
* @return {@link ChassisSpeeds} which can be sent to the Swerve Drive.
*/
public ChassisSpeeds getTargetSpeeds(double xInput, double yInput, Rotation2d angle)
{
Translation2d scaledInputs = SwerveMath.cubeTranslation(new Translation2d(xInput, yInput));
return swerveDrive.swerveController.getTargetSpeeds(scaledInputs.getX(),
scaledInputs.getY(),
angle.getRadians(),
getHeading().getRadians(),
Constants.MAX_SPEED);
}
/**
* Gets the current field-relative velocity (x, y and omega) of the robot
*
* @return A ChassisSpeeds object of the current field-relative velocity
*/
public ChassisSpeeds getFieldVelocity()
{
return swerveDrive.getFieldVelocity();
}
/**
* Gets the current velocity (x, y and omega) of the robot
*
* @return A {@link ChassisSpeeds} object of the current velocity
*/
public ChassisSpeeds getRobotVelocity()
{
return swerveDrive.getRobotVelocity();
}
/**
* Get the {@link SwerveController} in the swerve drive.
*
* @return {@link SwerveController} from the {@link SwerveDrive}.
*/
public SwerveController getSwerveController()
{
return swerveDrive.swerveController;
}
/**
* Get the {@link SwerveDriveConfiguration} object.
*
* @return The {@link SwerveDriveConfiguration} fpr the current drive.
*/
public SwerveDriveConfiguration getSwerveDriveConfiguration()
{
return swerveDrive.swerveDriveConfiguration;
}
/**
* Lock the swerve drive to prevent it from moving.
*/
public void lock()
{
swerveDrive.lockPose();
}
/**
* Gets the current pitch angle of the robot, as reported by the imu.
*
* @return The heading as a {@link Rotation2d} angle
*/
public Rotation2d getPitch()
{
return swerveDrive.getPitch();
}
/**
* Add a fake vision reading for testing purposes.
*/
public void addFakeVisionReading()
{
swerveDrive.addVisionMeasurement(new Pose2d(3, 3, Rotation2d.fromDegrees(65)), Timer.getFPGATimestamp());
}
/**
* Gets the swerve drive object.
*
* @return {@link SwerveDrive}
*/
public SwerveDrive getSwerveDrive()
{
return swerveDrive;
}
}