# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://yall.yassrobotics.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Yet Another Limelight Library

Yet Another Limelight Library — a WPILib vendordep for Limelight vision on FRC robots

**YALL** is a WPILib vendordep for FRC teams using [Limelight](https://limelightvision.io/) smart cameras. It wraps Limelight's NetworkTables API and JSON results output in a typed, chainable Java API — one object per camera, chainable settings, MegaTag1/MegaTag2 pose estimation, and typed results for every pipeline type. A parallel Python port ships alongside it.

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><h4><i class="fa-book" style="color:$primary;">:book:</i></h4></td><td><strong>Documentation</strong></td><td>Tutorials, how-to guides, and explanations for using YALL on your robot.</td><td><a href="https://yall.yassrobotics.com/documentation/">Documentation</a></td></tr><tr><td><h4><i class="fa-terminal" style="color:$primary;">:terminal:</i></h4></td><td><strong>API Reference</strong></td><td>Every class, field, and method, organized by package.</td><td><a href="https://yall.yassrobotics.com/api-reference/">API Reference</a></td></tr><tr><td><h4><i class="fa-github" style="color:$primary;">:github:</i></h4></td><td><strong>Source</strong></td><td>Source code, issues, and releases.</td><td><a href="https://github.com/BroncBotz3481/YALL">https://github.com/BroncBotz3481/YALL</a></td></tr></tbody></table>

## Install

Add the vendordep in WPILib VS Code (**WPILib: Manage Vendor Libraries → Install new library (online)**) using:

```
https://Yet-Another-Software-Suite.github.io/YALL/yall.json
```

## Quick example

```java
Limelight limelight = new Limelight("limelight");

limelight.getSettings()
         .withLimelightLEDMode(LEDMode.PipelineControl)
         .withCameraOffset(Pose3d.kZero)
         .save();

Optional<PoseEstimate> visionEstimate = limelight.createPoseEstimator(EstimationMode.MEGATAG2)
                                                  .getPoseEstimate();
visionEstimate.ifPresent(estimate ->
    poseEstimator.addVisionMeasurement(estimate.pose.toPose2d(), estimate.timestampSeconds));
```

## Part of Yet Another Software Suite

YALL is one of several FRC vendor libraries maintained under **Yet Another Software Suite**, alongside [YAGSL](https://github.com/Yet-Another-Software-Suite/YAGSL) (swerve drive) and [YAMS](https://github.com/Yet-Another-Software-Suite/YAMS) (mechanisms).


# Welcome

Welcome to the **Yet Another Limelight Library (YALL)** documentation!

YALL is a WPILib vendordep that wraps [Limelight](https://limelightvision.io/)'s NetworkTables API and JSON results output in a typed, chainable Java (and Python) API for FRC robots. It replaces the raw `LimelightHelpers` script with real objects: a `Limelight` per camera, chainable settings, MegaTag1/MegaTag2 pose estimation, and typed results for every pipeline type, including AprilTag, retroreflective, neural classifier/detector, and barcode.

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><h4><i class="fa-bolt">:bolt:</i></h4></td><td><strong>Basic setup</strong></td><td>Create your first Limelight object and configure it.</td><td><a href="/documentation/tutorials/basic-setup">Basic Setup</a></td></tr><tr><td><h4><i class="fa-crosshairs">:crosshairs:</i></h4></td><td><strong>AprilTag pose estimation</strong></td><td>Fuse MegaTag2 vision measurements into your pose estimator.</td><td><a href="/documentation/tutorials/apriltag-pose-estimation">AprilTag Pose Estimation</a></td></tr><tr><td><h4><i class="fa-eye">:eye:</i></h4></td><td><strong>Object detection</strong></td><td>Read neural classifier and detector results.</td><td><a href="/documentation/tutorials/object-detection">Object Detection</a></td></tr><tr><td><h4><i class="fa-display">:display:</i></h4></td><td><strong>Simulation</strong></td><td>Exercise vision code in desktop simulation without hardware.</td><td><a href="/documentation/tutorials/simulating-a-limelight">Simulating a Limelight</a></td></tr></tbody></table>

### Where to go next

* **Tutorials**: step-by-step walkthroughs for common setups.
* **How-to guides**: focused answers to specific "how do I…" questions.
* [**Tuning**](/documentation/tuning/tuning-workflow-overview): the tuning steps from Limelight's own documentation, reorganized into the order you'd actually apply them (sensor settings, crosshair/camera calibration, pipeline-specific tuning, then PID).
* **Understanding**: explanations of how YALL's settings, pose estimation, and results model work.
* **API Reference** (YALL-Gitbook-API space): every class, field, and method.
* [**Javadocs**](https://yet-another-software-suite.github.io/YALL/javadocs/): generated API docs.
* [**GitHub**](https://github.com/BroncBotz3481/YALL): source, issues, and releases.


# Why YALL?

## The problem with LimelightHelpers

LimelightVision publishes [`LimelightHelpers`](https://github.com/LimelightVision/limelightlib-wpijava) as a single drop-in `.java` file, a set of static methods keyed by raw NetworkTables entry names (`ledMode`, `pipeline_set`, `botpose_wpiblue`, `rawfiducials`, ...). It's simple, but that simplicity has costs:

* Every call re-fetches an NT entry, so no typed object holds settings or results for you.
* MegaTag1 vs. MegaTag2, alliance color, and coordinate frame are separate helper methods, easy to mix up.
* Results decode into loose arrays and parallel static fields, not classes.
* There's no chaining, since configuring a camera means many independent one-line calls with no obvious grouping.
* AprilTag ambiguity, standard deviations, and per-tag detail live in different places depending on which method you called.

## What YALL replaces it with

YALL models the same underlying NetworkTables API as **one object per camera**, with typed sub-objects for every concern:

```java
Limelight limelight = new Limelight("limelight");

limelight.getSettings()
         .withLimelightLEDMode(LEDMode.PipelineControl)
         .withCameraOffset(cameraOffset)
         .save();

LimelightPoseEstimator poseEstimator = limelight.createPoseEstimator(EstimationMode.MEGATAG2);
```

* **`Limelight`**: one per physical camera, resolves and validates its NT table by name.
* **`LimelightSettings`**: every writable setting as a chainable `.withXXXX()` call.
* **`LimelightPoseEstimator`** / **`PoseEstimate`**: MegaTag1/MegaTag2 pose, alliance-aware, with per-tag ambiguity already decoded for filtering.
* **`LimelightResults`**: the full JSON frame, with typed arrays for every pipeline type instead of parallel loose fields.
* **`LimelightData`**: direct, cheap NetworkTables reads (raw fiducials/detections, barcodes, Python I/O) for callers who don't need the full JSON parse.

## MegaTag2 done correctly

MegaTag2 requires the robot to submit its current heading to the Limelight every loop *before* reading a pose estimate, a step that's easy to get wrong or forget with raw NetworkTables calls. YALL makes the requirement explicit through the API:

```java
limelight.getSettings()
         .withRobotOrientation(new Orientation3d(gyro.getRotation3d(),
                                                  new AngularVelocity3d(DegreesPerSecond.of(gyro.getPitchVelocity()),
                                                                        DegreesPerSecond.of(gyro.getRollVelocity()),
                                                                        DegreesPerSecond.of(gyro.getYawVelocity()))))
         .save();

Optional<PoseEstimate> visionEstimate = limelight.createPoseEstimator(EstimationMode.MEGATAG2).getPoseEstimate();
```

`PoseEstimate` carries `tagCount`, `avgTagDist`, `avgTagArea`, and per-tag `RawFiducial` ambiguity so you can gate `addVisionMeasurement` calls without hand-rolling the array decoding yourself. See [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity).

## One API, every pipeline type

Whatever pipeline is active (AprilTag, retroreflective, neural classifier, neural detector, or barcode), `LimelightResults` exposes it as a typed array (`targets_Fiducials`, `targets_Retro`, `targets_Classifier`, `targets_Detector`, `targets_Barcode`) instead of a grab-bag of loosely related fields. See [Target & Pipeline Types](/documentation/understanding/target-and-pipeline-types).

## Raw data when you need speed

`getLatestResults()` parses a full JSON payload with Jackson on every call. When a periodic loop only needs tag or detection geometry, `LimelightData.getRawFiducials()` / `getRawDetections()` read the equivalent NetworkTables double-array entries directly, with no JSON parsing at all. See [Results JSON vs. Raw NetworkTables](/documentation/understanding/results-json-vs-raw-networktables).

## Simulation without hardware

`LimelightHelpers` has no simulation story: without a physical camera on the network, every NT entry it reads is empty. YALL ships `LimelightSim`, which projects the current season's AprilTags into a simple camera model from your simulated robot pose and publishes the same NetworkTables keys real hardware would. Code written against `Limelight`, `LimelightData`, and `LimelightPoseEstimator` runs unchanged in desktop simulation. See [Simulating a Limelight](/documentation/tutorials/simulating-a-limelight).

The `Field2d` raycast visualization that makes this easy to watch in action was contributed by FRC Team 9738.

## Java and Python, one model

YALL ships a Python port alongside the Java library with the same class names and (mostly) the same method names, so teams that write robot code in Python aren't stuck hand-rolling their own wrapper. See [Python & C++ Support](/documentation/understanding/python-and-cpp-support).

The Python port was originally written by FRC Team 9738 and merged into YALL for the whole community to use.


# Basic Setup

This tutorial creates a `Limelight`, configures it, and reads its 2D target data: the minimum setup for any pipeline type.

## 1. Install YALL

See [How do I install YALL?](/documentation/how-to-guides/how-do-i-install-yall) if you haven't added the vendordep yet.

## 2. Create the Limelight object

Create one `Limelight` per physical camera, named after its NetworkTables table (the name shown in the Limelight web UI, usually `limelight`):

```java
import limelight.Limelight;

Limelight limelight = new Limelight("limelight");
```

{% hint style="info" %}
Construction checks that the camera's NT table exists (skipped in simulation) and raises a WPILib `Alert` if it doesn't. Do this once, in your subsystem constructor, not in `periodic()`.
{% endhint %}

## 3. Configure it

`getSettings()` returns a chainable configuration object. Every `.withXXXX()` call applies immediately and returns `this`:

```java
import limelight.networktables.LimelightSettings.LEDMode;
import edu.wpi.first.math.geometry.Pose3d;

limelight.getSettings()
         .withLimelightLEDMode(LEDMode.PipelineControl)
         .withCameraOffset(Pose3d.kZero)
         .save();
```

`withCameraOffset` sets where the camera physically sits relative to robot center. Get this right, since MegaTag pose estimation is only as accurate as this offset. See [LimelightSettings & Pipelines](/documentation/understanding/limelight-settings-and-pipelines) for the full option list.

## 4. Read 2D target data

For simple aiming (turn-to-target, distance-to-target), `getData().targetData` gives you crosshair-relative offsets without any pose estimation:

```java
if (limelight.getData().targetData.getTargetStatus()) {
    double tx = limelight.getData().targetData.getHorizontalOffset();
    double ty = limelight.getData().targetData.getVerticalOffset();
    // turn toward tx, adjust range using ty
}
```

Always check `getTargetStatus()` before trusting `tx`/`ty`, since they hold stale values when no target is visible.

## Next steps

* [AprilTag Pose Estimation](/documentation/tutorials/apriltag-pose-estimation): fuse MegaTag2 into your robot's pose estimator.
* [Object Detection](/documentation/tutorials/object-detection): read neural classifier/detector results.
* [Simulating a Limelight](/documentation/tutorials/simulating-a-limelight): exercise this same code in desktop simulation.
* [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)
* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview): once basic setup works, this is the recommended order for getting accurate, reliable results out of whichever pipeline you're using.


# AprilTag Pose Estimation

This tutorial fuses Limelight MegaTag2 vision measurements into a WPILib pose estimator, the way `DrivebaseSubsystem` does in YALL's [example project](https://github.com/BroncBotz3481/YALL/tree/main/example).

## 1. Set up the camera offset once

MegaTag needs to know where the camera sits relative to robot center. Do this at construction time:

```java
Pose3d cameraOffset = new Pose3d(Inches.of(5).in(Meters),
                                  Inches.of(5).in(Meters),
                                  Inches.of(5).in(Meters),
                                  Rotation3d.kZero);

limelight = new Limelight("limelight");
limelight.getSettings()
         .withLimelightLEDMode(LEDMode.PipelineControl)
         .withCameraOffset(cameraOffset)
         .save();

poseEstimator = limelight.createPoseEstimator(EstimationMode.MEGATAG2);
```

## 2. Submit robot orientation every loop

MegaTag2 fuses AprilTag detections with your robot's current heading. This only works if you tell the Limelight your heading **every periodic loop, before reading a pose estimate**:

```java
@Override
public void periodic() {
    limelight.getSettings()
             .withRobotOrientation(new Orientation3d(gyro.getRotation3d(),
                                                      new AngularVelocity3d(DegreesPerSecond.of(0),
                                                                            DegreesPerSecond.of(0),
                                                                            DegreesPerSecond.of(0))))
             .save();
    // ...
}
```

{% hint style="warning" %}
Skip this step and MegaTag2 pose estimates will be inaccurate or stale. This is the single most common mistake when adopting MegaTag2. See [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)
{% endhint %}

## 3. Read and filter the pose estimate

```java
Optional<PoseEstimate> visionEstimate = poseEstimator.getPoseEstimate();
visionEstimate.ifPresent((PoseEstimate poseEstimate) -> {
    // Reject long-range or ambiguous reads before fusing.
    if (poseEstimate.avgTagDist < 4
        && poseEstimate.tagCount > 0
        && poseEstimate.getMinTagAmbiguity() < 0.3) {
        poseEstimator.addVisionMeasurement(poseEstimate.pose.toPose2d(), poseEstimate.timestampSeconds);
    }
});
```

`poseEstimator` above is your WPILib `SwerveDrivePoseEstimator` / `DifferentialDrivePoseEstimator`, a different object than YALL's `LimelightPoseEstimator`. Filtering on tag count, distance, and ambiguity before calling `addVisionMeasurement` keeps a single noisy or distant reading from corrupting your odometry.

## Alternative: the BotPose enum directly

If you don't need a `LimelightPoseEstimator` instance around, `BotPose` gives the same data directly:

```java
Optional<PoseEstimate> estimate = BotPose.BLUE_MEGATAG2.get(limelight);
```

Or fetch the alliance-relative estimate without checking `DriverStation` yourself:

```java
Optional<PoseEstimate> estimate = poseEstimator.getAlliancePoseEstimate();
```

## Next steps

* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity): what each `PoseEstimate` field means and how to tune your filter thresholds.
* [How do I mount a Limelight on a moving mechanism?](/documentation/how-to-guides/how-do-i-mount-a-limelight-on-a-moving-mechanism): updating `withCameraOffset` dynamically for a turret.
* [How do I filter AprilTags by ID?](/documentation/how-to-guides/how-do-i-filter-apriltags-by-id)
* [Simulating a Limelight](/documentation/tutorials/simulating-a-limelight): exercise this fusion code in desktop simulation without hardware.
* [AprilTag & MegaTag2 Localization Tuning](/documentation/tuning/apriltag-and-megatag2-tuning): IMU modes, assist alpha, and the setup mistakes that silently break MegaTag2.
* [ChArUco Camera Calibration](/documentation/tuning/charuco-camera-calibration): improves the accuracy of every pose this tutorial produces.


# Object Detection

This tutorial reads neural classifier results, the pipeline type used for game-piece detection (e.g. spotting a piece on the field before intaking it).

## 1. Switch to a classifier or detector pipeline

Configure the correct pipeline index in the Limelight web UI, or switch it from code:

```java
limelight.getSettings().withPipelineIndex(1).save();
```

## 2. Read results from the JSON payload

`getLatestResults()` returns the full frame, including whichever target arrays are populated for the active pipeline:

```java
limelight.getLatestResults().ifPresent((LimelightResults result) -> {
    for (NeuralClassifier object : result.targets_Classifier) {
        if (object.className.equals("algae") && object.confidence > 0.7) {
            // valid detection: object.tx / object.ty give position in the image
        }
    }
});
```

`targets_Classifier` is empty unless the active pipeline is a neural classifier pipeline. Check `result.pipeline_type` if you're unsure which pipeline produced a frame.

## 3. Neural Detector: bounding boxes instead of whole-frame labels

If your pipeline is a **detector** (bounding boxes) rather than a **classifier** (whole-frame/zone label), read `targets_Detector` instead. It's the same `LimelightResults` object, just a different array:

```java
limelight.getLatestResults().ifPresent((LimelightResults result) -> {
    for (NeuralDetector object : result.targets_Detector) {
        if (object.className.equals("coral")) {
            // object.tx / object.ty are crosshair-relative degrees, like an AprilTag result
            // object.ta is the bounding box area as a percentage of the image
        }
    }
});
```

## 4. Faster path: raw detections without JSON parsing

If you only need position and don't need `className`/`confidence`, `LimelightData.getRawDetections()` decodes the `rawdetections` NetworkTables entry directly, including the four bounding-box corners, which the JSON `NeuralDetector` result doesn't expose:

```java
for (RawDetection detection : limelight.getData().getRawDetections()) {
    // detection.classId, detection.txnc, detection.tync, detection.ta
    // detection.corner0_X .. detection.corner3_Y (pixel coordinates)
}
```

## Next steps

* [Target & Pipeline Types](/documentation/understanding/target-and-pipeline-types): every target type and what pipeline produces it.
* [Results JSON vs. Raw NetworkTables](/documentation/understanding/results-json-vs-raw-networktables): when to use `getLatestResults()` vs. the raw accessors.
* [Tuning a Neural Network Pipeline](/documentation/tuning/neural-network-pipeline-tuning): confidence threshold and crop window.


# Simulating a Limelight

This tutorial adds a simulated Limelight to your robot code so that vision dependent behavior (aiming, MegaTag pose fusion, object reactions) can be exercised in desktop simulation without physical hardware.

* `LimelightSim` projects AprilTags from the current season's field onto a simulated camera.
* It publishes the same NetworkTables keys real Limelight hardware would.
  * Nothing downstream (`LimelightData`, `LimelightTargetData`, `LimelightPoseEstimator`) needs to know it isn't talking to a real camera.

{% hint style="info" %}
The overall design (a per camera simulation object fed the robot's ground truth pose every loop, projecting field targets into a camera model to publish simulated output) is based on PhotonVision's `VisionSystemSim`/`PhotonCameraSim` classes. Credit to the PhotonVision project for that approach. YALL's implementation is a self contained port of the idea onto the Limelight NetworkTables schema and does not depend on PhotonVision at runtime.
{% endhint %}

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-19ad9956faf6338315a5532bab52e0978577296b%2Flimelight-sim-raycasts.gif?alt=media" alt=""><figcaption><p>The robot driving around the field in desktop simulation, with <code>withField2d</code> drawing a raycast to every AprilTag currently in view.</p></figcaption></figure>

## 1. Create the LimelightSim

* Construct one `LimelightSim` per `Limelight`, right next to where you construct the `Limelight` itself:

```java
import limelight.Limelight;
import limelight.sim.LimelightSim;

Limelight limelight = new Limelight("limelight");
LimelightSim limelightSim = new LimelightSim(limelight);
```

* No further configuration is required. By default `LimelightSim`:
  * Loads the current season's official AprilTag field.
  * Assumes the camera sits at the robot's origin.
  * Uses Limelight 3 like resolution, field of view, latency, and noise.

## 2. Match the camera offset you already configured

* If you called `withCameraOffset` on the real `Limelight`, give the simulation the same transform so the simulated camera looks out from the same point:

```java
limelightSim.withRobotToCameraTransform(
    new Transform3d(cameraOffset.getTranslation(), cameraOffset.getRotation()));
```

* The translation is the camera's offset from the center of the robot, in meters, not from any other reference point on the chassis.

## 3. Update it from simulationPeriodic

* Feed it the robot's ground truth pose (from your drivetrain simulation) every simulation loop:

```java
@Override
public void simulationPeriodic() {
    limelightSim.update(driveSimulation.getSimulatedDriveTrainPose());
}
```

* That's it. From the simulated pose, `LimelightSim` updates:
  * `tx`/`ty`/`ta`/`tv`/`tid`
  * every `botpose*` variant
  * `rawfiducials`
  * `t2d`
  * the target/camera relative poses
  * the `json` results blob
  * the same as they would from a real Limelight watching the same field.

### Finding a ground truth pose from a YAMS SwerveDrive

* If your drivetrain is a YAMS `SwerveDrive`, `getPose()` is the same kind of thing `DifferentialDrivePoseEstimator.getEstimatedPosition()` is for a tank drive: the fused odometry estimate, not ground truth.
  * Feeding it back into `LimelightSim.update(...)` would make the simulated camera and the pose estimator each assume the other is correct, so vision correction would never actually show up as a change.
* YAMS now exposes `SwerveDrive#getSimPose()`, which already tracks this same ground truth pose for you. Prefer it over the manual integration below when it's available.
* The manual approach below is still worth knowing for tank drives or older YAMS versions without `getSimPose()`: integrate `SwerveDrive#getDesiredChassisSpeeds()` into a separate pose every simulation loop:

```java
Pose2d simulatedPose = Pose2d.kZero;
double lastTimestampSeconds = Timer.getFPGATimestamp();

@Override
public void simulationPeriodic() {
    swerveDrive.simIterate();

    double now = Timer.getFPGATimestamp();
    double dt = now - lastTimestampSeconds;
    lastTimestampSeconds = now;

    ChassisSpeeds desired = swerveDrive.getDesiredChassisSpeeds();
    Twist2d twist = new Twist2d(desired.vxMetersPerSecond * dt, desired.vyMetersPerSecond * dt,
                                 desired.omegaRadiansPerSecond * dt);
    simulatedPose = simulatedPose.exp(twist);

    limelightSim.update(simulatedPose);
}
```

* `getDesiredChassisSpeeds()` returns the last commanded robot-relative speed.
  * It's a setpoint rather than a measurement, which is exactly what makes it convenient here: you get a usable ground truth pose without needing per-module `DCMotorSim` wiring first.
* `Pose2d#exp` treats a `Twist2d` as robot-relative, so this composes correctly whether the drive is moving straight, strafing, or rotating in place.
* If you've already wired up module-level simulation and want the simulated pose to track actual rather than commanded motion, integrate `getRobotRelativeSpeed()` the same way instead.
* This is the same pattern the example project's tank-drive `DrivebaseSubsystem` uses with its wheel speeds: keep a ground truth pose separate from odometry, and only feed that separate pose into `LimelightSim`.

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-6d2d507c765797d021ec6112a252ffaeae10f1ea%2Flimelight-sim-networktables.png?alt=media" alt=""><figcaption><p>The full set of keys <code>LimelightSim</code> publishes, viewed in the WPILib Sim GUI's NetworkTables panel.</p></figcaption></figure>

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-273a4739acbcdced0ac5fcaf648b23fd8737b9bd%2Flimelight-sim-detection.png?alt=media" alt=""><figcaption><p>A visible tag: <code>tv</code>, <code>tx</code>, <code>ty</code>, <code>tid</code>, and <code>tdist</code> updating from the simulated pose shown in the <code>Field2d</code> panel on the left.</p></figcaption></figure>

{% hint style="warning" %}
`LimelightSim` reads `robot_orientation_set` to source the yaw used for MegaTag2, exactly like real hardware does. Keep submitting `withRobotOrientation` every loop in simulation too, or MegaTag2 output will use a stale heading.
{% endhint %}

## Visualizing raycasts on a Field2d

{% hint style="info" %}
This visualization was contributed by FRC Team 9738. Thanks to them for it.
{% endhint %}

* Pass a `Field2d` to `withField2d` and `LimelightSim` draws a line from the robot to every AprilTag it currently sees, so you can watch detections come and go as the robot moves instead of reasoning about it purely from NT values:

```java
Field2d field2d = new Field2d();
SmartDashboard.putData("Field", field2d);

limelightSim.withField2d(field2d);
```

* This creates a single `FieldObject2d` named `Limelight Raycasts` on the `Field2d`.
  * It does not set the `Field2d`'s own robot pose, so keep doing that yourself (`field2d.setRobotPose(...)`) alongside it.
* Pass `null` to turn visualization off again and clear the existing raycasts.

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-7f52435ddbdd20fdf8386670ffba599b1a46648c%2Flimelight-sim-raycast-single.png?alt=media" alt=""><figcaption><p>One tag in view: a single raycast from the robot to it.</p></figcaption></figure>

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-d4e41214b7518606a934c1ae374bfb826a9a2e2e%2Flimelight-sim-raycast-multi.png?alt=media" alt=""><figcaption><p>Two tags in view at once: a separate raycast to each.</p></figcaption></figure>

## Tuning the simulated camera

* `LimelightSimSettings` covers resolution, field of view, tag size, detection range, latency, and noise, each with a `withXXX` method and a Limelight 3 like default:

```java
LimelightSim limelightSim = new LimelightSim(limelight,
    new LimelightSimSettings()
        .withResolution(1280, 800)
        .withFOV(82.9, 56.0)
        .withMaxDetectionRange(5.5)
        .withPipelineLatency(35, 5));
```

* Use `LimelightSimSettings.perfect()` when writing a unit test that needs deterministic, noise free output.

## Scope

* Only the AprilTag/fiducial pipeline is simulated. Retroreflective, neural classifier/detector, and barcode pipelines are not.
* Robot pose and tag geometry are known exactly by the simulator, so instead of re-deriving a pose estimate the way the real firmware does with solvePnP, every `botpose*` entry is the ground truth robot pose with configurable Gaussian noise applied.
  * Treat it as a reasonable approximation for exercising downstream code, not a source of physically accurate MegaTag uncertainty.

## Next steps

* [Basic Setup](/documentation/tutorials/basic-setup): if you haven't created a `Limelight` yet.
* [AprilTag Pose Estimation](/documentation/tutorials/apriltag-pose-estimation): the fusion code this simulation lets you exercise without hardware.
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)


# How do I install YALL?

## Vendordep (recommended)

In WPILib VS Code: **WPILib: Manage Vendor Libraries → Install new library (online)**, then paste:

```
https://Yet-Another-Software-Suite.github.io/YALL/yall.json
```

## Manual installation

Download the latest release from the [releases page](https://github.com/BroncBotz3481/YALL/releases) and drop it into `src/main` of your FRC project.

## Verify it worked

```java
import limelight.Limelight;
```

should resolve without errors after a Gradle sync. Javadocs for every class are at [yet-another-software-suite.github.io/YALL/javadocs](https://yet-another-software-suite.github.io/YALL/javadocs/).

## See Also

* [Basic Setup](/documentation/tutorials/basic-setup)


# How do I choose between MegaTag1 and MegaTag2?

## Short answer

Use **MegaTag2** unless you have a specific reason not to. It's smoother, more accurate at range and oblique angles, and is what `LimelightPoseEstimator.getPoseEstimate()` and `BotPose.BLUE`/`RED` recommend over their non-`_MEGATAG2` counterparts.

## The tradeoff

|                                               | MegaTag1                      | MegaTag2                                                                   |
| --------------------------------------------- | ----------------------------- | -------------------------------------------------------------------------- |
| Data required                                 | Visual only (single AprilTag) | AprilTag + robot heading, submitted every loop                             |
| Accuracy at range / oblique angles            | Lower                         | Higher                                                                     |
| Setup complexity                              | None beyond camera offset     | Must call `withRobotOrientation` every periodic loop before reading a pose |
| Fails silently if orientation isn't submitted | N/A                           | **Yes**: stale/inaccurate poses with no error                              |

## Using MegaTag1

```java
LimelightPoseEstimator estimator = limelight.createPoseEstimator(EstimationMode.MEGATAG1);
Optional<PoseEstimate> estimate = estimator.getPoseEstimate();
```

No per-loop orientation submission needed.

## Using MegaTag2

```java
LimelightPoseEstimator estimator = limelight.createPoseEstimator(EstimationMode.MEGATAG2);

// Every periodic loop, BEFORE reading a pose estimate:
limelight.getSettings()
         .withRobotOrientation(new Orientation3d(gyro.getRotation3d(),
                                                  new AngularVelocity3d(DegreesPerSecond.of(0),
                                                                        DegreesPerSecond.of(0),
                                                                        DegreesPerSecond.of(0))))
         .save();

Optional<PoseEstimate> estimate = estimator.getPoseEstimate();
```

If your gyro doesn't report angular velocity per-axis, passing zeros for pitch/roll rate is fine, since only yaw rate meaningfully affects MegaTag2's fusion, and even that is optional in most drivetrains.

## See Also

* [AprilTag Pose Estimation tutorial](/documentation/tutorials/apriltag-pose-estimation)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)
* [AprilTag & MegaTag2 Localization Tuning](/documentation/tuning/apriltag-and-megatag2-tuning): the full `ImuMode` breakdown and assist alpha tuning.
* LimelightSettings.ImuMode: for Limelight 4's internal IMU fusion options.


# How do I filter AprilTags by ID?

## Restrict tracking to specific tags

If your field has tags you never want to localize off of (opposing alliance station tags, tags outside your robot's operating area), restrict the fiducial pipeline to a known-good set:

```java
limelight.getSettings()
         .withAprilTagIdFilter(List.of(17, 18, 19, 20, 21, 22, 6, 7, 8, 9, 10, 11))
         .save();
```

This affects every fiducial-based reading from this camera: `LimelightResults.targets_Fiducials`, MegaTag pose estimates, and raw fiducials.

## Prioritize one tag when several are visible

If you need MegaTag to favor a specific tag when multiple are in view (e.g. targeting a specific scoring location), set a priority ID instead of / in addition to a filter:

```java
limelight.getSettings().withPriorityTagId(7).save();
```

## Reading which tag is currently targeted

```java
double currentTagId = limelight.getData().targetData.getAprilTagID();
```

## See Also

* LimelightSettings reference
* [Target & Pipeline Types](/documentation/understanding/target-and-pipeline-types)


# How do I use multiple Limelights?

## Give each camera a unique NT name

Rename each camera in its web UI (Settings tab → team number/name) so their NetworkTables tables don't collide, e.g. `limelight-front` and `limelight-back`.

## Create one Limelight object per camera

```java
Limelight front = new Limelight("limelight-front");
Limelight back  = new Limelight("limelight-back");
```

Each `Limelight`, `LimelightSettings`, `LimelightPoseEstimator`, and `PoseEstimate` instance is bound to its own camera. Nothing is shared or global, so there's no special coordination needed beyond keeping the objects around (usually as subsystem fields).

## Fusing pose estimates from multiple cameras

Feed every camera's filtered `PoseEstimate` into the same drivetrain pose estimator. WPILib's pose estimators accept multiple `addVisionMeasurement` calls per loop from different sources:

```java
for (Limelight ll : List.of(front, back)) {
    ll.getSettings().withRobotOrientation(currentOrientation).save();
    ll.createPoseEstimator(EstimationMode.MEGATAG2).getPoseEstimate().ifPresent(estimate -> {
        if (estimate.tagCount > 0 && estimate.getMinTagAmbiguity() < 0.3) {
            poseEstimator.addVisionMeasurement(estimate.pose.toPose2d(), estimate.timestampSeconds);
        }
    });
}
```

Give each camera an accurate, distinct `withCameraOffset`. This is what lets pose estimates from physically different mounting points agree with each other once fused.

## See Also

* [AprilTag Pose Estimation tutorial](/documentation/tutorials/apriltag-pose-estimation)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)


# How do I mount a Limelight on a moving mechanism?

`withCameraOffset` isn't limited to a fixed, one-time value. Call it every periodic loop with a pose computed from your mechanism's current position when the camera itself moves relative to robot center.

## Example: camera mounted on a rotating turret

Adapted from YALL's `TurretSubsystem` example ([LocalizationExamples](https://github.com/BroncBotz3481/YALL/tree/main/LocalizationExamples)):

```java
@Override
public void periodic() {
    limelight.getSettings()
             .withRobotOrientation(new Orientation3d(new Rotation3d(swerveDrive.getOdometryHeading()),
                                                      new AngularVelocity3d(DegreesPerSecond.of(0),
                                                                            DegreesPerSecond.of(0),
                                                                            DegreesPerSecond.of(0))))
             .withCameraOffset(cameraOffsetFromRobotCenter.rotateAround(
                     turretPivotCenterFromCamera,
                     new Rotation3d(0, 0, turret.getAngle().in(Radians))))
             .save();
}
```

`cameraOffsetFromRobotCenter` is the camera's pose when the turret sits at its zero angle. `rotateAround` re-derives the camera's *current* offset every loop by rotating that fixed pose around the turret's pivot point by the turret's live angle. Without this, MegaTag pose estimates silently assume the camera never moved and drift as the turret rotates.

## Checklist

* Measure `cameraOffsetFromRobotCenter` and the turret pivot point once, physically, at turret-zero.
* Call `withCameraOffset` with the *recomputed* pose every loop, not just once at startup.
* Still submit `withRobotOrientation` every loop for MegaTag2; the two settings are independent (robot heading vs. camera-to-robot offset).

## See Also

* [AprilTag Pose Estimation tutorial](/documentation/tutorials/apriltag-pose-estimation)
* [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)


# How do I read raw fiducials and detections?

`getLatestResults()` parses a full JSON `limelight.results` payload with Jackson every call. If you only need tag/detection geometry and not the full frame, read the equivalent raw NetworkTables entries directly instead.

## Raw AprilTag detections

```java
for (RawFiducial tag : limelight.getData().getRawFiducials()) {
    // tag.id, tag.txnc, tag.tync, tag.ta
    // tag.distToCamera, tag.distToRobot (meters)
    // tag.ambiguity (0-1, lower is more trustworthy)
}
```

This is the same `RawFiducial` type populated in `PoseEstimate.rawFiducials`, since the pose estimator already uses this path internally.

## Raw neural detections

```java
for (RawDetection detection : limelight.getData().getRawDetections()) {
    // detection.classId, detection.txnc, detection.tync, detection.ta
    // detection.corner0_X .. detection.corner3_Y are the bounding-quad corners in pixels
}
```

`RawDetection` includes the four bounding-box corners, which the JSON `NeuralDetector` result does not expose.

## When to use the JSON path instead

Reach for `getLatestResults()` when you need:

* Multiple pipeline types' results at once (e.g. classifier *and* fiducial in the same frame)
* Hardware/IMU telemetry (`HardwareReport`, `IMUResults`, `RewindStats`)
* Barcode or retroreflective results, since there's no raw-NT equivalent for those

## See Also

* [Results JSON vs. Raw NetworkTables](/documentation/understanding/results-json-vs-raw-networktables)
* [Object Detection tutorial](/documentation/tutorials/object-detection)


# How do I reduce thermal output while disabled?

The Limelight processes frames continuously by default, which generates heat even when the robot isn't moving. Throttle frame processing while disabled to cut thermal output:

```java
@Override
public void disabledInit() {
    limelight.getSettings().withThrottle(150).save();
}

@Override
public void autonomousInit() {
    limelight.getSettings().withThrottle(0).save();
}

@Override
public void teleopInit() {
    limelight.getSettings().withThrottle(0).save();
}
```

`withThrottle(n)` skips `n` frames between processed frames. The library's recommendation is **100-200** while disabled; outputs are not zeroed during skipped frames, so this is safe to toggle without side effects on stale readings. Set it back to `0` before you need fresh vision data.

## See Also

* LimelightSettings reference
* [Hardware Telemetry & IMU](/documentation/understanding/hardware-telemetry-and-imu): reading CPU temperature to confirm the throttle helped.


# How do I take snapshots and rewind captures?

## Snapshots (all hardware)

Asynchronously requests the Limelight to save a still image, without blocking the robot loop:

```java
limelight.snapshot("auto-align-attempt");
```

Pass `null` or `""` to let the Limelight auto-name the snapshot. This runs on a background thread via `CompletableFuture`, so it's safe to call from a periodic loop, though it's typically triggered from a button or a one-shot event rather than every cycle.

## Rewind capture (supported hardware only)

Rewind saves a rolling video buffer you can flush to disk on demand, useful for post-match diagnosis of a missed vision read. Enable recording, then trigger a capture:

```java
limelight.getSettings().withRewindEnable(RewindState.ENABLED).save();

// Later, e.g. bound to a driver button after a suspicious auto-align:
limelight.rewindCapture(10); // capture the last 10 seconds, max 165
```

Capture requests are rate-limited to once every 2 seconds on the Limelight and are dropped if a flush is already in progress.

## Checking rewind buffer status

```java
limelight.getLatestResults().ifPresent(result -> {
    if (result.rewindStats != null) {
        boolean isFull = result.rewindStats.bufferUsage >= 1.0;
        double secondsStored = result.rewindStats.storedSeconds;
    }
});
```

## See Also

* Limelight#rewindCapture
* RewindStats reference


# How do I forward USB ports?

Limelight 3A/3G units connected over USB (rather than the robot network) need port forwarding through the roboRIO before their web interface or video stream is reachable from a driver station laptop.

## Set up forwarding once, at robot init

```java
@Override
public void robotInit() {
    Limelight.setupPortForwardingUSB(0); // first USB-connected Limelight
}
```

For a second USB-connected Limelight, use index `1`, and so on. Each index maps to its own IP (`172.29.<index>.1`) and port block.

## Accessing the web UI

| USB index | IP forwarded from      | Web UI URL                             |
| --------- | ---------------------- | -------------------------------------- |
| `0`       | `172.29.0.1:5800-5809` | `http://roboRIO-<team>-FRC.local:5801` |
| `1`       | `172.29.1.1:5810-5819` | `http://roboRIO-<team>-FRC.local:5811` |

The port offset within each block (`+1` for the web UI) matches the Limelight's own documented port layout. `setupPortForwardingUSB` just forwards the whole 10-port block per camera.

## See Also

* Limelight#setupPortForwardingUSB


# Tuning Workflow Overview

[Limelight's own documentation](https://docs.limelightvision.io/) has all of the tuning guidance in this section, but it's spread across a dozen unrelated pages: sensor settings live under "Getting Started," color thresholding lives under the retro pipeline, MegaTag2 IMU tuning lives under AprilTag localization, and PID starting points are buried in a tutorial. This section reorganizes the same guidance into the order you'd actually tune a robot, cross-linked to the YALL API where a step is configured from robot code instead of the web UI.

## The order that works

1. [**Camera sensor settings**](/documentation/tuning/camera-sensor-settings): exposure, black level, gain. Do this first, regardless of pipeline type. Every later step (thresholding, detection, pose accuracy) is easier against a clean image.
2. [**Crosshair calibration**](/documentation/tuning/crosshair-calibration): only if you're driving off `tx`/`ty` directly (visual servoing) rather than a full 3D pose.
3. [**ChArUco camera calibration**](/documentation/tuning/charuco-camera-calibration): only if you need accurate 3D measurements: AprilTag 3D tracking, robot localization, or `getXXXPose_YYYSpace()` calls in general.
4. Pipeline-specific tuning: pick the one matching your active pipeline:
   * [**Retroreflective pipeline tuning**](/documentation/tuning/retroreflective-pipeline-tuning): HSV thresholding, then contour filtering/sorting.
   * [**AprilTag & MegaTag2 localization tuning**](/documentation/tuning/apriltag-and-megatag2-tuning): robot-space offset, field map, IMU mode, assist alpha.
   * [**Neural network pipeline tuning**](/documentation/tuning/neural-network-pipeline-tuning): confidence threshold, crop window.
5. [**PID tuning for aiming & ranging**](/documentation/tuning/pid-tuning-for-aiming-and-ranging): once target tracking itself is stable, tune the control loop that drives on it.

{% hint style="info" %}
Steps 1–4 are almost entirely web UI configuration (the Limelight's pipeline JSON), not YALL API calls. YALL reads the *results* of that tuning; it doesn't perform it. Each page below calls out the few settings that YALL does own, mainly camera offset, robot orientation, and IMU mode.
{% endhint %}

## See Also

* [LimelightSettings & Pipelines](/documentation/understanding/limelight-settings-and-pipelines)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)


# Camera Sensor Settings

Before touching any pipeline's thresholds or filters, tune the camera sensor itself in the Limelight web UI's **Camera Settings** tab. This is the same image feeding every pipeline type, so getting it right first makes AprilTag detection more consistent and retroreflective thresholding dramatically easier.

## Tuning order

1. **Exposure: set it low and fixed.** Low, fixed exposure "blacks out" most ambient and arena lighting, which is exactly what you want: FRC field lighting is bright and inconsistent, and a long or auto-adjusting exposure lets it wash out your target and introduces motion blur while the robot is moving.
2. **Black level offset: raise it next.** This is a sensor-level darkening control, distinct from digital brightness. It further suppresses arena lighting without reintroducing the noise or blur that a longer exposure would.
3. **Sensor gain: use sparingly.** Gain brightens the image but adds noise. If the image is too dark after steps 1–2, prefer combining more black level offset with a touch of gain over raising exposure back up, since that keeps motion blur low.
4. **Red/blue balance: leave alone.** Only touch these if you have a specific color-cast problem; they aren't part of the normal tuning pass.

The goal is a **mostly-black image** where only the target (retroreflective tape, AprilTag, game piece) stands out clearly. Everything downstream, from HSV thresholds to contour filters to AprilTag detection reliability, gets easier against that kind of image.

{% hint style="warning" %}
None of these are exposed through `LimelightSettings`. They're stored in the pipeline's JSON on the Limelight itself and tuned once per pipeline in the web UI, not from robot code.
{% endhint %}

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [Tuning a Retroreflective Pipeline](/documentation/tuning/retroreflective-pipeline-tuning)


# Crosshair Calibration

The crosshair is the reference point `tx`/`ty` (`LimelightTargetData.getHorizontalOffset()` / `getVerticalOffset()`) are measured against. If you're driving directly off `tx`/`ty` (visual servoing, not a full 3D pose), calibrating it correctly is what makes "`tx == 0`" actually mean "aligned with where I want to score," instead of just "aligned with the sensor's optical center."

## Single crosshair mode

Use this when your scoring position and camera angle don't vary.

1. Drive the robot to its ideal scoring location and rotation.
2. Click **Calibrate** in the Limelight web UI.
3. Verify: `tx`/`ty` should now read `0`/`0` when the robot is back in that exact position and rotation.
4. Recalibrate whenever you change field setup or camera mounting. For example, if a practice match reveals a better scoring position, recalibrate during the next lull.

## Dual crosshair mode

Use this for off-axis cameras or shooters that need real-time compensation as range changes. The effective crosshair interpolates between crosshair A and B based on target area.

1. Drive to the **closest** scoring position with ideal rotation, click **Calibrate** for crosshair A.
2. Drive to the **farthest** scoring position with ideal rotation, click **Calibrate** for crosshair B.
3. As the robot moves between those distances, the Limelight uses the target's area to interpolate between A and B automatically, with no additional code required.

{% hint style="info" %}
Crosshair calibration only affects `tx`/`ty` (and the values `LimelightTargetData` reads from them). It has no effect on 3D pose data (`getXXXPose_YYYSpace()`, `PoseEstimate`); that accuracy comes from [camera calibration](/documentation/tuning/charuco-camera-calibration) instead.
{% endhint %}

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [PID Tuning for Aiming & Ranging](/documentation/tuning/pid-tuning-for-aiming-and-ranging)


# ChArUco Camera Calibration

Every `getXXXPose_YYYSpace()` call on `AprilTagFiducial`/`RetroreflectiveTape`, every `PoseEstimate` from `LimelightPoseEstimator`, and AprilTag 3D tracking in general all depend on SolvePnP, which depends on an accurate camera intrinsic calibration. The factory calibration gets you close; a ChArUco calibration done on your specific camera gets you accurate. If you're only using `tx`/`ty` for visual servoing, you can skip this, since it's only worth doing when 3D pose accuracy matters.

## Prepare the board

1. Print a ChArUco board, or display one on a large monitor.
2. Measure and record: grid width and height (count black squares + ArUco markers per row/column; 11×8 is the default board), square size, marker size, and dictionary type (5x5\_100 is the default). **Use calipers** for the square/marker size measurements, since small errors here directly bias the calibration.
3. If printed, mount the board on something rigid (a clipboard works). A warped board produces a bad calibration no matter how many images you capture.

## Capture images

Capture **at least 25 images, 50+ recommended**, with deliberate variety:

* The board filling large and small regions of the frame.
* The board partially off-screen, extending past image edges/corners.
* The board at an angle to the camera, not just parallel to the image plane. Roughly half your captures should show significant foreshortening.

## Run the calibration

1. Create a "Charuco Calibration Preview" pipeline and enter the board settings from step 2 above.
2. Delete any existing snapshots, then capture your new, varied set of images.
3. Go to the **Calibration** tab and click **Calibrate with Snapshots**. This takes 1–2 minutes.
4. Check the results, then download/upload the calibration file to persist it.

## What "good" looks like

| Metric             | Good                         | Investigate if                                                                 |
| ------------------ | ---------------------------- | ------------------------------------------------------------------------------ |
| Reprojection error | < 1 px (0.3–0.8 typical)     | Consistently > 1 px: board is likely warped or the marker measurements are off |
| Pixel aspect ratio | \~1.0 (0.99–1.01 acceptable) | Noticeably off 1.0: same causes as above                                       |

A good calibration's per-image reprojection error plot is tight and evenly scattered around zero. A warning-level calibration shows a visibly larger spread, which is your cue to redo the capture pass with more foreshortened images or a flatter board:

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-20689384514644e25e2a0737aad1c67beee56d7b%2Fcharuco-calibration-good.png?alt=media" alt=""><figcaption><p>A good calibration: low, tightly scattered reprojection error.</p></figcaption></figure>

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-48ef454c0721b3777ff0deea7c684e7314461c33%2Fcharuco-calibration-warning.png?alt=media" alt=""><figcaption><p>A flagged calibration: wider error spread, worth recapturing.</p></figcaption></figure>

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)
* [AprilTag & MegaTag2 Localization Tuning](/documentation/tuning/apriltag-and-megatag2-tuning)


# Tuning a Retroreflective Pipeline

A retroreflective pipeline finds targets in two sequential stages: an HSV color threshold turns the image into a binary mask, then contour filtering/sorting picks which blob(s) in that mask are the real target. Tune them in that order, since filtering a noisy mask is much harder than filtering a clean one.

{% hint style="info" %}
Do the [camera sensor settings](/documentation/tuning/camera-sensor-settings) pass first. A properly dark, low-exposure image makes the threshold step below almost trivial.
{% endhint %}

## Stage 1: HSV color threshold

Switch the web UI's video feed to **threshold** view so you can see the binary mask update live while you tune.

| Slider         | What it does                                                                                                                      |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Hue**        | The "pure" color, independent of brightness (0 = red, \~59 = green). Tune this first, since it's the most discriminating channel. |
| **Saturation** | Color purity: how washed-out (low) vs. pure (high) the color is.                                                                  |
| **Value**      | Brightness: how much black is mixed in.                                                                                           |

Workflow:

1. Use the **eyedropper** tool on the target in the raw camera feed to center the HSV range on it automatically.
2. Refine with the **add**/**subtract** wands rather than dragging sliders blindly.
3. **Raise the minimum Value off of zero.** Leaving it at `0` passes black pixels through the mask, which is almost never what you want.
4. Keep every range **as small as possible**: the tighter the range, the more portable the pipeline is to other fields/lighting rigs.
5. If tracking a red target, enable hue inversion (red wraps around both ends of the hue range).

## Stage 2: Contour filtering and sorting

Once the mask is clean, filter which contours in it count as "the target," in this order:

1. **Target Area**: eliminates obviously-wrong-size blobs first (stadium lights, scoreboard displays). The area slider is quartically scaled, giving finer control at the low end where real FRC targets usually sit.
2. **Target Aspect Ratio**: width ÷ height of the bounding rectangle; discriminates target shape (tall vs. wide). Also nonlinearly scaled.
3. **Target Fullness**: percentage of active pixels inside the bounding rectangle; solid targets approach `1.0`, hollow/U-shaped targets read lower. Use this to reject partial detections that passed area/aspect-ratio by coincidence.
4. **Sort Mode**: how to pick among multiple contours that still pass every filter above. `closest` picks the one nearest the (calibrated) crosshair, usually what you want for aiming.
5. **Target Grouping**: enable dual/tri mode if your real target is made of multiple retroreflective shapes that should be tracked as one.
6. **Smart Speckle Rejection**: apply last, to reject small, close-range artifacts (e.g. LEDs). This is an outlier filter, not a primary one.

{% hint style="warning" %}
Lean on area/aspect-ratio/fullness to do the real work. Outlier rejection (speckle rejection, smart grouping) works *against* you if the individual filters are loose: it starts throwing away legitimate detections instead of noise.
{% endhint %}

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [Target & Pipeline Types](/documentation/understanding/target-and-pipeline-types): `RetroreflectiveTape`, the typed result this pipeline feeds into `LimelightResults`.
* [Crosshair Calibration](/documentation/tuning/crosshair-calibration): needed before "closest" sort mode means what you expect.


# AprilTag & MegaTag2 Localization Tuning

This page covers the setup steps that make MegaTag2 robot localization actually accurate, on top of the basic wiring already covered in the [AprilTag Pose Estimation tutorial](/documentation/tutorials/apriltag-pose-estimation) and [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)

## Why MegaTag beats single-tag pose

A single AprilTag's pose solve is sensitive to noise and near-symmetric ambiguity. MegaTag fuses keypoints from every visible tag into one combined solve, which is far more stable: the more tags and the more spread out they are, the better constrained the result:

<figure><img src="https://323141120-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxvbH7hsvI1wbJLmWKbYA%2Fuploads%2Fgit-blob-a826124d5d4ff7c552db5175f6bbdc8d00b5720a%2Fmegatag-diagram.png?alt=media" alt=""><figcaption><p>MegaTag fuses keypoints across all visible tags. Real-world results are even better than this simplified planar diagram suggests.</p></figcaption></figure>

This is exactly why [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity) recommends filtering `addVisionMeasurement` calls on `tagCount` and `tagSpan`, not just ambiguity: more, more-spread-out tags is the mechanism that makes MegaTag reliable in the first place.

## Prerequisites checklist

1. **Camera offset**: `limelight.getSettings().withCameraOffset(...)` set once, accurately, in robot space. Every localization result is only as good as this offset.
2. **Field map**: upload the correct `.fmap` for the season's field to the Limelight.
3. **Blue-corner origin**: MegaTag2 (2024+) always uses the blue-corner field origin; a mismatched origin convention silently rotates/flips every pose.
4. **Robot orientation every loop**: `withRobotOrientation(...)` must be called every periodic loop, *before* reading a pose estimate. This is the single most common MegaTag2 mistake. Skip it and you get stale or inaccurate poses with no error thrown.

## Tuning the internal IMU (Limelight 4)

`LimelightSettings.ImuMode` controls how the Limelight 4's internal IMU interacts with your externally-submitted orientation:

| `ImuMode`                   | Behavior                                                                                 | When to use                                                                                                            |
| --------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `ExternalImu`               | Internal IMU ignored entirely; MT2 uses only what you submit via `withRobotOrientation`. | Simplest option; fine if your external gyro is trustworthy every loop.                                                 |
| `SyncInternalImu`           | Internal IMU stays synced to your external submissions.                                  | Good default while disabled/pre-match; "seeds" the internal IMU.                                                       |
| `InternalImu`               | Internal IMU drives MT2; external submissions ignored.                                   | Rarely, only if you have no reliable external gyro.                                                                    |
| `InternalImuMT1Assist`      | Internal IMU drives MT2, continuously corrected by filtered MT1 (vision-only) yaw.       | Enabled, vision-heavy matches; gentle correction without needing a gyro.                                               |
| `InternalImuExternalAssist` | Internal IMU drives MT2, continuously corrected by your external submissions.            | Enabled: a good default once your gyro is confirmed working, more robust to a single bad gyro read than `ExternalImu`. |

A common pattern: seed with `SyncInternalImu` (or `ExternalImu`) while disabled, then switch to `InternalImuMT1Assist`/`InternalImuExternalAssist` once enabled:

```java
@Override
public void disabledInit() {
    limelight.getSettings().withImuMode(ImuMode.SyncInternalImu).save();
}

@Override
public void teleopInit() {
    limelight.getSettings().withImuMode(ImuMode.InternalImuExternalAssist).save();
}
```

### Complementary filter alpha

`withImuAssistAlpha(alpha)` (default `0.001`) controls how fast the internal IMU converges toward whichever assist source is active:

* **Lower**: the internal IMU stays stable but corrects drift slowly.
* **Higher**: corrects drift faster, at the cost of reacting more to noise in the assist source, which matters more during rapid turns.

Start at the default and only raise it if you observe heading drift the assist source isn't correcting fast enough.

## Common setup mistakes

* Forgetting `withRobotOrientation(...)` on some loop iterations (e.g. an early `return` before the settings call).
* No `.fmap` uploaded, or an outdated one from a previous season.
* Mounting a Limelight 4 in portrait orientation: its internal IMU requires landscape mounting.
* Assuming the field origin convention from a pre-2024 season still applies.

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [ChArUco Camera Calibration](/documentation/tuning/charuco-camera-calibration): accurate intrinsics are a prerequisite for accurate MegaTag poses.
* [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)


# Tuning a Neural Network Pipeline

Neural classifier and detector pipelines expose far fewer tuning knobs than retroreflective or AprilTag pipelines. Most of the "tuning" work is in the model itself (see Limelight's training documentation for classifiers/detectors), not the pipeline settings. In the web UI, there are two levers worth adjusting:

## Confidence threshold

Both pipeline types expose a **confidence threshold** slider. Raising it rejects lower-confidence detections/classifications outright, giving fewer false positives, but you'll also start missing genuine borderline detections. There's no universal value; raise it until false positives on your specific game pieces/field elements stop, then back off slightly to keep recall reasonable.

`NeuralDetector.confidence` / `NeuralClassifier.confidence` (read via `LimelightResults.targets_Detector` / `targets_Classifier`) reflect whatever passed this threshold. You can still apply an additional, stricter threshold in robot code if you want different behavior per-mode (e.g. stricter during autonomous) without touching the pipeline itself.

## Crop window

Both pipeline types support a **crop window**, restricting inference to a sub-region of the frame:

* For a **detector**, this lets you ignore objects outside a zone you care about (e.g. only the field in front of an intake).
* For a **classifier**, this reduces how much irrelevant background the model has to reason about, which usually improves classification accuracy directly.

`LimelightSettings.withCropWindow(minX, maxX, minY, maxY)` sets the same crop from robot code if you need it to change dynamically (e.g. widening the zone once a game piece is expected to be closer) rather than fixed per-pipeline in the web UI.

## Hardware prerequisite

Neural pipelines require a coprocessor (e.g. Google Coral) connected via the Limelight's USB-A port. If detections/classifications never populate `LimelightResults` regardless of threshold, confirm the accelerator is connected before assuming it's a tuning problem.

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [Target & Pipeline Types](/documentation/understanding/target-and-pipeline-types): the `NeuralClassifier` vs. `NeuralDetector` distinction.
* [Object Detection tutorial](/documentation/tutorials/object-detection)


# PID Tuning for Aiming & Ranging

Once tracking itself is stable (pipeline tuned, [crosshair calibrated](/documentation/tuning/crosshair-calibration)), this is the last step: closing the loop between `tx`/`ty` and drivetrain output. This only applies to direct visual servoing off `tx`/`ty`/`ta` (`limelight.getData().targetData.getHorizontalOffset()` / `getVerticalOffset()` / `getTargetArea()`, as in [Basic Setup](/documentation/tutorials/basic-setup)); if you're driving off a fused `PoseEstimate` instead, this doesn't apply, so tune your pose estimator's trust filters ([Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity)) instead.

## Starting gains

Limelight's own aiming/ranging example uses simple proportional-only control as its starting point, a reasonable baseline before you add integral/derivative terms:

| Term            | Starting value | Drives                                                                                                                                                             |
| --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `kP_aim`        | `-0.1`         | Turn rate, from `tx` (heading error)                                                                                                                               |
| `kP_distance`   | `-0.1`         | Forward/back speed, from `ty` (range error)                                                                                                                        |
| `minAimCommand` | `0.05`         | Deadband floor: the minimum command applied once outside the deadband, so small errors don't get commanded a near-zero output that never overcomes static friction |

The negative sign matters: a positive `tx` (target to the right) should produce a *negative* turn command if your convention is "positive turn = counterclockwise." Get the sign backwards and the loop actively drives away from the target instead of toward it.

## Deadband

Only apply the aim correction once `|tx| > 1.0` degrees (this exact threshold is a starting point, not a hard rule). Without a deadband, the loop chases sensor noise once it's essentially on-target, and oscillates instead of settling.

```java
double tx = limelight.getData().targetData.getHorizontalOffset();
double steer = 0.0;
if (Math.abs(tx) > 1.0) {
    steer = kP_aim * tx;
}
```

## Tuning order

1. **Aim (`tx`) alone first**, with ranging disabled. Confirm the robot settles on heading without oscillating before adding range control.
2. **Range (`ty`/`ta`) alone next**, with aim disabled, same idea: isolate one loop before combining them.
3. **Combine both** once each is independently stable. Combined aim+range is more sensitive to gain that's slightly too high, since heading and distance errors can compound.
4. **Increase `kP` gradually** from the starting values above until the robot responds promptly without overshoot/oscillation at your target distance; back off \~20% from the point oscillation starts.

## See Also

* [Tuning Workflow Overview](/documentation/tuning/tuning-workflow-overview)
* [Crosshair Calibration](/documentation/tuning/crosshair-calibration)
* [Pose Estimation & Ambiguity](/documentation/understanding/pose-estimation-and-ambiguity): the equivalent tuning problem when driving off a fused pose instead of raw `tx`/`ty`.


# LimelightSettings & Pipelines

`LimelightSettings` (from `limelight.getSettings()`) is the only way to change how a Limelight behaves from robot code. Every `.withXXXX()` call writes directly to a NetworkTables entry the Limelight watches. There's no local caching or batching, so changes normally apply within a frame or two. `save()` forces an immediate NT flush but rarely matters since individual writes already propagate quickly.

## Settings are write-only

The constructor fetches current values from the Limelight, but `LimelightSettings` exposes no getters. This is intentional: it exists purely as an attachment point for chained `.withXXXX()` calls, not as a settings mirror. If you need to know the *current* pipeline or LED state, read it back through [`LimelightData`](/documentation/understanding/results-json-vs-raw-networktables) / `LimelightPipelineData` instead.

## The settings groups

| Concern                    | Methods                                                                                                                   |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **LEDs**                   | `withLimelightLEDMode`                                                                                                    |
| **Pipeline**               | `withPipelineIndex`, `withPriorityTagId`, `withAprilTagIdFilter`, `withFiducialDownscalingOverride`, `withAprilTagOffset` |
| **Camera geometry**        | `withCameraOffset`                                                                                                        |
| **Robot state (MegaTag2)** | `withRobotOrientation`, `withImuMode`, `withImuAssistAlpha`                                                               |
| **Stream / crop**          | `withStreamMode`, `withCropWindow`, `withKeystone`                                                                        |
| **Thermal management**     | `withThrottle`                                                                                                            |
| **Rewind (LL4)**           | `withRewindEnable`, `rewindCapture`                                                                                       |

## Pipelines are indices, not objects

YALL doesn't model pipelines as objects. A pipeline is just an index (0-9) configured in the Limelight web UI. `withPipelineIndex(n)` switches which pipeline is active; everything about *what that pipeline does* (its type, whether AprilTag, retroreflective, classifier, or detector; its crop; its color thresholds) is configured in the Limelight UI itself, not from robot code. Robot code reacts to whatever the active pipeline produces, via [target types](/documentation/understanding/target-and-pipeline-types).

## LED mode vs. pipeline LED behavior

`LEDMode.PipelineControl` (the default recommendation) lets each pipeline decide its own LED behavior, configured per-pipeline in the web UI. The `ForceXXX` modes override every pipeline's LED behavior robot-wide, useful for driver signaling (e.g. force-blink LEDs when a game piece is detected) independent of which pipeline is active.

## See Also

* [Basic Setup tutorial](/documentation/tutorials/basic-setup)
* [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)
* LimelightSettings reference


# Pose Estimation & Ambiguity

## Where a pose estimate comes from

A `PoseEstimate` is decoded from one `botpose*` NetworkTables double-array entry, and which one depends on the `BotPose` value used (`BLUE`, `BLUE_MEGATAG2`, `RED`, `RED_MEGATAG2`). `LimelightPoseEstimator.getPoseEstimate()` picks the blue-origin entry matching its `EstimationMode`; `getAlliancePoseEstimate()` picks the entry matching `DriverStation.getAlliance()`.

Each `BotPose` value caches one `PoseEstimate` object per camera it's queried with, so repeated calls in the same loop don't re-allocate, but each call to `getPoseEstimate()` does re-read NetworkTables and re-decode the array.

## Why you must filter before fusing

Not every pose estimate is trustworthy. A single distant or oblique-angle tag can produce a pose that's technically "present" but wildly inaccurate. `PoseEstimate` exposes exactly the fields you need to gate on:

| Field                                                                    | What it tells you                                                                                                                        |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `hasData`                                                                | Whether any tag contributed to this estimate at all.                                                                                     |
| `tagCount`                                                               | More tags generally means a more constrained, trustworthy solve.                                                                         |
| `avgTagDist`                                                             | Farther tags have more angular pose error per pixel of detection noise.                                                                  |
| `avgTagArea`                                                             | A proxy for distance/detection quality: larger is closer/clearer.                                                                        |
| `tagSpan`                                                                | Wider-spread tags better constrain rotation than tags clustered together.                                                                |
| `getMinTagAmbiguity()` / `getMaxTagAmbiguity()` / `getAvgTagAmbiguity()` | Per-tag pose ambiguity (0-1) from SolvePnP. Near-symmetric tag views produce multiple plausible poses, which shows up as high ambiguity. |

The pattern used throughout YALL's examples:

```java
if (poseEstimate.avgTagDist < 4 && poseEstimate.tagCount > 0 && poseEstimate.getMinTagAmbiguity() < 0.3) {
    poseEstimator.addVisionMeasurement(poseEstimate.pose.toPose2d(), poseEstimate.timestampSeconds);
}
```

Tune the thresholds (`4` meters, `0.3` ambiguity) to your field and camera; they aren't universal constants, just a reasonable starting point.

## Timestamps matter

`PoseEstimate.timestampSeconds` is the NT server timestamp adjusted for total pipeline latency, not "now." Always pass it (not `Timer.getFPGATimestamp()`) to `addVisionMeasurement`, so your pose estimator correctly accounts for how stale the vision reading actually is relative to your odometry.

## MegaTag1 vs. MegaTag2 fields

Every field above works identically regardless of which `EstimationMode` produced the estimate; `isMegaTag2` just records which one it was. The meaningful difference between the two modes is accuracy and setup requirements, covered in [How do I choose between MegaTag1 and MegaTag2?](/documentation/how-to-guides/how-do-i-choose-megatag1-vs-megatag2)

## See Also

* [AprilTag Pose Estimation tutorial](/documentation/tutorials/apriltag-pose-estimation)
* [AprilTag & MegaTag2 Localization Tuning](/documentation/tuning/apriltag-and-megatag2-tuning): why more, more-spread-out tags produce a more trustworthy estimate.
* [ChArUco Camera Calibration](/documentation/tuning/charuco-camera-calibration): accurate intrinsics are what these fields are measuring the quality of in the first place.
* PoseEstimate reference
* RawFiducial reference


# Results JSON vs. Raw NetworkTables

YALL gives you two different paths to the same underlying camera data, and picking the right one for your use case matters for loop timing.

## The JSON path: `getLatestResults()`

`limelight.getLatestResults()` (equivalently `limelight.getData().getResults()`) reads the `json` NetworkTables entry and deserializes it with Jackson into a `LimelightResults` object: one object holding **everything** the Limelight published for that frame, including every target type array, hardware/IMU telemetry, every bot-pose variant, latency figures, and more.

This only works if the Limelight GUI's **Output & Crosshair → Send JSON over NT?** option is enabled. If it's off, `getLatestResults()` always returns `Optional.empty()`.

Reach for this when you need:

* Multiple target/pipeline types at once
* Hardware telemetry (`HardwareReport`, `IMUResults`, `RewindStats`, `HailoStats`)
* Barcode or retroreflective results (no raw-NT equivalent exists for these)

Cost: a full JSON parse on every call. Fine for most periodic loops, but avoid calling it more than once per loop iteration. Cache the `Optional<LimelightResults>` locally if multiple parts of your code need it in the same cycle.

## The raw path: `LimelightData` direct reads

`LimelightData` (from `limelight.getData()`) also exposes several values as direct NetworkTables reads, bypassing JSON entirely:

| Method                                        | Backing NT entry        |
| --------------------------------------------- | ----------------------- |
| `getRawFiducials()`                           | `rawfiducials`          |
| `getRawDetections()`                          | `rawdetections`         |
| `getBarcodeData()`                            | `rawbarcodes`           |
| `getCamera2Robot()`                           | `camerapose_robotspace` |
| `getClassifierClass()` / `getDetectorClass()` | `tcclass` / `tdclass`   |

`LimelightTargetData` (`limelight.getData().targetData`) goes further: `tx`, `ty`, target area, target count, and every relative pose (`robot2Target`, `camera2Target`, etc.) are all direct scalar/array NT reads, with no JSON involved at all.

Reach for these when:

* You only need tag/detection geometry, not the full frame
* You're polling every loop and want to avoid repeated JSON parsing
* You need bounding-box corners (`RawDetection`), which the JSON `NeuralDetector` result doesn't include

## Rule of thumb

Raw NetworkTables reads for tight, latency-sensitive loops (aiming, MegaTag pose fusion). JSON results when you need the full picture or a target type only the JSON exposes.

## See Also

* [How do I read raw fiducials and detections?](/documentation/how-to-guides/how-do-i-read-raw-fiducials-and-detections)
* LimelightData reference
* LimelightResults reference


# Target & Pipeline Types

A Limelight pipeline produces exactly one kind of target result, and `LimelightResults` exposes each kind as its own typed array. Only the array matching the active pipeline's type is populated for a given frame; the rest are empty.

| Pipeline type       | `LimelightResults` field | Type                    | Produced by                                                                |
| ------------------- | ------------------------ | ----------------------- | -------------------------------------------------------------------------- |
| AprilTag / fiducial | `targets_Fiducials`      | `AprilTagFiducial[]`    | AprilTag detection + SolvePnP.                                             |
| Retroreflective     | `targets_Retro`          | `RetroreflectiveTape[]` | Color/contour-based retroreflective tape pipelines.                        |
| Neural classifier   | `targets_Classifier`     | `NeuralClassifier[]`    | Whole-frame/zone classification model; labels the scene, no bounding box.  |
| Neural detector     | `targets_Detector`       | `NeuralDetector[]`      | Object detection model; per-object bounding boxes with class + confidence. |
| Barcode             | `targets_Barcode`        | `Barcode[]`             | QR/DataMatrix/etc. decoding.                                               |

Check `LimelightResults.pipeline_type` if your code needs to confirm which pipeline produced a given frame before reading its target array.

## Classifier vs. Detector

These are easy to confuse since both are "neural" pipelines:

* **Classifier** (`NeuralClassifier`): answers "what is this?" for the whole frame or a zone. Has `className`, `confidence`, and a rough `tx`/`ty` position, but no bounding box or area.
* **Detector** (`NeuralDetector`): answers "what objects are where?" with individual bounding boxes. Has `className`, `confidence`, `ta` (area), and crosshair-relative `tx`/`ty`, laid out the same way as `AprilTagFiducial`/`RetroreflectiveTape`. The raw-NT equivalent, `RawDetection`, also exposes the four bounding-box corner points.

## AprilTag vs. Retroreflective: shared pose API

`AprilTagFiducial` and `RetroreflectiveTape` expose the identical set of `getXXXPose_YYYSpace()` / `...2D()` methods (camera-in-target-space, robot-in-field-space, robot-in-target-space, target-in-camera-space, target-in-robot-space). The only real difference is that `AprilTagFiducial` additionally carries `fiducialID` and `fiducialFamily`. If you're writing code that only cares about "where is this target," it can be written generically against either type's pose methods.

## Barcode

`Barcode` is the odd one out: it has no pose accessors, since a printed barcode has no known real-world dimension for SolvePnP to use. It gives you `family`, `data` (the decoded string), pixel/degree position, and optional pixel-space `corners` (must be enabled in the Limelight output tab).

## See Also

* [Object Detection tutorial](/documentation/tutorials/object-detection)
* [Tuning a Retroreflective Pipeline](/documentation/tuning/retroreflective-pipeline-tuning)
* [Tuning a Neural Network Pipeline](/documentation/tuning/neural-network-pipeline-tuning)
* LimelightResults reference


# Hardware Telemetry & IMU

Newer Limelight firmware (2026+) publishes system health and, on the Limelight 4, onboard IMU data as part of the JSON results frame. All of it lives under `LimelightResults` and is only available through [`getLatestResults()`](/documentation/understanding/results-json-vs-raw-networktables), since there's no raw-NT equivalent.

## HardwareReport

`LimelightResults.hardware` reports CPU usage, disk space, RAM usage, and CPU temperature:

```java
limelight.getLatestResults().ifPresent(result -> {
    if (result.hardware != null && result.hardware.getTemp().gt(Celsius.of(70))) {
        // consider throttling, see How do I reduce thermal output while disabled?
    }
});
```

If a Hailo neural accelerator module is installed (Limelight 4 only, sold separately), its stats are nested at `result.hardware.hailoStats` as a `HailoStats`: presence, temperature, power draw, and throttle state.

## IMUResults (Limelight 4)

`LimelightResults.imuResults` exposes the onboard IMU's fused yaw and full 9-axis data (orientation + angular velocity + acceleration):

```java
limelight.getLatestResults().ifPresent(result -> {
    if (result.imuResults != null) {
        Pair<Orientation3d, AngularAcceleration3d> imu = result.imuResults.getIMUData();
        Angle fusedYaw = result.imuResults.getFusedYaw();
    }
});
```

This is a separate concept from `LimelightSettings.withRobotOrientation`. That method **submits** your robot's gyro data *to* the Limelight for MegaTag2 fusion, while `IMUResults` **reads back** the Limelight 4's own internal IMU, which is useful for diagnostics or as a fallback orientation source, not as a replacement for your robot's primary gyro. See `LimelightSettings.ImuMode` for how the two interact when both an internal and external IMU are available.

## RewindStats (Limelight 4)

`LimelightResults.rewindStats` reports rolling-buffer status: usage fraction, frame count, and whether a flush to disk is in progress. See [How do I take snapshots and rewind captures?](/documentation/how-to-guides/how-do-i-take-snapshots-and-rewind-captures) for triggering captures.

## See Also

* [How do I reduce thermal output while disabled?](/documentation/how-to-guides/how-do-i-reduce-thermal-output-while-disabled)
* HardwareReport reference
* IMUResults reference


# Python & C++ Support

## Python: a full, parallel port

{% hint style="info" %}
The Python port was written by FRC Team 9738, who did the original translation of the Java API and contributed it back to YALL. Thanks to them, teams running Python robot code get the same library everyone else does.
{% endhint %}

YALL ships a Python package (`yall`) alongside the Java library, mirroring its class names and most method signatures:

```python
from yall.limelight import Limelight, EstimationMode
limelight = Limelight("limelight")
```

The Python port was translated from an earlier revision of the Java API and hasn't caught up to every recent addition. Notably, there's no Python equivalent yet for `IMUResults`, `HardwareReport`, `HailoStats`, `RewindStats`, rewind capture, or USB port forwarding. A couple of method names also differ slightly (`withCameraToRobot` instead of `withCameraOffset`, `createPoseEstimator(bool)` instead of taking an `EstimationMode` enum). See the Python reference overview for the full list of differences.

For everything else, including settings, pose estimation, and target results, the concepts on this site apply directly; only the syntax changes.

## C++: not yet implemented

A C++ source file exists in the repository (`yall/cpp/Limelight.cpp`) as a placeholder, and the vendordep JSON currently ships no C++ artifact. If your team writes robot code in C++, track the [GitHub repository](https://github.com/BroncBotz3481/YALL) for progress rather than expecting a working C++ API today.

## See Also

* Python API reference
* Java API reference


# Overview

Yet Another Limelight Library (YALL) is a WPILib vendordep for Limelight smart cameras used in FRC. It wraps the raw Limelight NetworkTables API and `limelight.results` JSON output in a typed, chainable Java API — pose estimation (MegaTag1/MegaTag2), AprilTag/neural/retroreflective/barcode target results, raw fiducial/detection data, IMU and hardware telemetry, and Limelight configuration (LEDs, pipelines, crop windows, camera offsets, etc).

A Python port with an equivalent API surface ships alongside the Java library. A C++ port is planned but not yet implemented.

## Features

* **`Limelight`** — one object per camera, resolves its NetworkTables table by name
* **`LimelightSettings`** — chainable `.withXXXX()` configuration for LEDs, pipelines, IMU, crop, offsets, and more
* **`LimelightPoseEstimator`** — MegaTag1/MegaTag2 pose estimates with alliance-aware helpers
* **`LimelightResults`** — full JSON `limelight.results` output, including all target/pipeline types
* **`LimelightData`** — direct NetworkTables reads for raw fiducials, raw detections, barcodes, and Python script I/O
* **Typed target results** — `AprilTagFiducial`, `RetroreflectiveTape`, `NeuralClassifier`, `NeuralDetector`, `Barcode`
* **Hardware telemetry** — `IMUResults`, `HardwareReport`, `HailoStats`, `RewindStats` (2026+ hardware)

## Quick Navigation

* [Java API](/api-reference/java-reference/java-reference)
* [Python API](/api-reference/python-reference/python-reference)

For tutorials, how-to guides, and conceptual explanations, see the main YALL documentation space (YALL-Gitbook).

## Supported Hardware

| Device                                   | Notes                                            |
| ---------------------------------------- | ------------------------------------------------ |
| Limelight 2/2+/3/3G/3A                   | AprilTag, retroreflective, neural pipelines      |
| Limelight 4                              | Adds onboard IMU, rewind capture, USB networking |
| Hailo accelerator (LL4, sold separately) | Reported via `HardwareReport.hailoStats`         |


# Overview

**Root package:** `limelight`

```java
import limelight.Limelight;
```

## Package Layout

| Package                                   | Contents                                                                   |
| ----------------------------------------- | -------------------------------------------------------------------------- |
| `limelight`                               | [`Limelight`](/api-reference/java-reference/limelight) — the camera object |
| `limelight.networktables`                 | Settings, data access, pose estimation, JSON results, and geometry helpers |
| `limelight.networktables.target`          | Typed 2D/3D target results: AprilTag, retroreflective, barcode             |
| `limelight.networktables.target.pipeline` | Typed neural pipeline results: classifier, detector                        |
| `limelight.results`                       | Raw NetworkTables detection structs and hardware/IMU/rewind telemetry      |

## Where to Start

Every use of YALL begins with one `Limelight` object per camera:

```java
Limelight limelight = new Limelight("limelight");
```

From there:

* [`getSettings()`](/api-reference/java-reference/networktables/limelight-settings) configures the camera (LEDs, pipeline, crop, camera offset, IMU mode, robot orientation, ...)
* [`createPoseEstimator(EstimationMode)`](/api-reference/java-reference/networktables/limelight-pose-estimator) returns a [`LimelightPoseEstimator`](/api-reference/java-reference/networktables/limelight-pose-estimator) for MegaTag1/MegaTag2 field-relative pose
* [`getData()`](/api-reference/java-reference/networktables/limelight-data) exposes raw fiducials, raw detections, barcodes, and Python script I/O
* [`getLatestResults()`](/api-reference/java-reference/networktables/limelight-results) returns the full JSON `LimelightResults` for a frame, including every target type

## Reference

* [Limelight](/api-reference/java-reference/limelight)
* NetworkTables
  * [LimelightSettings](/api-reference/java-reference/networktables/limelight-settings)
  * [LimelightPoseEstimator](/api-reference/java-reference/networktables/limelight-pose-estimator)
  * [PoseEstimate](/api-reference/java-reference/networktables/pose-estimate)
  * [LimelightData](/api-reference/java-reference/networktables/limelight-data)
  * [LimelightPipelineData](/api-reference/java-reference/networktables/limelight-pipeline-data)
  * [LimelightTargetData](/api-reference/java-reference/networktables/limelight-target-data)
  * [LimelightResults](/api-reference/java-reference/networktables/limelight-results)
  * [LimelightUtils](/api-reference/java-reference/networktables/limelight-utils)
  * [Orientation3d](/api-reference/java-reference/networktables/orientation3d)
  * [AngularVelocity3d](/api-reference/java-reference/networktables/angular-velocity3d)
  * [AngularAcceleration3d](/api-reference/java-reference/networktables/angular-acceleration3d)
* Target Types
  * [AprilTagFiducial](/api-reference/java-reference/target-types/apriltag-fiducial)
  * [RetroreflectiveTape](/api-reference/java-reference/target-types/retroreflective-tape)
  * [Barcode](/api-reference/java-reference/target-types/barcode)
  * [NeuralClassifier](/api-reference/java-reference/target-types/neural-classifier)
  * [NeuralDetector](/api-reference/java-reference/target-types/neural-detector)
* Results & Telemetry
  * [RawFiducial](/api-reference/java-reference/results-and-telemetry/raw-fiducial)
  * [RawDetection](/api-reference/java-reference/results-and-telemetry/raw-detection)
  * [IMUResults](/api-reference/java-reference/results-and-telemetry/imu-results)
  * [HardwareReport](/api-reference/java-reference/results-and-telemetry/hardware-report)
  * [HailoStats](/api-reference/java-reference/results-and-telemetry/hailo-stats)
  * [RewindStats](/api-reference/java-reference/results-and-telemetry/rewind-stats)


# Limelight

**Package:** `limelight`

`Limelight` is the entry point for the library — one instance per physical camera, bound to that camera's NetworkTables table (`/<name>`). Construction verifies the table exists (except in simulation) and creates the associated `LimelightData` and `LimelightSettings` objects.

***

## Constructor

```java
Limelight(String name)
```

| Parameter | Description                                                                 |
| --------- | --------------------------------------------------------------------------- |
| `name`    | NetworkTables name of the camera, e.g. `"limelight"` or `"limelight-front"` |

***

## Fields

| Field           | Type     | Description                     |
| --------------- | -------- | ------------------------------- |
| `limelightName` | `String` | Name passed to the constructor. |

***

## Methods

| Method                                        | Returns                      | Description                                                                                                                                                                                   |
| --------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getSettings()`                               | `LimelightSettings`          | Chainable object for `.withXXXX()` configuration calls. See [LimelightSettings](/api-reference/java-reference/networktables/limelight-settings).                                              |
| `getData()`                                   | `LimelightData`              | Read-only NetworkTables data: raw fiducials, raw detections, barcodes, Python I/O. See [LimelightData](/api-reference/java-reference/networktables/limelight-data).                           |
| `createPoseEstimator(EstimationMode)`         | `LimelightPoseEstimator`     | Creates a MegaTag1 or MegaTag2 pose estimator bound to this camera. See [LimelightPoseEstimator](/api-reference/java-reference/networktables/limelight-pose-estimator).                       |
| `getLatestResults()`                          | `Optional<LimelightResults>` | Parses the latest `limelight.results` JSON blob. Empty if the Limelight isn't publishing JSON over NT. See [LimelightResults](/api-reference/java-reference/networktables/limelight-results). |
| `getNTTable()`                                | `NetworkTable`               | The underlying `NetworkTable` for this camera.                                                                                                                                                |
| `flush()`                                     | `void`                       | Flushes the default `NetworkTableInstance` immediately.                                                                                                                                       |
| `rewindCapture(double durationSeconds)`       | `void`                       | Triggers a rewind buffer capture (max 165s, rate-limited on the Limelight). Requires supported hardware.                                                                                      |
| `snapshot(String snapshotname)`               | `void`                       | Asynchronously requests an HTTP snapshot capture (`capturesnapshot`) named `snapshotname`.                                                                                                    |
| `static isAvailable(String limelightName)`    | `boolean`                    | Polls NetworkTables (up to 2s) for a `getpipe` key under the given table name. Raises a WPILib `Alert` and returns `false` if not found.                                                      |
| `static setupPortForwardingUSB(int usbIndex)` | `void`                       | Forwards ports `5800-5809 + usbIndex*10` to `172.29.<usbIndex>.1:5800-5809` for USB-connected LL3A/3G web UI access.                                                                          |

***

## Notes

* `isAvailable` is meant to run once, at robot construction — not in a periodic loop. Use `getData().targetData.getTargetStatus()` for per-iteration 2D target validity, or `PoseEstimate.hasData` for 3D pose validity.
* `snapshot()` runs the HTTP request on a separate thread via `CompletableFuture` so it never blocks the robot loop.

## See Also

* [LimelightSettings](/api-reference/java-reference/networktables/limelight-settings)
* [LimelightPoseEstimator](/api-reference/java-reference/networktables/limelight-pose-estimator)
* [LimelightData](/api-reference/java-reference/networktables/limelight-data)


# NetworkTables


# LimelightSettings

**Package:** `limelight.networktables`

Chainable configuration object for a [`Limelight`](/api-reference/java-reference/limelight). Fetched once via `limelight.getSettings()` and reused — every `.withXXXX()` call writes to NetworkTables and returns `this` for chaining. Most writes take effect on the Limelight immediately; `save()` forces an NT flush but is rarely required.

```java
limelight.getSettings()
         .withLimelightLEDMode(LEDMode.PipelineControl)
         .withCameraOffset(Pose3d.kZero)
         .save();
```

{% hint style="info" %}
Settings are write-only. The constructor fetches current values from the Limelight, but there are no getters — `LimelightSettings` exists purely as an attachment point for `.withXXXX()` calls.
{% endhint %}

***

## Methods

| Method                                                                     | Description                                                                                                                                     |
| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `withLimelightLEDMode(LEDMode mode)`                                       | Sets the LED mode.                                                                                                                              |
| `withPipelineIndex(int index)`                                             | Switches the active pipeline (0-9).                                                                                                             |
| `withPriorityTagId(int aprilTagId)`                                        | Sets the AprilTag ID MegaTag should prioritize when multiple tags are visible.                                                                  |
| `withStreamMode(StreamMode mode)`                                          | Sets the camera stream layout (standard / picture-in-picture).                                                                                  |
| `withCropWindow(double minX, double maxX, double minY, double maxY)`       | Sets the processing crop window, `-1` to `1` per axis. The crop window in the web UI must be fully open for this to take effect.                |
| `withImuMode(ImuMode mode)`                                                | Sets how the Limelight 4's internal IMU is fused with externally-submitted robot orientation for MegaTag2.                                      |
| `withImuAssistAlpha(double alpha)`                                         | Convergence strength (default `0.001`) for internal-IMU-assist modes.                                                                           |
| `withRobotOrientation(Orientation3d orientation)`                          | Submits robot heading + angular velocity for MegaTag2. **Required every loop when using `EstimationMode.MEGATAG2`.** Calls `save()` internally. |
| `withFiducialDownscalingOverride(DownscalingOverride downscalingOverride)` | Overrides AprilTag detection downscaling. Higher downscale trades detection range for performance.                                              |
| `withAprilTagOffset(Translation3d offset)`                                 | Sets the 3D point-of-interest offset for the active fiducial pipeline.                                                                          |
| `withAprilTagIdFilter(List<Integer> idFilter)`                             | Restricts MegaTag/fiducial tracking to the given AprilTag IDs.                                                                                  |
| `withCameraOffset(Pose3d offset)`                                          | Sets the camera's pose relative to robot center (meters + `Rotation3d`). Required for accurate MegaTag pose estimation.                         |
| `withKeystone(double horizontal, double vertical)`                         | Keystone perspective correction for the crop window, `-0.95` to `0.95` per axis.                                                                |
| `withThrottle(double throttle)`                                            | Skips `throttle` frames between processed frames. Recommended `100-200` while disabled to reduce thermal output.                                |
| `withRewindEnable(RewindState state)`                                      | Enables or pauses rewind buffer recording (supported hardware only).                                                                            |
| `rewindCapture(double durationSeconds)`                                    | Triggers a rewind capture (max 165s, rate-limited to once per 2s).                                                                              |
| `save()`                                                                   | Flushes the default `NetworkTableInstance` immediately.                                                                                         |

***

## Enums

### LEDMode

`PipelineControl` · `ForceOff` · `ForceBlink` · `ForceOn` · `ForceLeftOn` · `ForceRightOn` · `BounceHalves` · `ForceLeftBlink` · `ForceRightBlink`

### StreamMode

`Standard` (side-by-side) · `PictureInPictureMain` (secondary in corner) · `PictureInPictureSecondary` (main in corner)

### DownscalingOverride

`Pipeline` (0, pipeline-controlled) · `NoDownscale` (1) · `HalfDownscale` (1.5) · `DoubleDownscale` (2) · `TripleDownscale` (3) · `QuadrupleDownscale` (4)

### ImuMode

| Value                       | Behavior                                                                               |
| --------------------------- | -------------------------------------------------------------------------------------- |
| `ExternalImu`               | Uses only the yaw submitted via `withRobotOrientation`. Internal IMU ignored entirely. |
| `SyncInternalImu`           | Uses external yaw; internal IMU is kept synced to it.                                  |
| `InternalImu`               | Uses the internal IMU exclusively; ignores external orientation updates.               |
| `InternalImuMT1Assist`      | Uses the internal IMU, corrected continuously by filtered MegaTag1 yaw estimates.      |
| `InternalImuExternalAssist` | Uses the internal IMU, corrected continuously by the externally-submitted IMU.         |

### RewindState

`DISABLED` · `ENABLED`

## See Also

* [Limelight](/api-reference/java-reference/limelight)
* [LimelightPoseEstimator](/api-reference/java-reference/networktables/limelight-pose-estimator)
* [Orientation3d](/api-reference/java-reference/networktables/orientation3d)


# LimelightPoseEstimator

**Package:** `limelight.networktables`

Fetches field-relative robot pose estimates from a [`Limelight`](/api-reference/java-reference/limelight), using either the MegaTag1 or MegaTag2 pipeline. Created via `limelight.createPoseEstimator(EstimationMode)`.

```java
LimelightPoseEstimator poseEstimator = limelight.createPoseEstimator(EstimationMode.MEGATAG2);
Optional<PoseEstimate> estimate = poseEstimator.getPoseEstimate();
```

***

## Constructor

```java
LimelightPoseEstimator(Limelight camera, EstimationMode estimationMode)
```

Prefer `limelight.createPoseEstimator(mode)` over calling this directly.

***

## Methods

| Method                        | Returns                  | Description                                                                                                           |
| ----------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `getPoseEstimate()`           | `Optional<PoseEstimate>` | Blue-origin pose estimate, using MegaTag1 or MegaTag2 depending on the estimator's `EstimationMode`.                  |
| `getAlliancePoseEstimate()`   | `Optional<PoseEstimate>` | Pose estimate in the coordinate frame matching `DriverStation.getAlliance()`. Empty if alliance color is unavailable. |
| `getBotPose()` *(deprecated)* | `Pose3d`                 | Legacy MegaTag1 `botpose` entry, not alliance- or origin-aware. Prefer `getPoseEstimate()`.                           |

***

## EstimationMode

| Value      | Description                                                                                                                                                                                                                                                                                             |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MEGATAG1` | Estimates pose from a single AprilTag using only visual data. No external state required.                                                                                                                                                                                                               |
| `MEGATAG2` | Fuses AprilTag detections with robot heading for smoother, more accurate localization — especially at long range or oblique angles. Requires calling [`LimelightSettings.withRobotOrientation`](/api-reference/java-reference/networktables/limelight-settings) every loop before reading the estimate. |

***

## BotPose

Internal enum mapping each `EstimationMode`/alliance combination to its NetworkTables entry name. Exposed publicly for direct access without going through a `LimelightPoseEstimator`:

```java
Optional<PoseEstimate> estimate = BotPose.BLUE_MEGATAG2.get(limelight);
```

| Value                           | NT Entry              | MegaTag2 |
| ------------------------------- | --------------------- | -------- |
| `RED`                           | `botpose_wpired`      | No       |
| `RED_MEGATAG2`                  | `botpose_orb_wpired`  | Yes      |
| `BLUE` *(recommended)*          | `botpose_wpiblue`     | No       |
| `BLUE_MEGATAG2` *(recommended)* | `botpose_orb_wpiblue` | Yes      |

Each `BotPose` value caches one `PoseEstimate` per `Limelight` it's queried with, keyed by camera name + entry, so repeated calls don't allocate.

## See Also

* [PoseEstimate](/api-reference/java-reference/networktables/pose-estimate)
* [LimelightSettings#withRobotOrientation](/api-reference/java-reference/networktables/limelight-settings)
* [Limelight](/api-reference/java-reference/limelight)


# PoseEstimate

**Package:** `limelight.networktables`

A single 3D pose estimate read from one Limelight `botpose*` NetworkTables entry, along with the AprilTag observations that produced it. Instances come from [`LimelightPoseEstimator`](/api-reference/java-reference/networktables/limelight-pose-estimator) or `BotPose.get(limelight)` — you generally don't construct these directly.

***

## Fields

| Field              | Type              | Description                                                     |
| ------------------ | ----------------- | --------------------------------------------------------------- |
| `pose`             | `Pose3d`          | Estimated robot pose.                                           |
| `timestampSeconds` | `double`          | NT server timestamp, adjusted for total latency, in seconds.    |
| `latency`          | `double`          | Total pipeline latency in milliseconds.                         |
| `tagCount`         | `int`             | Number of AprilTags used in this estimate.                      |
| `tagSpan`          | `double`          | Maximum distance between visible tags, in meters.               |
| `avgTagDist`       | `double`          | Average camera-to-tag distance, in meters.                      |
| `avgTagArea`       | `double`          | Average tag area as a percentage of the image.                  |
| `rawFiducials`     | `RawFiducial[]`   | Per-tag detail for every tag used in the estimate.              |
| `hasData`          | `boolean`         | `true` if the estimate contains at least one observed fiducial. |
| `isMegaTag2`       | `boolean` (final) | Whether this estimate came from the MegaTag2 pipeline.          |

***

## Methods

| Method                 | Returns                  | Description                                                                                      |
| ---------------------- | ------------------------ | ------------------------------------------------------------------------------------------------ |
| `getPoseEstimate()`    | `Optional<PoseEstimate>` | Re-reads the bound NT entry and repopulates this object's fields. Empty if no data is published. |
| `refresh()`            | `PoseEstimate`           | Calls `getPoseEstimate()` and returns `this` for chaining.                                       |
| `getMinTagAmbiguity()` | `double`                 | Minimum `ambiguity` across `rawFiducials`. Returns `1` if `hasData` is `false`.                  |
| `getMaxTagAmbiguity()` | `double`                 | Maximum `ambiguity` across `rawFiducials`. Returns `1` if `hasData` is `false`.                  |
| `getAvgTagAmbiguity()` | `double`                 | Average `ambiguity` across `rawFiducials`. Returns `1` if `hasData` is `false`.                  |

***

## Filtering Before Fusing

`avgTagDist`, `tagCount`, and the ambiguity helpers are the standard gate before calling `addVisionMeasurement` on a WPILib pose estimator — reject stale or unreliable reads instead of trusting every frame:

```java
visionEstimate.ifPresent(estimate -> {
    if (estimate.avgTagDist < 4 && estimate.tagCount > 0 && estimate.getMinTagAmbiguity() < 0.3) {
        poseEstimator.addVisionMeasurement(estimate.pose.toPose2d(), estimate.timestampSeconds);
    }
});
```

## See Also

* [LimelightPoseEstimator](/api-reference/java-reference/networktables/limelight-pose-estimator)
* [RawFiducial](/api-reference/java-reference/results-and-telemetry/raw-fiducial)


# LimelightData

**Package:** `limelight.networktables`

Read-only NetworkTables data access for a [`Limelight`](/api-reference/java-reference/limelight). Fetched via `limelight.getData()`. Holds two sub-objects — `targetData` ([`LimelightTargetData`](/api-reference/java-reference/networktables/limelight-target-data)) and `pipelineData` ([`LimelightPipelineData`](/api-reference/java-reference/networktables/limelight-pipeline-data)) — plus JSON results parsing and raw NT reads that aren't part of the JSON blob.

***

## Fields

| Field          | Type                    | Description                                                                                                                    |
| -------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `targetData`   | `LimelightTargetData`   | 2D/3D target metrics. See [LimelightTargetData](/api-reference/java-reference/networktables/limelight-target-data).            |
| `pipelineData` | `LimelightPipelineData` | Pipeline latency/index/type. See [LimelightPipelineData](/api-reference/java-reference/networktables/limelight-pipeline-data). |

***

## Methods

| Method                                 | Returns                      | Description                                                                                                                                                                                                        |
| -------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `getResults()`                         | `Optional<LimelightResults>` | Parses the `json` NT entry into a [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results). Empty if the LL GUI's "Send JSON over NT?" option is off or nothing has been published yet. |
| `getRawFiducials()`                    | `RawFiducial[]`              | Decodes the `rawfiducials` double array (7 values per tag) into typed structs.                                                                                                                                     |
| `getRawDetections()`                   | `RawDetection[]`             | Decodes the `rawdetections` double array (12 values per detection) into typed structs.                                                                                                                             |
| `getCamera2Robot()`                    | `Pose3d`                     | Camera pose relative to the robot, from `camerapose_robotspace`.                                                                                                                                                   |
| `getClassifierClass()`                 | `String`                     | Current neural classifier result class name (`tcclass`).                                                                                                                                                           |
| `getDetectorClass()`                   | `String`                     | Primary neural detector result class name (`tdclass`).                                                                                                                                                             |
| `getBarcodeData()`                     | `String[]`                   | Decoded barcode strings (`rawbarcodes`).                                                                                                                                                                           |
| `getPythonData()`                      | `double[]`                   | Output array from a custom Python SnapScript pipeline (`llpython`).                                                                                                                                                |
| `setPythonData(double[] outgoingData)` | `void`                       | Writes input data for a custom Python SnapScript pipeline (`llrobot`).                                                                                                                                             |
| `takeSnapshot()`                       | `void`                       | Increments the `snapshot` counter to trigger a rising-edge snapshot. Rate-limited to once per 10 frames.                                                                                                           |

***

## Raw NetworkTables vs. JSON Results

`getRawFiducials()` / `getRawDetections()` read individual NT entries directly and are cheaper per-call than `getResults()`, which parses a full JSON payload with Jackson every call. Use the raw accessors in a tight periodic loop when you only need tag/detection geometry; use `getResults()` when you need the full frame — target arrays for every pipeline type, hardware/IMU telemetry, or multiple bot-pose variants at once.

## See Also

* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)
* [RawFiducial](/api-reference/java-reference/results-and-telemetry/raw-fiducial)
* [RawDetection](/api-reference/java-reference/results-and-telemetry/raw-detection)
* [LimelightTargetData](/api-reference/java-reference/networktables/limelight-target-data)


# LimelightPipelineData

**Package:** `limelight.networktables`

Pipeline status readouts for a [`Limelight`](/api-reference/java-reference/limelight), accessed via `limelight.getData().pipelineData`.

***

## Methods

| Method                      | Returns  | Description                                                                                     |
| --------------------------- | -------- | ----------------------------------------------------------------------------------------------- |
| `getProcessingLatency()`    | `double` | Pipeline processing latency contribution, in milliseconds (`tl`).                               |
| `getCaptureLatency()`       | `double` | Capture latency between end-of-exposure and start of the tracking loop, in milliseconds (`cl`). |
| `getCurrentPipelineIndex()` | `double` | Currently active pipeline index, 0-9 (`getpipe`).                                               |
| `getCurrentPipelineType()`  | `String` | Active pipeline type string, e.g. `"retro"`, `"apriltag"` (`getpipetype`).                      |

## See Also

* [LimelightData](/api-reference/java-reference/networktables/limelight-data)
* [LimelightSettings#withPipelineIndex](/api-reference/java-reference/networktables/limelight-settings)


# LimelightTargetData

**Package:** `limelight.networktables`

2D and 3D per-target metrics for the currently tracked target, accessed via `limelight.getData().targetData`. Reflects whatever pipeline is active — retroreflective, AprilTag, classifier, or detector.

***

## Methods

| Method                               | Returns                | Description                                                                                                                                                                                                                                                                                |
| ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `getTargetStatus()`                  | `boolean`              | `true` if a valid target is present (`tv`). Check this before trusting `tx`/`ty`/etc.                                                                                                                                                                                                      |
| `getHorizontalOffset()`              | `double`               | Crosshair-relative horizontal offset in degrees (`tx`).                                                                                                                                                                                                                                    |
| `getVerticalOffset()`                | `double`               | Crosshair-relative vertical offset in degrees (`ty`).                                                                                                                                                                                                                                      |
| `getHorizontalOffsetFromPrincipal()` | `double`               | Principal-pixel-relative horizontal offset in degrees (`txnc`). More accurate than `tx` on a calibrated camera when adjustable crosshair isn't needed.                                                                                                                                     |
| `getVerticalOffsetFromPrincipal()`   | `double`               | Principal-pixel-relative vertical offset in degrees (`tync`).                                                                                                                                                                                                                              |
| `getTargetArea()`                    | `double`               | Target area as a percentage of the image, 0-100 (`ta`).                                                                                                                                                                                                                                    |
| `getTargetCount()`                   | `int`                  | Number of currently detected targets, decoded from the `t2d` metrics array.                                                                                                                                                                                                                |
| `getAprilTagID()`                    | `double`               | Current fiducial ID (`tid`).                                                                                                                                                                                                                                                               |
| `getNeuralClassID()`                 | `String`               | Current neural class name (`tclass`).                                                                                                                                                                                                                                                      |
| `getClassifierClassIndex()`          | `int`                  | Classifier class index, decoded from `t2d`.                                                                                                                                                                                                                                                |
| `getDetectorClassIndex()`            | `int`                  | Primary detector class index, decoded from `t2d`.                                                                                                                                                                                                                                          |
| `getTargetColor()`                   | `double[]`             | Target color in HSV/RGB format (`tc`).                                                                                                                                                                                                                                                     |
| `getTargetMetrics()`                 | `double[]`             | Raw `t2d` array: `[targetValid, targetCount, targetLatency, captureLatency, tx, ty, txnc, tync, ta, tid, targetClassIndexDetector, targetClassIndexClassifier, targetLongSidePixels, targetShortSidePixels, targetHorizontalExtentPixels, targetVerticalExtentPixels, targetSkewDegrees]`. |
| `getStandardDeviations()`            | `Pair<Pose3d, Pose3d>` | MegaTag1/MegaTag2 standard deviations as `Pair.of(MT1, MT2)`, decoded from `stddevs`.                                                                                                                                                                                                      |
| `getRobotToTarget()`                 | `Pose3d`               | Robot pose relative to the target (`botpose_targetspace`).                                                                                                                                                                                                                                 |
| `getCameraToTarget()`                | `Pose3d`               | Camera pose relative to the target (`camerapose_targetspace`).                                                                                                                                                                                                                             |
| `getTargetToCamera()`                | `Pose3d`               | Target pose relative to the camera (`targetpose_cameraspace`).                                                                                                                                                                                                                             |
| `getTargetToRobot()`                 | `Pose3d`               | Target pose relative to the robot (`targetpose_robotspace`).                                                                                                                                                                                                                               |

## See Also

* [LimelightData](/api-reference/java-reference/networktables/limelight-data)
* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)


# LimelightResults

**Package:** `limelight.networktables`

Java model of the full `limelight.results` JSON payload — every field the Limelight can publish for a single frame, across every pipeline type. Retrieved via `limelight.getLatestResults()` or `limelight.getData().getResults()`, both of which return `Optional<LimelightResults>` (empty if the LL GUI's "Send JSON over NT?" option is off).

{% hint style="warning" %}
Parsing this object deserializes a full JSON payload with Jackson every call. For a tight periodic loop where you only need tag/detection geometry, prefer [`LimelightData.getRawFiducials()`](/api-reference/java-reference/networktables/limelight-data) / `getRawDetections()`, or the direct NT reads on [`LimelightTargetData`](/api-reference/java-reference/networktables/limelight-target-data).
{% endhint %}

***

## Key Fields

| Field                                                                                          | Type                    | Description                                                                                                                   |
| ---------------------------------------------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `valid`                                                                                        | `boolean`               | `true` if any valid target is present (`v`).                                                                                  |
| `error`                                                                                        | `String`                | Error message, if any.                                                                                                        |
| `tx`, `ty`                                                                                     | `double`                | Crosshair-relative horizontal/vertical offset in degrees.                                                                     |
| `txnc`, `tync`                                                                                 | `double`                | Principal-pixel-relative horizontal/vertical offset in degrees.                                                               |
| `ta`                                                                                           | `double`                | Undistorted, normalized target area (0-100).                                                                                  |
| `pipelineID`, `pipeline_type`                                                                  | `double`, `String`      | Active pipeline index and type string.                                                                                        |
| `latency_pipeline`, `latency_capture`                                                          | `double`                | Tracking loop latency and capture latency, in milliseconds.                                                                   |
| `timestamp_LIMELIGHT_publish`, `timestamp_RIOFPGA_capture`, `timestamp_NT`, `timestamp_System` | `double`                | Timestamps from various clocks — Limelight boot, RIO FPGA, NT server, and system wall clock.                                  |
| `botpose`, `botpose_wpired`, `botpose_wpiblue`                                                 | `double[6]`             | MegaTag1 pose in raw/red/blue coordinate frames: `[x, y, z, roll, pitch, yaw]`.                                               |
| `botpose_mt2`, `botpose_mt2_blue`                                                              | `double[6]`             | MegaTag2 pose, raw and blue-origin.                                                                                           |
| `botpose_tagcount`, `botpose_span`, `botpose_avgdist`, `botpose_avgarea`                       | `double`                | Aggregate stats over the tags used to compute `botpose`.                                                                      |
| `stdev_mt1`, `stdev_mt2`                                                                       | `double[6]`             | Standard deviations for MegaTag1/MegaTag2 pose components.                                                                    |
| `camerapose_robotspace`                                                                        | `double[6]`             | Camera pose relative to the robot.                                                                                            |
| `targets_Retro`                                                                                | `RetroreflectiveTape[]` | Retroreflective pipeline results. See [RetroreflectiveTape](/api-reference/java-reference/target-types/retroreflective-tape). |
| `targets_Fiducials`                                                                            | `AprilTagFiducial[]`    | AprilTag pipeline results. See [AprilTagFiducial](/api-reference/java-reference/target-types/apriltag-fiducial).              |
| `targets_Classifier`                                                                           | `NeuralClassifier[]`    | Neural classifier results. See [NeuralClassifier](/api-reference/java-reference/target-types/neural-classifier).              |
| `targets_Detector`                                                                             | `NeuralDetector[]`      | Neural detector results. See [NeuralDetector](/api-reference/java-reference/target-types/neural-detector).                    |
| `targets_Barcode`                                                                              | `Barcode[]`             | Barcode pipeline results. See [Barcode](/api-reference/java-reference/target-types/barcode).                                  |
| `hardware`                                                                                     | `HardwareReport`        | System hardware telemetry (2026+). See [HardwareReport](/api-reference/java-reference/results-and-telemetry/hardware-report). |
| `imuResults`                                                                                   | `IMUResults`            | IMU orientation/acceleration data. See [IMUResults](/api-reference/java-reference/results-and-telemetry/imu-results).         |
| `rewindStats`                                                                                  | `RewindStats`           | Rewind buffer stats (LL4 only). See [RewindStats](/api-reference/java-reference/results-and-telemetry/rewind-stats).          |
| `targetDistance`                                                                               | `double`                | 3D distance from camera to target/POI, in meters (`tdist`).                                                                   |
| `PythonOut`                                                                                    | `double[8]`             | Output from a custom Python SnapScript pipeline.                                                                              |

***

## Methods

| Method                                          | Returns  | Description                                                  |
| ----------------------------------------------- | -------- | ------------------------------------------------------------ |
| `getBotPose3d()`                                | `Pose3d` | MegaTag1 `botpose` as a `Pose3d`.                            |
| `getBotPose3d(DriverStation.Alliance alliance)` | `Pose3d` | MegaTag1 pose in the given alliance's coordinate frame.      |
| `getBotPose2d()`                                | `Pose2d` | MegaTag1 `botpose` as a `Pose2d`.                            |
| `getBotPose2d(DriverStation.Alliance alliance)` | `Pose2d` | MegaTag1 pose (2D) in the given alliance's coordinate frame. |
| `getMT2Pose3d()`                                | `Pose3d` | MegaTag2 `botpose_orb` as a `Pose3d`.                        |

{% hint style="info" %}
Prefer [`LimelightPoseEstimator`](/api-reference/java-reference/networktables/limelight-pose-estimator) / [`PoseEstimate`](/api-reference/java-reference/networktables/pose-estimate) for pose consumption in a periodic loop — they read the NT double-array entries directly (cheaper than JSON parsing) and include per-tag ambiguity data for filtering.
{% endhint %}

## See Also

* [LimelightData](/api-reference/java-reference/networktables/limelight-data)
* [PoseEstimate](/api-reference/java-reference/networktables/pose-estimate)


# LimelightUtils

**Package:** `limelight.networktables`

Static conversion helpers between WPILib geometry/units types and the flat `double[]` arrays the Limelight NetworkTables API uses. Used internally throughout YALL; useful directly if you're reading raw NT entries yourself.

***

## Methods

| Method                                                           | Returns         | Description                                                                                                                        |
| ---------------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `static toPose3D(double[] inData)`                               | `Pose3d`        | Converts a 6-element `[x, y, z, roll, pitch, yaw]` array (meters, degrees) into a `Pose3d`. Empty `Pose3d` if `inData.length < 6`. |
| `static toPose2D(double[] inData)`                               | `Pose2d`        | Same input format; keeps only `x`, `y`, and `yaw`.                                                                                 |
| `static toTranslation3d(double[] translation)`                   | `Translation3d` | Converts a 3-element `[x, y, z]` array (meters) into a `Translation3d`.                                                            |
| `static toOrientation(double[] orientation)`                     | `Orientation3d` | Converts a 6-element `[yaw, yawrate, pitch, pitchrate, roll, rollrate]` array (degrees) into an `Orientation3d`.                   |
| `static orientation3dToArray(Orientation3d orientation)`         | `double[]`      | Inverse of `toOrientation`.                                                                                                        |
| `static pose3dToArray(Pose3d pose)`                              | `double[]`      | Converts a `Pose3d` into `[x, y, z, roll, pitch, yaw]` (meters, degrees).                                                          |
| `static pose2dToArray(Pose2d pose)`                              | `double[]`      | Converts a `Pose2d` into `[x, y, 0, 0, 0, yaw]` (meters, degrees).                                                                 |
| `static translation3dToArray(Translation3d translation)`         | `double[]`      | Converts a `Translation3d` into `[x, y, z]` (meters).                                                                              |
| `static extractArrayEntry(double[] inData, int position)`        | `double`        | Returns `inData[position]`, or `0` if `position` is out of bounds. Used to safely decode variable-length NT arrays.                |
| `static sanitizeName(String name)`                               | `String`        | Returns `name`, or `"limelight"` if `name` is `null`/empty.                                                                        |
| `static getLimelightURLString(String tableName, String request)` | `URL`           | Builds `http://<tableName>.local:5807/<request>` for HTTP calls like snapshot capture.                                             |

## See Also

* [PoseEstimate](/api-reference/java-reference/networktables/pose-estimate)
* [Orientation3d](/api-reference/java-reference/networktables/orientation3d)


# Orientation3d

**Package:** `limelight.networktables`

Bundles a robot's 3D rotation with its angular velocity, in the shape MegaTag2 expects via [`LimelightSettings.withRobotOrientation`](/api-reference/java-reference/networktables/limelight-settings).

***

## Constructors

```java
Orientation3d(Rotation3d orientation, AngularVelocity yaw, AngularVelocity pitch, AngularVelocity roll)
Orientation3d(Rotation3d orientation, AngularVelocity3d angularVelocity)
```

***

## Fields

| Field             | Type                | Description                     |
| ----------------- | ------------------- | ------------------------------- |
| `orientation`     | `Rotation3d`        | Current robot rotation.         |
| `angularVelocity` | `AngularVelocity3d` | Current robot angular velocity. |

## Usage

```java
limelight.getSettings()
         .withRobotOrientation(new Orientation3d(
             gyro.getRotation3d(),
             new AngularVelocity3d(
                 DegreesPerSecond.of(gyro.getPitchVelocity()),
                 DegreesPerSecond.of(gyro.getRollVelocity()),
                 DegreesPerSecond.of(gyro.getYawVelocity()))))
         .save();
```

## See Also

* [AngularVelocity3d](/api-reference/java-reference/networktables/angular-velocity3d)
* [LimelightSettings#withRobotOrientation](/api-reference/java-reference/networktables/limelight-settings)


# AngularVelocity3d

**Package:** `limelight.networktables`

Immutable 3-axis angular velocity struct. Each axis is exposed under both its Cartesian name (`x`/`y`/`z`) and its rotational name (`roll`/`pitch`/`yaw`) — they're the same field.

***

## Constructor

```java
AngularVelocity3d(AngularVelocity x, AngularVelocity y, AngularVelocity z)
```

`x`/`roll`, `y`/`pitch`, `z`/`yaw`.

***

## Fields

| Field        | Type              | Description                        |
| ------------ | ----------------- | ---------------------------------- |
| `x`, `roll`  | `AngularVelocity` | Angular velocity about the X-axis. |
| `y`, `pitch` | `AngularVelocity` | Angular velocity about the Y-axis. |
| `z`, `yaw`   | `AngularVelocity` | Angular velocity about the Z-axis. |

## See Also

* [Orientation3d](/api-reference/java-reference/networktables/orientation3d)
* [AngularAcceleration3d](/api-reference/java-reference/networktables/angular-acceleration3d)


# AngularAcceleration3d

**Package:** `limelight.networktables`

Immutable 3-axis angular acceleration struct, following the same `x`/`roll`, `y`/`pitch`, `z`/`yaw` aliasing as [`AngularVelocity3d`](/api-reference/java-reference/networktables/angular-velocity3d). Produced by [`IMUResults.getIMUData()`](/api-reference/java-reference/results-and-telemetry/imu-results).

***

## Constructor

```java
AngularAcceleration3d(AngularAcceleration x, AngularAcceleration y, AngularAcceleration z)
```

***

## Fields

| Field        | Type                  | Description                            |
| ------------ | --------------------- | -------------------------------------- |
| `x`, `roll`  | `AngularAcceleration` | Angular acceleration about the X-axis. |
| `y`, `pitch` | `AngularAcceleration` | Angular acceleration about the Y-axis. |
| `z`, `yaw`   | `AngularAcceleration` | Angular acceleration about the Z-axis. |

## See Also

* [AngularVelocity3d](/api-reference/java-reference/networktables/angular-velocity3d)
* [IMUResults](/api-reference/java-reference/results-and-telemetry/imu-results)


# Target Types


# AprilTagFiducial

**Package:** `limelight.networktables.target`

A single AprilTag detection from the JSON `Fiducial` array in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results).

***

## Fields

| Field                              | Type     | Description                                    |
| ---------------------------------- | -------- | ---------------------------------------------- |
| `fiducialID`                       | `double` | Tag ID (`fID`).                                |
| `fiducialFamily`                   | `String` | Tag family, e.g. `"36H11C"` (`fam`).           |
| `ta`                               | `double` | Target area as a percentage of the image, 0-1. |
| `tx`, `ty`                         | `double` | Crosshair-relative offset in degrees.          |
| `tx_pixels`, `ty_pixels`           | `double` | Crosshair-relative offset in pixels.           |
| `tx_nocrosshair`, `ty_nocrosshair` | `double` | Principal-pixel-relative offset in degrees.    |
| `ts`                               | `double` | Timestamp in milliseconds from boot.           |

***

## Methods

Each pose pair below is computed by SolvePnP and exposed as both `Pose3d` and `Pose2d`:

| Method                                    | Returns           | Description                                              |
| ----------------------------------------- | ----------------- | -------------------------------------------------------- |
| `getCameraPose_TargetSpace()` / `...2D()` | `Pose3d`/`Pose2d` | Camera pose relative to the tag.                         |
| `getRobotPose_FieldSpace()` / `...2D()`   | `Pose3d`/`Pose2d` | Robot pose in field space, computed from this tag alone. |
| `getRobotPose_TargetSpace()` / `...2D()`  | `Pose3d`/`Pose2d` | Robot pose relative to the tag.                          |
| `getTargetPose_CameraSpace()` / `...2D()` | `Pose3d`/`Pose2d` | Tag pose relative to the camera.                         |
| `getTargetPose_RobotSpace()` / `...2D()`  | `Pose3d`/`Pose2d` | Tag pose relative to the robot.                          |

## See Also

* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)
* [RawFiducial](/api-reference/java-reference/results-and-telemetry/raw-fiducial)


# RetroreflectiveTape

**Package:** `limelight.networktables.target`

A single retroreflective/color target detection from the JSON `Retro` array in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results). Field and pose accessor layout is identical to [`AprilTagFiducial`](/api-reference/java-reference/target-types/apriltag-fiducial), minus tag ID/family.

***

## Fields

| Field                              | Type     | Description                                    |
| ---------------------------------- | -------- | ---------------------------------------------- |
| `ta`                               | `double` | Target area as a percentage of the image, 0-1. |
| `tx`, `ty`                         | `double` | Crosshair-relative offset in degrees.          |
| `tx_pixels`, `ty_pixels`           | `double` | Crosshair-relative offset in pixels.           |
| `tx_nocrosshair`, `ty_nocrosshair` | `double` | Principal-pixel-relative offset in degrees.    |
| `ts`                               | `double` | Timestamp in milliseconds from boot.           |

***

## Methods

| Method                                    | Returns           | Description                         |
| ----------------------------------------- | ----------------- | ----------------------------------- |
| `getCameraPose_TargetSpace()` / `...2D()` | `Pose3d`/`Pose2d` | Camera pose relative to the target. |
| `getRobotPose_FieldSpace()` / `...2D()`   | `Pose3d`/`Pose2d` | Robot pose in field space.          |
| `getRobotPose_TargetSpace()` / `...2D()`  | `Pose3d`/`Pose2d` | Robot pose relative to the target.  |
| `getTargetPose_CameraSpace()` / `...2D()` | `Pose3d`/`Pose2d` | Target pose relative to the camera. |
| `getTargetPose_RobotSpace()` / `...2D()`  | `Pose3d`/`Pose2d` | Target pose relative to the robot.  |

## See Also

* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)
* [AprilTagFiducial](/api-reference/java-reference/target-types/apriltag-fiducial)


# Barcode

**Package:** `limelight.networktables.target`

A single decoded barcode/QR/DataMatrix detection from the JSON `Barcode` array in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results).

***

## Fields

| Field                              | Type         | Description                                                                               |
| ---------------------------------- | ------------ | ----------------------------------------------------------------------------------------- |
| `family`                           | `String`     | Barcode family, e.g. `"QR"`, `"DataMatrix"` (`fam`).                                      |
| `data`                             | `String`     | Decoded content of the barcode.                                                           |
| `ta`                               | `double`     | Target area as a percentage of the image, 0-1.                                            |
| `tx`, `ty`                         | `double`     | Crosshair-relative offset in degrees.                                                     |
| `tx_pixels`, `ty_pixels`           | `double`     | Crosshair-relative offset in pixels.                                                      |
| `tx_nocrosshair`, `ty_nocrosshair` | `double`     | Principal-pixel-relative offset in degrees.                                               |
| `corners`                          | `double[][]` | Pixel-space corner coordinates `[x0,y0,x1,y1,...]`. Must be enabled in the LL output tab. |

***

## Methods

| Method        | Returns  | Description       |
| ------------- | -------- | ----------------- |
| `getFamily()` | `String` | Returns `family`. |

## See Also

* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)


# NeuralClassifier

**Package:** `limelight.networktables.target.pipeline`

A single result from the JSON `Classifier` array in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results). The classifier pipeline labels the whole image/zone rather than drawing a bounding box.

***

## Fields

| Field                    | Type     | Description                                   |
| ------------------------ | -------- | --------------------------------------------- |
| `className`              | `String` | Predicted class name (`class`).               |
| `classID`                | `double` | Predicted class ID (`classID`).               |
| `confidence`             | `double` | Prediction confidence (`conf`).               |
| `zone`                   | `double` | Zone index the classification applies to.     |
| `tx`, `ty`               | `double` | Object position in the image as a percentage. |
| `tx_pixels`, `ty_pixels` | `double` | Object position in the image as pixels.       |

## Usage

```java
limelight.getLatestResults().ifPresent(result -> {
    for (NeuralClassifier object : result.targets_Classifier) {
        if (object.className.equals("algae") && object.confidence > 0.7) {
            // valid detection
        }
    }
});
```

## See Also

* [NeuralDetector](/api-reference/java-reference/target-types/neural-detector)
* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)


# NeuralDetector

**Package:** `limelight.networktables.target.pipeline`

A single result from the JSON `Detector` array in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results). Unlike [`NeuralClassifier`](/api-reference/java-reference/target-types/neural-classifier), the detector pipeline reports individual bounding-box detections with crosshair-relative angles, matching the layout of [`AprilTagFiducial`](/api-reference/java-reference/target-types/apriltag-fiducial)/[`RetroreflectiveTape`](/api-reference/java-reference/target-types/retroreflective-tape).

***

## Fields

| Field                              | Type     | Description                                    |
| ---------------------------------- | -------- | ---------------------------------------------- |
| `className`                        | `String` | Predicted class name (`class`).                |
| `classID`                          | `double` | Predicted class ID (`classID`).                |
| `confidence`                       | `double` | Prediction confidence (`conf`).                |
| `ta`                               | `double` | Target area as a percentage of the image, 0-1. |
| `tx`, `ty`                         | `double` | Crosshair-relative offset in degrees.          |
| `tx_pixels`, `ty_pixels`           | `double` | Crosshair-relative offset in pixels.           |
| `tx_nocrosshair`, `ty_nocrosshair` | `double` | Principal-pixel-relative offset in degrees.    |

## See Also

* [NeuralClassifier](/api-reference/java-reference/target-types/neural-classifier)
* [RawDetection](/api-reference/java-reference/results-and-telemetry/raw-detection)


# Results & Telemetry


# RawFiducial

**Package:** `limelight.results`

Per-tag detail decoded from the raw NetworkTables `rawfiducials` entry, via [`LimelightData.getRawFiducials()`](/api-reference/java-reference/networktables/limelight-data). Also populated inside [`PoseEstimate.rawFiducials`](/api-reference/java-reference/networktables/pose-estimate) for the tags that contributed to a pose estimate.

***

## Fields

| Field          | Type     | Description                                            |
| -------------- | -------- | ------------------------------------------------------ |
| `id`           | `int`    | AprilTag ID.                                           |
| `txnc`, `tync` | `double` | Principal-pixel-relative offset in the image.          |
| `ta`           | `double` | Target area as a percentage of the image.              |
| `distToCamera` | `double` | Distance from the tag to the camera, in meters.        |
| `distToRobot`  | `double` | Distance from the tag to the robot, in meters.         |
| `ambiguity`    | `double` | Pose ambiguity, `0` to `1`. Lower is more trustworthy. |

## Usage

`ambiguity` is the standard signal for rejecting unreliable single-tag poses — see [`PoseEstimate.getMinTagAmbiguity()`](/api-reference/java-reference/networktables/pose-estimate) for a ready-made aggregate.

## See Also

* [PoseEstimate](/api-reference/java-reference/networktables/pose-estimate)
* [AprilTagFiducial](/api-reference/java-reference/target-types/apriltag-fiducial)


# RawDetection

**Package:** `limelight.results`

Per-detection detail decoded from the raw NetworkTables `rawdetections` entry, via [`LimelightData.getRawDetections()`](/api-reference/java-reference/networktables/limelight-data). Includes the four corner points of the detection's bounding quadrilateral, which the JSON [`NeuralDetector`](/api-reference/java-reference/target-types/neural-detector) result does not expose.

***

## Fields

| Field                                                  | Type     | Description                                          |
| ------------------------------------------------------ | -------- | ---------------------------------------------------- |
| `classId`                                              | `int`    | Predicted class ID.                                  |
| `txnc`, `tync`                                         | `double` | Principal-pixel-relative offset in degrees.          |
| `ta`                                                   | `double` | Target area, 0-100% of image.                        |
| `corner0_X` .. `corner3_X`, `corner0_Y` .. `corner3_Y` | `double` | Pixel coordinates of the four bounding-quad corners. |

## See Also

* [NeuralDetector](/api-reference/java-reference/target-types/neural-detector)
* [LimelightData](/api-reference/java-reference/networktables/limelight-data)


# IMUResults

**Package:** `limelight.results`

Onboard IMU data from the Limelight 4, populated from the JSON `imu` object in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results).

***

## Fields

| Field        | Type        | Description                                                                                                                       |
| ------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `data`       | `double[9]` | Raw IMU array: `[roll, pitch, yaw, roll_rate, pitch_rate, yaw_rate, accel_x, accel_y, accel_z]` (degrees, degrees/s, degrees/s²). |
| `quaternion` | `double[4]` | Orientation quaternion `[w, x, y, z]`.                                                                                            |
| `yaw`        | `double`    | Final fused yaw, in degrees.                                                                                                      |

***

## Methods

| Method          | Returns                                      | Description                                                                                                                                                                                                                                        |
| --------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Quaternion()`  | `Rotation3d`                                 | `quaternion` decoded as a `Rotation3d`.                                                                                                                                                                                                            |
| `getIMUData()`  | `Pair<Orientation3d, AngularAcceleration3d>` | `data` decoded into an [`Orientation3d`](/api-reference/java-reference/networktables/orientation3d) (orientation + angular velocity) paired with an [`AngularAcceleration3d`](/api-reference/java-reference/networktables/angular-acceleration3d). |
| `getFusedYaw()` | `Angle`                                      | `yaw` as a WPILib `Angle`.                                                                                                                                                                                                                         |

## See Also

* [Orientation3d](/api-reference/java-reference/networktables/orientation3d)
* [LimelightSettings.ImuMode](/api-reference/java-reference/networktables/limelight-settings)


# HardwareReport

**Package:** `limelight.results`

System-level hardware telemetry (2026+ firmware), from the JSON `hw` object in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results).

***

## Fields

| Field         | Type         | Description                                                                                                 |
| ------------- | ------------ | ----------------------------------------------------------------------------------------------------------- |
| `cameraId`    | `String`     | Camera sensor ID (`cid`).                                                                                   |
| `cpuUsage`    | `double`     | CPU usage percentage.                                                                                       |
| `diskFree`    | `double`     | Free disk space, in MB.                                                                                     |
| `diskTotal`   | `double`     | Total disk space, in MB.                                                                                    |
| `ramUsage`    | `double`     | RAM usage percentage.                                                                                       |
| `temperature` | `double`     | CPU temperature, in Celsius.                                                                                |
| `hailoStats`  | `HailoStats` | Hailo accelerator stats. See [HailoStats](/api-reference/java-reference/results-and-telemetry/hailo-stats). |

***

## Methods

| Method      | Returns       | Description                              |
| ----------- | ------------- | ---------------------------------------- |
| `getTemp()` | `Temperature` | `temperature` as a WPILib `Temperature`. |

## See Also

* [HailoStats](/api-reference/java-reference/results-and-telemetry/hailo-stats)
* [LimelightResults](/api-reference/java-reference/networktables/limelight-results)


# HailoStats

**Package:** `limelight.results`

Stats for the Hailo neural accelerator module (sold separately, Limelight 4 only), from the JSON `hailo` object nested in [`HardwareReport`](/api-reference/java-reference/results-and-telemetry/hardware-report).

***

## Fields

| Field      | Type     | Description                                        |
| ---------- | -------- | -------------------------------------------------- |
| `present`  | `int`    | `1` if a Hailo accelerator is detected, else `0`.  |
| `type`     | `String` | Hailo device type string.                          |
| `temp`     | `double` | Hailo temperature, in Celsius.                     |
| `power`    | `double` | Hailo power consumption, in watts.                 |
| `throttle` | `int`    | `1` if throttling capability is enabled, else `0`. |

***

## Methods

| Method         | Returns   | Description                  |
| -------------- | --------- | ---------------------------- |
| `getPower()`   | `Power`   | `power` as a WPILib `Power`. |
| `getEnabled()` | `boolean` | `true` if `throttle == 1`.   |

## See Also

* [HardwareReport](/api-reference/java-reference/results-and-telemetry/hardware-report)


# RewindStats

**Package:** `limelight.results`

Rewind buffer status, from the JSON `rewind` object in [`LimelightResults`](/api-reference/java-reference/networktables/limelight-results). Supported hardware only (Limelight 4).

***

## Fields

| Field            | Type     | Description                                                                       |
| ---------------- | -------- | --------------------------------------------------------------------------------- |
| `bufferUsage`    | `double` | Buffer usage fraction, `0.0` to `1.0`.                                            |
| `enabled`        | `int`    | `1` if rewind recording is enabled, `0` if paused.                                |
| `flushing`       | `int`    | `1` if the buffer is currently flushing to disk.                                  |
| `frameCount`     | `int`    | Number of frames currently in the buffer.                                         |
| `latencyPenalty` | `int`    | Latency penalty added by rewind recording, in microseconds (typically 500µs-1ms). |
| `storedSeconds`  | `double` | Seconds of video currently held in the buffer.                                    |

***

## Methods

| Method                | Returns   | Description                          |
| --------------------- | --------- | ------------------------------------ |
| `getLatencyPenalty()` | `Time`    | `latencyPenalty` as a WPILib `Time`. |
| `getBufferTime()`     | `Time`    | `storedSeconds` as a WPILib `Time`.  |
| `getEnabled()`        | `boolean` | `true` if `enabled == 1`.            |
| `isFlushing()`        | `boolean` | `true` if `flushing == 1`.           |
| `getFrameCount()`     | `int`     | Returns `frameCount`.                |

## See Also

* [Limelight#rewindCapture](/api-reference/java-reference/limelight)
* [LimelightSettings#withRewindEnable](/api-reference/java-reference/networktables/limelight-settings)


# Overview

**Package:** `yall`

YALL ships a Python port with the same class names and most of the same method names as the Java library, built on `ntcore` directly (no WPILib Python `Limelight`-specific dependency beyond networktables/geometry). If you know the [Java API](/api-reference/java-reference/java-reference), the Python API will look immediately familiar.

```python
from yall.limelight import Limelight, EstimationMode
from yall.networktables.geometry import Orientation3d, AngularVelocity3d

limelight = Limelight("limelight")
limelight.getSettings().withLimelightLEDMode(LEDMode.PipelineControl).withCameraToRobot(Pose3d())
```

## Module Layout

| Module                        | Contents                                                                                                                                                                                     |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `yall.limelight`              | `Limelight`, `LimelightSettings`, `LimelightData`, `LimelightPipelineData`, `LimelightTargetData`, `LimelightResults`, `LimelightPoseEstimator`, `PoseEstimate`, `BotPose`, `EstimationMode` |
| `yall.results`                | `RawFiducial`, `RawDetection`                                                                                                                                                                |
| `yall.networktables.geometry` | `Orientation3d`, `AngularVelocity3d`                                                                                                                                                         |
| `yall.networktables.targets`  | `RetroreflectiveTape`, `Barcode`, `AprilTagFiducial`, `NeuralClassifier`, `NeuralDetector`                                                                                                   |
| `yall.networktables.util`     | Array/pose conversion helpers, equivalent to Java's `LimelightUtils`                                                                                                                         |
| `yall.deprecated`             | Legacy compatibility shims                                                                                                                                                                   |

## Differences from the Java API

The Python port is a direct translation of an earlier revision of the Java library and has not yet caught up to every 2026 addition. Known differences:

* `createPoseEstimator(megatag2: bool)` takes a `bool` instead of Java's `EstimationMode` enum.
* `LimelightSettings.withCameraToRobot(pose)` is the Python equivalent of Java's `withCameraOffset(Pose3d)`.
* `withArilTagIdFilter(...)` — note the typo carried over from an earlier API revision; this is the equivalent of Java's `withAprilTagIdFilter`.
* No Python equivalents yet for `IMUResults`, `HardwareReport`, `HailoStats`, `RewindStats`, or rewind-capture / USB port-forwarding helpers.

For the full method-by-method reference, use the [Java reference](/api-reference/java-reference/java-reference) as the source of truth — field names and behavior are otherwise identical — and cross-check against `yall/python/yall/` in the YALL repository for the exact Python signature.

## See Also

* [Java API](/api-reference/java-reference/java-reference)


