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;
006
007import com.stuypulse.robot.commands.auton.AutonFactory;
008import com.stuypulse.robot.commands.subsystems.DriveCommands;
009import com.stuypulse.robot.constants.DriverConstants;
010import com.stuypulse.robot.constants.FieldConstants;
011import com.stuypulse.robot.constants.GlobalSettings;
012import com.stuypulse.robot.generated.BuildConstants;
013import com.stuypulse.robot.opmodes.AutonOpMode;
014import com.stuypulse.robot.opmodes.sysid.SwerveDriveSysId;
015import com.stuypulse.robot.subsystems.swerve.GyroIO;
016import com.stuypulse.robot.subsystems.swerve.GyroIOPigeon2;
017import com.stuypulse.robot.subsystems.swerve.ModuleIO;
018import com.stuypulse.robot.subsystems.swerve.ModuleIOSim;
019import com.stuypulse.robot.subsystems.swerve.ModuleIOTalonFX;
020import com.stuypulse.robot.subsystems.swerve.Swerve;
021import com.stuypulse.robot.subsystems.swerve.TunerConstants;
022import com.stuypulse.robot.subsystems.vision.Vision;
023import com.stuypulse.robot.subsystems.vision.VisionConstants;
024import com.stuypulse.robot.subsystems.vision.VisionConstants.Camera;
025import com.stuypulse.robot.subsystems.vision.VisionConstants.CameraType;
026import com.stuypulse.robot.subsystems.vision.VisionIO;
027import com.stuypulse.robot.subsystems.vision.VisionIOLimelight;
028import com.stuypulse.robot.subsystems.vision.VisionIOPhoton;
029import com.stuypulse.robot.subsystems.vision.VisionIOPhotonSim;
030import com.stuypulse.robot.util.PeriodicSubsystem;
031
032import org.wpilib.command3.Scheduler;
033import org.wpilib.command3.button.CommandGamepad;
034import org.wpilib.command3.sysid.SysIdRoutine;
035import org.wpilib.command3.sysid.SysIdRoutine.Direction;
036import org.wpilib.driverstation.Alliance;
037import org.wpilib.driverstation.MatchState;
038import org.wpilib.hardware.hal.RobotMode;
039import org.wpilib.math.geometry.Rotation2d;
040import org.wpilib.tunable.Tunables;
041import org.wpilib.util.Alert;
042
043import java.util.EnumMap;
044import java.util.Optional;
045import org.littletonrobotics.junction.LogFileUtil;
046import org.littletonrobotics.junction.LoggedOpModeRobot;
047import org.littletonrobotics.junction.Logger;
048import org.littletonrobotics.junction.networktables.NT4Publisher;
049import org.littletonrobotics.junction.wpilog.WPILOGReader;
050import org.littletonrobotics.junction.wpilog.WPILOGWriter;
051
052/**
053 * Robot Class
054 *
055 * <p>This is the main class for robot code, instantiated in {@link com.stuypulse.robot.Main} It
056 * extends TimedRobot, meaning that the methods in this class are called automatically during
057 * specific states of the robot.
058 */
059public class Robot extends LoggedOpModeRobot {
060    private static final Alert allianceMissing =
061            new Alert(
062                    "MissingAllianceWarning",
063                    "Alliance optional has no value present",
064                    Alert.Level.MEDIUM);
065
066    /**
067     * Checks the alliance the robot is on
068     *
069     * @return true if the robot is on the blue alliance, false if the robot is on the red alliance,
070     *     and false if alliance cannot be determined.
071     */
072    public static boolean isBlue() {
073        final Optional<Alliance> alliance = MatchState.getAlliance();
074        if (alliance.isPresent()) {
075            allianceMissing.set(false);
076            return alliance.get() == Alliance.BLUE;
077        } else {
078            allianceMissing.set(true);
079        }
080        return false;
081    }
082
083    // Gamepads
084    public final CommandGamepad driver =
085            new CommandGamepad(DriverConstants.Driver.DRIVER_INDEX); // model-agnostic controller
086    public final Swerve swerve;
087    public final Vision vision;
088    public final Scheduler defaultScheduler;
089
090    public Robot() {
091        this.defaultScheduler = Scheduler.getDefault();
092        configureLogging();
093
094        EnumMap<Camera, VisionIO> visionIOMap = new EnumMap<>(Camera.class);
095        switch (GlobalSettings.CURRENT_MODE) {
096            case REAL -> {
097                swerve =
098                        new Swerve(
099                                new GyroIOPigeon2(),
100                                new ModuleIOTalonFX(TunerConstants.FrontLeft),
101                                new ModuleIOTalonFX(TunerConstants.FrontRight),
102                                new ModuleIOTalonFX(TunerConstants.BackLeft),
103                                new ModuleIOTalonFX(TunerConstants.BackRight));
104                for (Camera camera : VisionConstants.Camera.values()) {
105                    visionIOMap.put(
106                            camera,
107                            camera.getCameraType() == CameraType.LIMELIGHT
108                                    ? new VisionIOLimelight(
109                                            camera.getName(), camera.getRobotToCamera())
110                                    : new VisionIOPhoton(
111                                            camera.getName(), camera.getRobotToCamera()));
112                }
113            }
114
115            case SIM -> {
116                swerve =
117                        new Swerve(
118                                new GyroIO() {},
119                                new ModuleIOSim(TunerConstants.FrontLeft),
120                                new ModuleIOSim(TunerConstants.FrontRight),
121                                new ModuleIOSim(TunerConstants.BackLeft),
122                                new ModuleIOSim(TunerConstants.BackRight));
123                for (Camera camera : Camera.values()) {
124                    visionIOMap.put(
125                            camera,
126                            new VisionIOPhotonSim(
127                                    camera.getName(), camera.getRobotToCamera(), swerve::getPose));
128                }
129            }
130
131            default -> {
132                swerve =
133                        new Swerve(
134                                new GyroIO() {},
135                                new ModuleIO() {},
136                                new ModuleIO() {},
137                                new ModuleIO() {},
138                                new ModuleIO() {});
139                for (Camera camera : Camera.values()) {
140                    visionIOMap.put(camera, new VisionIO() {});
141                }
142            }
143        }
144        vision = new Vision(swerve.visionConsumer, visionIOMap, swerve::getRotation);
145
146        configureDefaultCommands();
147        configureButtonBindings();
148        configureAutons();
149        configureSysIds();
150        publishOpModes();
151    }
152
153    /*********************/
154    /*** CONFIGURATION ***/
155    /*********************/
156
157    private void configureLogging() {
158        // Git metadata
159        Logger.recordMetadata("ProjectName", BuildConstants.MAVEN_NAME);
160        Logger.recordMetadata("BuildDate", BuildConstants.BUILD_DATE);
161        Logger.recordMetadata("GitCommitMessage", BuildConstants.GIT_MESSAGE);
162        if (!BuildConstants.GIT_LINK.isBlank()) {
163            Logger.recordMetadata("GitCommitLink", BuildConstants.GIT_LINK);
164        }
165        Logger.recordMetadata(
166                "GitPushStatus",
167                switch (BuildConstants.GIT_PUSH_STATUS) {
168                    case "PUSHED" -> "Commit pushed to remote repository";
169                    case "NOT_PUSHED" -> "Local commit not pushed to remote repository";
170                    case "STALE" -> "Could not verify push status. Cached information may be stale";
171                    default -> "Unable to determine commit push status";
172                });
173        Logger.recordMetadata("GitSHA", BuildConstants.GIT_SHA);
174        Logger.recordMetadata("GitDate", BuildConstants.GIT_DATE);
175        Logger.recordMetadata("GitBranch", BuildConstants.GIT_BRANCH);
176        Logger.recordMetadata(
177                "GitDirty",
178                switch (BuildConstants.DIRTY) {
179                    case 0 -> "All changes committed";
180                    case 1 -> "Uncommitted changes";
181                    default -> "Unknown";
182                });
183
184        // Log setup
185        switch (GlobalSettings.CURRENT_MODE) {
186            case REAL -> {
187                // Running on a real robot, log to a USB stick ("/U/logs")
188                Logger.addDataReceiver(new WPILOGWriter());
189                Logger.addDataReceiver(new NT4Publisher());
190            }
191
192            case SIM -> {
193                // Running a physics simulator, log to NT
194                Logger.addDataReceiver(new NT4Publisher());
195            }
196
197            case REPLAY -> {
198                // Replaying a log, set up replay source
199                setUseTiming(false); // Run as fast as possible
200                String logPath = LogFileUtil.findReplayLog();
201                Logger.setReplaySource(new WPILOGReader(logPath));
202                Logger.addDataReceiver(
203                        new WPILOGWriter(LogFileUtil.addPathSuffix(logPath, "_replay")));
204            }
205        }
206
207        Logger.start();
208        Tunables.publish("Field", FieldConstants.FIELD_2D);
209    }
210
211    private void configureDefaultCommands() {
212        swerve.setDefaultCommand(DriveCommands.joystickDrive(swerve, driver));
213    }
214
215    private void configureButtonBindings() {
216        driver.dpadUp().onTrue(DriveCommands.resetHeading(swerve, Rotation2d.ZERO));
217    }
218
219    private void configureAutons() {
220        AutonFactory autonFactory = new AutonFactory(swerve, vision);
221
222        AutonOpMode.addDefaultAuton("Do Nothing", autonFactory.doNothingAuton());
223
224        addOpMode(RobotMode.AUTONOMOUS, "Chooser Auton", () -> new AutonOpMode(this));
225    }
226
227    private void configureSysIds() {
228        addOpMode(
229                RobotMode.UTILITY,
230                "Quasistatic Reverse",
231                "SysId",
232                () -> new SwerveDriveSysId(swerve, Direction.REVERSE, SysIdRoutine::quasistatic));
233        addOpMode(
234                RobotMode.UTILITY,
235                "Quasistatic Forward",
236                "SysId",
237                () -> new SwerveDriveSysId(swerve, Direction.FORWARD, SysIdRoutine::quasistatic));
238        addOpMode(
239                RobotMode.UTILITY,
240                "Dynamic Forward",
241                "SysId",
242                () -> new SwerveDriveSysId(swerve, Direction.FORWARD, SysIdRoutine::dynamic));
243        addOpMode(
244                RobotMode.UTILITY,
245                "Dynamic Reverse",
246                "SysId",
247                () -> new SwerveDriveSysId(swerve, Direction.REVERSE, SysIdRoutine::dynamic));
248    }
249
250    /************************/
251    /*** ROBOT SCHEDULING ***/
252    /************************/
253
254    @Override
255    public void robotPeriodic() {
256        defaultScheduler.run();
257        PeriodicSubsystem.runAllPeriodicAfterScheduler();
258    }
259}