Skip to content

Commit

Permalink
Abstract all auto code into Auto.java (#22)
Browse files Browse the repository at this point in the history
* Abstract all auto code into Auto.java

* Renamed new test auto.

---------

Co-authored-by: mmilunicmobile <mmilunicmobile@gmail.com>
  • Loading branch information
rechsby and mmilunicmobile authored Dec 17, 2024
1 parent a2453db commit 93c1761
Show file tree
Hide file tree
Showing 6 changed files with 380 additions and 65 deletions.
223 changes: 223 additions & 0 deletions src/main/deploy/choreo/Spinny Path.traj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"version": "2025.0",
"command": {
"type": "sequential",
"data": {
"commands": [
{
"type": "path",
"data": {
"pathName": "Spinny Path"
}
}
]
}
},
"resetOdom": true,
"folder": null,
"choreoAuto": true
}
123 changes: 123 additions & 0 deletions src/main/java/frc/robot/Auto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package frc.robot;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.littletonrobotics.junction.networktables.LoggedDashboardChooser;

import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.commands.PathPlannerAuto;
import com.pathplanner.lib.config.PIDConstants;
import com.pathplanner.lib.config.RobotConfig;
import com.pathplanner.lib.controllers.PPHolonomicDriveController;
import com.pathplanner.lib.path.PathPlannerPath;
import com.pathplanner.lib.path.PathPoint;

import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.trajectory.TrajectoryConfig;
import edu.wpi.first.math.trajectory.TrajectoryGenerator;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStation.Alliance;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import frc.robot.subsystems.CommandSwerveDrivetrain;

public class Auto {
private final LoggedDashboardChooser<Command> autoChooser;
private Command previousAuto = Commands.none();
private RobotConfig config; // PathPlanner robot configuration

// *NEW
private final Field2d m_trajectoryField = new Field2d();

public Auto(CommandSwerveDrivetrain drivetrain) {
setUpPathPlanner(drivetrain);
autoChooser = new LoggedDashboardChooser<>("Auto Routine", AutoBuilder.buildAutoChooser());
SmartDashboard.putData("Auto Path", m_trajectoryField);
}

public void logAutoInformation() {
if (previousAuto == autoChooser.get()) {
return;
}

previousAuto = autoChooser.get();

Command command = previousAuto;
{
try
{
var paths = PathPlannerAuto.getPathGroupFromAutoFile(command.getName()); // A list of all paths contained in this auto
List<Pose2d> poses = new ArrayList<>(); // This will be a list of all points during the auto

for (PathPlannerPath path : paths) { // For each path assigned, split into segments
List<PathPoint> points = path.getAllPathPoints();
for (PathPoint point : points) { // For each segment, split into points
Pose2d newPose2d = new Pose2d(point.position, new Rotation2d());
poses.add(newPose2d);
}
}

// Generate a trajectory from the "poses" list. This is our entire path
// "config" is used for unit conversions; Reference Field2d Widget
var m_trajectory = TrajectoryGenerator.generateTrajectory(poses, new TrajectoryConfig(Units.feetToMeters(3.0), Units.feetToMeters(3.0)));

// Log the trajectory
m_trajectoryField.getObject("traj").setTrajectory(m_trajectory);
// Log the start and end positions
m_trajectoryField.getObject("start_and_end").setPoses(poses.get(0), poses.get(poses.size() -1));
}
catch (Exception e)
{
// Fallback in case the path is set to none, or the path file referenced does not exist
e.printStackTrace();
System.out.println("Pathplanner file not found! Skipping...");
m_trajectoryField.getObject("traj").setPoses();
m_trajectoryField.getObject("start_and_end").setPoses();
}
}
}

public Command getAuto() {
if (AutoBuilder.isConfigured()) {
return autoChooser.get();
} else {
return Commands.none();
}
}

public void setUpPathPlanner(CommandSwerveDrivetrain drivetrain) {
try {
config = RobotConfig.fromGUISettings();
} catch (Exception e) {
e.printStackTrace();
}

AutoBuilder.configure(
drivetrain::getRobotPose,
drivetrain::resetPose,
drivetrain::getChassisSpeeds,
(speeds, feedforwards) -> drivetrain.setControl(drivetrain.driveWithFeedforwards(speeds, 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,
() -> {
// Boolean supplier that controls when the path will be mirrored for the red alliance
Optional<Alliance> alliance = DriverStation.getAlliance();
if (alliance.isPresent()) {
return alliance.get() == DriverStation.Alliance.Red;
}
return false;
},
drivetrain
);
}
}

10 changes: 4 additions & 6 deletions src/main/java/frc/robot/Robot.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,13 @@
package frc.robot;


import org.littletonrobotics.junction.LogFileUtil;
import org.littletonrobotics.junction.LoggedRobot;
import org.littletonrobotics.junction.Logger;
import org.littletonrobotics.junction.networktables.NT4Publisher;
import org.littletonrobotics.junction.wpilog.WPILOGReader;
import org.littletonrobotics.junction.wpilog.WPILOGWriter;

import edu.wpi.first.wpilibj.PowerDistribution;
import edu.wpi.first.wpilibj.PowerDistribution.ModuleType;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.CommandScheduler;

Expand All @@ -33,7 +30,8 @@ public Robot() {
Logger.addDataReceiver(new NT4Publisher()); // Publish data to NetworkTables
PowerDistribution distribution = new PowerDistribution(1, ModuleType.kRev); // Enables power distribution logging
} else {
setUseTiming(false); // Run as fast as possible
setUseTiming(true); // Run as fast as possible
Logger.addDataReceiver(new NT4Publisher()); // Publish data to NetworkTables
}

Logger.start(); // Start logging! No more data receivers, replay sources, or metadata values may be added.
Expand All @@ -42,8 +40,8 @@ public Robot() {

@Override
public void robotPeriodic() {
CommandScheduler.getInstance().run();

CommandScheduler.getInstance().run();
m_robotContainer.auto.logAutoInformation();
}

@Override
Expand Down
63 changes: 4 additions & 59 deletions src/main/java/frc/robot/RobotContainer.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,10 @@

import static edu.wpi.first.units.Units.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import org.littletonrobotics.junction.networktables.LoggedDashboardChooser;


import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.commands.PathPlannerAuto;
import com.pathplanner.lib.path.PathPlannerPath;
import com.pathplanner.lib.path.PathPoint;
import com.ctre.phoenix6.swerve.SwerveRequest;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.trajectory.TrajectoryConfig;
import edu.wpi.first.math.trajectory.TrajectoryGenerator;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine.Direction;
import frc.lib.controller.LogitechController;
Expand All @@ -50,55 +34,17 @@ public class RobotContainer {

public final CommandSwerveDrivetrain drivetrain = TunerConstants.createDrivetrain();

private final LoggedDashboardChooser<Command> autoChooser;
public Auto auto = new Auto(drivetrain);

// Use open-loop control for drive motors
private final SwerveRequest.SwerveDriveBrake brake = new SwerveRequest.SwerveDriveBrake();
private final SwerveRequest.PointWheelsAt point = new SwerveRequest.PointWheelsAt();

private final Field2d m_trajectoryField = new Field2d(); // *NEW
public RobotContainer() {
configureBindings();

drivetrain.setUpPathPlanner();
SmartDashboard.putData("Trajectory Field", m_trajectoryField); // Establish the "Trajectory Field" Field2d into the dashboard
var tempAutoChooser = AutoBuilder.buildAutoChooser();
tempAutoChooser.onChange((Command command) -> {
try
{
var paths = PathPlannerAuto.getPathGroupFromAutoFile(command.getName()); // A list of all paths contained in this auto
List<Pose2d> poses = new ArrayList<>(); // This will be a list of all points during the auto

for (PathPlannerPath path : paths) { // For each path assigned, split into segments
List<PathPoint> points = path.getAllPathPoints();
for (PathPoint point : points) { // For each segment, split into points
Pose2d newPose2d = new Pose2d(point.position, new Rotation2d());
poses.add(newPose2d);
}
}

// Generate a trajectory from the "poses" list. This is our entire path
// "config" is used for unit conversions; Reference Field2d Widget
var m_trajectory = TrajectoryGenerator.generateTrajectory(poses, new TrajectoryConfig(Units.feetToMeters(3.0), Units.feetToMeters(3.0)));

// Log the trajectory
m_trajectoryField.getObject("traj").setTrajectory(m_trajectory);
// Log the start and end positions
m_trajectoryField.getObject("start_and_end").setPoses(poses.get(0), poses.get(poses.size() -1));
}
catch (Exception e)
{
// Fallback in case the path is set to none, or the path file referenced does not exist
e.printStackTrace();
System.out.println("Pathplanner file not found! Skipping...");
m_trajectoryField.getObject("traj").setPoses();
m_trajectoryField.getObject("start_and_end").setPoses();
}

});
SmartDashboard.putData(tempAutoChooser);

autoChooser = new LoggedDashboardChooser<>("Auto Routine", tempAutoChooser);
// Establish the "Trajectory Field" Field2d into the dashboard
}

private void configureBindings() {
Expand Down Expand Up @@ -155,8 +101,7 @@ private double sps(double value) {
}

public Command getAutonomousCommand() {

return autoChooser.get();

return auto.getAuto();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Subsystem;
import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine;
import frc.robot.RobotContainer;

/**
* Class that extends the Phoenix 6 SwerveDrivetrain class and implements
Expand Down Expand Up @@ -309,6 +310,12 @@ public SwerveRequest driveFieldRelative(ChassisSpeeds speeds) {
return driveRobotRelative(speeds);
}

public SwerveRequest driveWithFeedforwards(ChassisSpeeds speeds, DriveFeedforwards feedforwards) {
return m_applyRobotSpeeds.withSpeeds(speeds)
.withWheelForceFeedforwardsX(feedforwards.robotRelativeForcesXNewtons())
.withWheelForceFeedforwardsY(feedforwards.robotRelativeForcesYNewtons());
}

/**
* Returns a command that applies the specified control request to this swerve drivetrain.
*
Expand Down

0 comments on commit 93c1761

Please sign in to comment.