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.vision;
006
007import com.stuypulse.robot.constants.FieldConstants;
008import com.stuypulse.robot.constants.GlobalSettings;
009import com.stuypulse.robot.subsystems.vision.VisionConstants.Camera;
010import com.stuypulse.robot.subsystems.vision.VisionConstants.Pipeline;
011import com.stuypulse.robot.subsystems.vision.VisionConstants.VisionSettings;
012import com.stuypulse.robot.subsystems.vision.VisionIO.MegaTagMode;
013import com.stuypulse.robot.subsystems.vision.VisionIO.PoseObservation;
014import com.stuypulse.robot.subsystems.vision.VisionIO.PoseObservationType;
015import com.stuypulse.robot.subsystems.vision.VisionIO.VisionIOOutputs;
016import com.stuypulse.robot.util.PeriodicSubsystem;
017
018import org.wpilib.command3.Command;
019import org.wpilib.math.geometry.Pose2d;
020import org.wpilib.math.geometry.Pose3d;
021import org.wpilib.math.geometry.Rotation2d;
022import org.wpilib.math.linalg.Matrix;
023import org.wpilib.math.linalg.VecBuilder;
024import org.wpilib.math.numbers.N1;
025import org.wpilib.math.numbers.N3;
026import org.wpilib.system.Timer;
027import org.wpilib.util.Alert;
028
029import com.limelightvision.IMUMode;
030import com.limelightvision.Limelight;
031import java.util.EnumMap;
032import java.util.Iterator;
033import java.util.LinkedList;
034import java.util.List;
035import java.util.Map.Entry;
036import java.util.Optional;
037import java.util.function.Supplier;
038import org.littletonrobotics.junction.Logger;
039
040public class Vision extends PeriodicSubsystem {
041    private final VisionConsumer consumer;
042    private final EnumMap<Camera, VisionIO> io;
043    private final Supplier<Rotation2d> rotationSupplier;
044    private final EnumMap<Camera, VisionIOInputsAutoLogged> inputs;
045    private final EnumMap<Camera, VisionIOOutputs> outputs;
046    private final EnumMap<Camera, Alert> disconnectedAlerts;
047
048    private final Timer hdrTimer;
049
050    public Vision(
051            VisionConsumer consumer,
052            EnumMap<Camera, VisionIO> cameraIOMap,
053            Supplier<Rotation2d> rotationSupplier) {
054        this.consumer = consumer;
055
056        this.io = new EnumMap<>(cameraIOMap);
057
058        this.rotationSupplier = rotationSupplier;
059
060        // Initialize inputs
061        this.inputs = new EnumMap<>(Camera.class);
062        this.outputs = new EnumMap<>(Camera.class);
063
064        // Initialize disconnected alerts
065        this.disconnectedAlerts = new EnumMap<>(Camera.class);
066
067        this.hdrTimer = new Timer();
068        for (Camera camera : io.keySet()) {
069            inputs.put(camera, new VisionIOInputsAutoLogged());
070            outputs.put(camera, new VisionIOOutputs());
071            disconnectedAlerts.put(
072                    camera,
073                    new Alert(
074                            "Camera" + camera.getName() + "Disconnect",
075                            "Vision camera " + camera.getName() + " is disconnected.",
076                            Alert.Level.MEDIUM));
077        }
078
079        hdrTimer.start();
080    }
081
082    /**
083     * Returns the X angle to the best target, which can be used for simple servoing with vision.
084     *
085     * @param camera The camera to use
086     */
087    public Rotation2d getTargetX(Camera camera) {
088        return inputs.get(camera).latestTargetObservation.tx();
089    }
090
091    public Optional<Integer> getPipeline() {
092        Iterator<VisionIOInputsAutoLogged> iterator = inputs.values().iterator();
093        return iterator.hasNext() ? Optional.of(iterator.next().currentPipeline) : Optional.empty();
094    }
095
096    @Override
097    public void periodic() {
098        for (Entry<Camera, VisionIO> entry : io.entrySet()) {
099            VisionIO currentIO = entry.getValue();
100            VisionIOInputsAutoLogged currentInputs = inputs.get(entry.getKey());
101            currentIO.updateInputs(currentInputs);
102            Logger.processInputs("Vision/" + entry.getKey().getName(), currentInputs);
103        }
104        Limelight.setSharedRobotOrientation(rotationSupplier.get().getDegrees());
105
106        // inputs should update regardless of being enabled
107        if (!GlobalSettings.EnabledSubsystems.VISION.get()) {
108            return;
109        }
110
111        Optional<Integer> pipeline = getPipeline();
112
113        if (hdrTimer.hasElapsed(VisionConstants.VisionSettings.HDR_SWITCHING_INTERVAL)
114                && VisionConstants.VisionSettings.HDR_ENABLED.get()
115                && pipeline.isPresent()) {
116            int nextPipeline =
117                    pipeline.get() == Pipeline.HIGH_SUN.getIndex()
118                            ? Pipeline.LOW_SUN.getIndex()
119                            : Pipeline.HIGH_SUN.getIndex();
120
121            for (VisionIOOutputs outputs : outputs.values()) {
122                outputs.pipeline = nextPipeline;
123            }
124
125            hdrTimer.reset();
126        }
127
128        // Initialize logging values
129        List<Pose3d> allTagPoses = new LinkedList<>();
130        List<Pose3d> allRobotPoses = new LinkedList<>();
131        List<Pose3d> allRobotPosesAccepted = new LinkedList<>();
132        List<Pose3d> allRobotPosesRejected = new LinkedList<>();
133
134        // Loop over cameras
135        for (Entry<Camera, VisionIO> entry : io.entrySet()) {
136            Camera currentCamera = entry.getKey();
137            VisionIOInputsAutoLogged currentInputs = inputs.get(currentCamera);
138
139            // Update disconnected alert
140            disconnectedAlerts.get(currentCamera).set(!currentInputs.connected);
141
142            // Initialize logging values
143            List<Pose3d> tagPoses = new LinkedList<>();
144            List<Pose3d> robotPoses = new LinkedList<>();
145            List<Pose3d> robotPosesAccepted = new LinkedList<>();
146            List<Pose3d> robotPosesRejected = new LinkedList<>();
147
148            // Add tag poses
149            for (int tagId : currentInputs.tagIds) {
150                Optional<Pose3d> tagPose = FieldConstants.FIELD_LAYOUT.getTagPose(tagId);
151                if (tagPose.isPresent()) {
152                    tagPoses.add(tagPose.get());
153                }
154            }
155
156            // Loop over pose observations
157            for (PoseObservation observation : currentInputs.poseObservations) {
158                // Check whether to reject pose
159                boolean rejectPose =
160                        observation.tagCount() == 0 // Must have at least one tag
161                                || (observation.tagCount() == 1
162                                        && observation.ambiguity()
163                                                > VisionSettings
164                                                        .MAX_AMBIGUITY) // Cannot be high ambiguity
165                                || Math.abs(observation.pose().getZ())
166                                        > VisionSettings
167                                                .MAX_Z_ERROR // Must have realistic Z coordinate
168
169                                // Must be within the field boundaries
170                                || observation.pose().getX() < 0.0
171                                || observation.pose().getX()
172                                        > FieldConstants.FIELD_LAYOUT.getFieldLength()
173                                || observation.pose().getY() < 0.0
174                                || observation.pose().getY()
175                                        > FieldConstants.FIELD_LAYOUT.getFieldWidth();
176
177                // Add pose to log
178                robotPoses.add(observation.pose());
179                if (rejectPose) {
180                    robotPosesRejected.add(observation.pose());
181                } else {
182                    robotPosesAccepted.add(observation.pose());
183                }
184
185                // Skip if rejected
186                if (rejectPose) {
187                    continue;
188                }
189
190                // Calculate standard deviations
191                double stdDevFactor =
192                        Math.pow(observation.averageTagDistance(), 2.0) / observation.tagCount();
193                double linearStdDev = VisionSettings.LINEAR_STD_DEV_BASELINE * stdDevFactor;
194                double angularStdDev = VisionSettings.ANGULAR_STD_DEV_BASELINE * stdDevFactor;
195                if (observation.type() == PoseObservationType.MEGATAG_2) {
196                    linearStdDev *= VisionSettings.LINEAR_STD_DEV_MEGATAG_2_FACTOR;
197                    angularStdDev *= VisionSettings.ANGULAR_STD_DEV_MEGATAG_2_FACTOR;
198                }
199                linearStdDev *= currentCamera.getStdDevFactor();
200                angularStdDev *= currentCamera.getStdDevFactor();
201
202                // Send vision observation
203                consumer.accept(
204                        observation.pose().toPose2d(),
205                        observation.timestamp(),
206                        VecBuilder.fill(linearStdDev, linearStdDev, angularStdDev));
207            }
208
209            // Log camera metadata
210            Logger.recordOutput(
211                    "Vision/Camera_" + currentCamera.getName() + "/TagPoses",
212                    tagPoses.toArray(new Pose3d[tagPoses.size()]));
213            Logger.recordOutput(
214                    "Vision/Camera_" + currentCamera.getName() + "/RobotPoses",
215                    robotPoses.toArray(new Pose3d[robotPoses.size()]));
216            Logger.recordOutput(
217                    "Vision/Camera_" + currentCamera.getName() + "/RobotPosesAccepted",
218                    robotPosesAccepted.toArray(new Pose3d[robotPosesAccepted.size()]));
219            Logger.recordOutput(
220                    "Vision/Camera_" + currentCamera.getName() + "/RobotPosesRejected",
221                    robotPosesRejected.toArray(new Pose3d[robotPosesRejected.size()]));
222            allTagPoses.addAll(tagPoses);
223            allRobotPoses.addAll(robotPoses);
224            allRobotPosesAccepted.addAll(robotPosesAccepted);
225            allRobotPosesRejected.addAll(robotPosesRejected);
226        }
227
228        // Log summary data
229        Logger.recordOutput("Vision/Summary/TagPoses", allTagPoses.toArray(new Pose3d[0]));
230        Logger.recordOutput("Vision/Summary/RobotPoses", allRobotPoses.toArray(new Pose3d[0]));
231        Logger.recordOutput(
232                "Vision/Summary/RobotPosesAccepted", allRobotPosesAccepted.toArray(new Pose3d[0]));
233        Logger.recordOutput(
234                "Vision/Summary/RobotPosesRejected", allRobotPosesRejected.toArray(new Pose3d[0]));
235    }
236
237    @Override
238    public void periodicAfterScheduler() {
239        for (Entry<Camera, VisionIO> entry : io.entrySet()) {
240            entry.getValue().applyOutputs(outputs.get(entry.getKey()));
241        }
242    }
243
244    @FunctionalInterface
245    public static interface VisionConsumer {
246        public void accept(
247                Pose2d visionRobotPoseMeters,
248                double timestampSeconds,
249                Matrix<N3, N1> visionMeasurementStdDevs);
250    }
251
252    public void enable() {
253        GlobalSettings.EnabledSubsystems.VISION.set(true);
254    }
255
256    public void disable() {
257        GlobalSettings.EnabledSubsystems.VISION.set(false);
258    }
259
260    public Command setPipeline(int pipeline) {
261        return run(coroutine -> {
262                    for (VisionIOOutputs output : outputs.values()) {
263                        output.pipeline = pipeline;
264                    }
265                })
266                .named("Vision Set Pipeline");
267    }
268
269    public Command setMegaTagMode(MegaTagMode mode) {
270        return run(coroutine -> {
271                    for (VisionIOOutputs output : outputs.values()) {
272                        output.megaTagMode = mode;
273                    }
274                })
275                .named("Vision Set MegaTag Mode");
276    }
277
278    public Command setVisionEnabled() {
279        return run(coroutine -> {
280                    this.enable();
281                })
282                .named("Vision Set Enabled");
283    }
284
285    public Command setVisionDisabled() {
286        return run(coroutine -> {
287                    this.disable();
288                })
289                .named("Vision Set Enabled");
290    }
291
292    public Command setAprilTagWhitelist(int[] whitelist) {
293        return run(coroutine -> {
294                    for (VisionIOOutputs output : outputs.values()) {
295                        output.aprilTagWhitelist = whitelist.clone();
296                    }
297                })
298                .named("Vision Set April Tag Whitelist");
299    }
300
301    private Command setIMUMode(IMUMode imuMode, String name) {
302        return run(coroutine -> {
303                    for (VisionIOOutputs output : outputs.values()) {
304                        output.imuMode = imuMode;
305                    }
306                })
307                .named(name);
308    }
309
310    public Command setIMUMode(IMUMode imuMode) {
311        return setIMUMode(imuMode, "Vision Set IMU Mode");
312    }
313
314    public Command resetIMU() {
315        return setIMUMode(VisionSettings.RESET_IMU_MODE, "Vision Reset IMU");
316    }
317}