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 org.wpilib.math.geometry.Rotation2d;
008import org.wpilib.math.kinematics.SwerveModulePosition;
009import org.wpilib.math.kinematics.SwerveModuleVelocity;
010import org.wpilib.math.util.Units;
011import org.wpilib.util.Alert;
012
013import com.ctre.phoenix6.configs.CANcoderConfiguration;
014import com.ctre.phoenix6.configs.TalonFXConfiguration;
015import com.ctre.phoenix6.swerve.SwerveModuleConstants;
016
017import org.littletonrobotics.junction.Logger;
018
019public class Module {
020    private final ModuleIO io;
021    private final ModuleIOInputsAutoLogged inputs = new ModuleIOInputsAutoLogged();
022    private final int index;
023    private final SwerveModuleConstants<
024                    TalonFXConfiguration, TalonFXConfiguration, CANcoderConfiguration>
025            constants;
026
027    private final Alert driveDisconnectedAlert;
028    private final Alert turnDisconnectedAlert;
029    private final Alert turnEncoderDisconnectedAlert;
030    private SwerveModulePosition[] odometryPositions = new SwerveModulePosition[] {};
031
032    public Module(
033            ModuleIO io,
034            int index,
035            SwerveModuleConstants<TalonFXConfiguration, TalonFXConfiguration, CANcoderConfiguration>
036                    constants) {
037        this.io = io;
038        this.index = index;
039        this.constants = constants;
040        driveDisconnectedAlert =
041                new Alert(
042                        "ModuleDriveDisconnect_" + Integer.toString(index),
043                        "Disconnected drive motor on module " + Integer.toString(index) + ".",
044                        Alert.Level.HIGH);
045        turnDisconnectedAlert =
046                new Alert(
047                        "ModuleTurnDisconnect_" + Integer.toString(index),
048                        "Disconnected turn motor on module " + Integer.toString(index) + ".",
049                        Alert.Level.HIGH);
050        turnEncoderDisconnectedAlert =
051                new Alert(
052                        "ModuleEncoderDisconnect_" + Integer.toString(index),
053                        "Disconnected turn encoder on module " + Integer.toString(index) + ".",
054                        Alert.Level.HIGH);
055    }
056
057    public void periodic() {
058        io.updateInputs(inputs);
059        Logger.processInputs("Drive/Module" + Integer.toString(index), inputs);
060
061        // Calculate positions for odometry
062        int sampleCount = inputs.odometryTimestamps.length; // All signals are sampled together
063        odometryPositions = new SwerveModulePosition[sampleCount];
064        for (int i = 0; i < sampleCount; i++) {
065            double positionMeters = inputs.odometryDrivePositionsRad[i] * constants.WheelRadius;
066            Rotation2d angle = inputs.odometryTurnPositions[i];
067            odometryPositions[i] = new SwerveModulePosition(positionMeters, angle);
068        }
069
070        // Update alerts
071        driveDisconnectedAlert.set(!inputs.driveConnected);
072        turnDisconnectedAlert.set(!inputs.turnConnected);
073        turnEncoderDisconnectedAlert.set(!inputs.turnEncoderConnected);
074    }
075
076    /** Runs the module with the specified setpoint state. Mutates the state to optimize it. */
077    public void runSetpoint(SwerveModuleVelocity state) {
078        // Optimize velocity setpoint
079        state = state.optimize(getAngle());
080        state = state.cosineScale(inputs.turnPosition);
081
082        // Apply setpoints
083        io.setDriveVelocity(state.velocity / constants.WheelRadius);
084        io.setTurnPosition(state.angle);
085    }
086
087    /** Runs the module with the specified output while controlling to zero degrees. */
088    public void runCharacterization(double output) {
089        io.setDriveOpenLoop(output);
090        io.setTurnPosition(Rotation2d.ZERO);
091    }
092
093    public void runTurnCharacterization(double output) {
094        io.setDriveOpenLoop(0.0);
095        io.setTurnOpenLoop(output);
096    }
097
098    /** Disables all outputs to motors. */
099    public void stop() {
100        io.setDriveOpenLoop(0.0);
101        io.setTurnOpenLoop(0.0);
102    }
103
104    /** Returns the current turn angle of the module. */
105    public Rotation2d getAngle() {
106        return inputs.turnPosition;
107    }
108
109    /** Returns the current drive position of the module in meters. */
110    public double getPositionMeters() {
111        return inputs.drivePositionRad * constants.WheelRadius;
112    }
113
114    /** Returns the current drive velocity of the module in meters per second. */
115    public double getVelocityMetersPerSec() {
116        return inputs.driveVelocityRadPerSec * constants.WheelRadius;
117    }
118
119    /** Returns the module position (turn angle and drive position). */
120    public SwerveModulePosition getPosition() {
121        return new SwerveModulePosition(getPositionMeters(), getAngle());
122    }
123
124    /** Returns the module velocity (turn angle and drive velocity). */
125    public SwerveModuleVelocity getVelocity() {
126        return new SwerveModuleVelocity(getVelocityMetersPerSec(), getAngle());
127    }
128
129    /** Returns the module positions received this cycle. */
130    public SwerveModulePosition[] getOdometryPositions() {
131        return odometryPositions;
132    }
133
134    /** Returns the timestamps of the samples received this cycle. */
135    public double[] getOdometryTimestamps() {
136        return inputs.odometryTimestamps;
137    }
138
139    /** Returns the module position in radians. */
140    public double getWheelRadiusCharacterizationPosition() {
141        return inputs.drivePositionRad;
142    }
143
144    /** Returns the module velocity in rotations/sec (Phoenix native units). */
145    public double getFFCharacterizationVelocity() {
146        return Units.radiansToRotations(inputs.driveVelocityRadPerSec);
147    }
148}