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 org.wpilib.math.geometry.Pose3d;
008import org.wpilib.math.geometry.Rotation2d;
009import org.wpilib.math.geometry.Transform3d;
010
011import com.limelightvision.FiducialTarget;
012import com.limelightvision.Limelight;
013import com.limelightvision.LimelightResults;
014import com.limelightvision.PoseEstimateType;
015import java.util.HashSet;
016import java.util.LinkedList;
017import java.util.List;
018import java.util.Set;
019
020/** IO implementation for real Limelight hardware. */
021public class VisionIOLimelight implements VisionIO {
022    private final Limelight camera;
023
024    private MegaTagMode megaTagMode;
025
026    /**
027     * Creates a new VisionIOLimelight.
028     *
029     * @param name The configured name of the Limelight.
030     * @param robotToCamera The 3D position of the camera relative to the robot.
031     */
032    public VisionIOLimelight(String name, Transform3d robotToCamera) {
033        this.camera = new Limelight(name);
034
035        megaTagMode = MegaTagMode.MEGATAG_1;
036
037        camera.setCameraPose_RobotSpaceOverride(
038                new Pose3d(robotToCamera.getTranslation(), robotToCamera.getRotation()), false);
039    }
040
041    @Override
042    public void updateInputs(VisionIOInputs inputs) {
043        inputs.connected = camera.isConnected();
044
045        inputs.currentPipeline = camera.getCurrentPipelineIndex();
046
047        // Update target observation
048        inputs.latestTargetObservation =
049                new TargetObservation(
050                        Rotation2d.fromDegrees(camera.getTXDegrees()),
051                        Rotation2d.fromDegrees(camera.getTYDegrees()));
052
053        // Read new pose observations from NetworkTables
054        Set<Integer> tagIds = new HashSet<>();
055        List<PoseObservation> poseObservations = new LinkedList<>();
056
057        for (LimelightResults rawSample : camera.readResultsQueue()) {
058            if (!rawSample.valid) { // ignore invalid results obv
059                continue;
060            }
061            for (FiducialTarget tag : rawSample.fiducialTargets) {
062                tagIds.add(tag.fiducialId);
063            }
064            double ambiguity = 0.0;
065            // Ambiguity, using only the first tag because ambiguity isn't applicable for multitag
066            if (megaTagMode == MegaTagMode.MEGATAG_1 && rawSample.fiducialTargets.length == 1) {
067                ambiguity = rawSample.fiducialTargets[0].ambiguity;
068            }
069            poseObservations.add(
070                    new PoseObservation(
071                            // Timestamp, based on server timestamp of publish and latency
072                            rawSample.ntTimestampMicros * 1.0e-6
073                                    - rawSample.timestampMillis * 1.0e-3,
074
075                            // 3D pose estimate
076                            megaTagMode == MegaTagMode.MEGATAG_1
077                                    ? rawSample.getRobotPose(PoseEstimateType.MT1_WPIBLUE)
078                                    : rawSample.getRobotPose(PoseEstimateType.MT2_WPIBLUE),
079                            ambiguity,
080
081                            // Tag count
082                            rawSample.fiducialTargets.length,
083
084                            // Average tag distance
085                            rawSample.avgTagDistanceMeters,
086
087                            // Observation type
088                            megaTagMode == MegaTagMode.MEGATAG_1
089                                    ? PoseObservationType.MEGATAG_1
090                                    : PoseObservationType.MEGATAG_2));
091        }
092
093        // Save pose observations to inputs object
094        inputs.poseObservations = new PoseObservation[poseObservations.size()];
095        for (int i = 0; i < poseObservations.size(); i++) {
096            inputs.poseObservations[i] = poseObservations.get(i);
097        }
098
099        // Save tag IDs to inputs objects
100        inputs.tagIds = new int[tagIds.size()];
101        int i = 0;
102        for (int id : tagIds) {
103            inputs.tagIds[i++] = id;
104        }
105    }
106
107    @Override
108    public void applyOutputs(VisionIOOutputs outputs) {
109        camera.setPipelineIndex(outputs.pipeline);
110
111        this.megaTagMode = outputs.megaTagMode;
112
113        camera.setFiducialIDFiltersOverride(outputs.aprilTagWhitelist);
114        camera.setIMUMode(outputs.imuMode);
115    }
116}