> This is the Markdown version of the page. For the complete Lattice Developers documentation index, fetch https://developer.anduril.com/llms.txt. Append .md to any page URL for its clean Markdown.

# Create a track

> Publish fusion-ready tracks from sensors so Lattice can correlate them

This page shows how to publish tracks that the Lattice fusion engine can ingest and correlate. It covers
2D bearing-only tracks, 3D signal-of-interest tracks with an estimated range, and fully resolved 3D
tracks with position and velocity uncertainty. For more information on entities, see
[Entities overview](/guides/entities/overview).

A *track* represents any entity tracked by another asset or integration source.
Tracks are not directly under the control of friendly forces. This includes aircraft
tracks from radar or sensor hits, signal detections, and vehicles, people, or animals detected through cameras.

## Before you begin

* To publish tracks, [set up the Lattice SDK](/guides/getting-started/set-up) and set up a Lattice environment.
* Publish the observing sensor as a `TEMPLATE_ASSET` entity before generating tracks. The fusion
  engine uses the sensor's entity ID, which you specify in each track's `relationships.trackedBy`, to
  identify which sensors contribute to the track. The examples on this page pair with the sensors from
  [Create an asset](/guides/entities/create-an-asset):

  | Track                                                 | Sensor asset                                                                                  | `sensor_id`    |
  | ----------------------------------------------------- | --------------------------------------------------------------------------------------------- | -------------- |
  | [2D bearing-only](#publish-a-2d-bearing-only-track)   | [Camera sensor](/guides/entities/create-an-asset#example-camera-sensor)                       | `camera-01-eo` |
  | [RF signal with line-of-bearing](#publish-a-3d-track) | [UxV with onboard sensors](/guides/entities/create-an-asset#example-uxv-with-onboard-sensors) | `rf-1`         |
  | [Resolved 3D detection](#publish-a-3d-track)          | [Multi-panel radar](/guides/entities/create-an-asset#example-multi-panel-radar)               | `panel-1`      |
* Choose a unique [`integration_name`](/reference/rest/entities/publish-entity#request.body.provenance.integrationName)
  and [`data_type`](/reference/rest/entities/publish-entity#request.body.provenance.dataType) pair. The
  fusion engine uses the combination to distinguish your track feed from other sources.

> **gRPC authentication**
>
> These gRPC examples authenticate with a static environment token attached as request metadata.
> If you are using OAuth 2.0 client credentials instead, [set up the token refresh module](/guides/getting-started/authenticate#client-credentials) before running the examples on this page.

## Produce fusion-ready tracks

To make a track eligible for correlation by the Lattice fusion engine, populate the following components:

#### Generate with \`PublishEntity\`

Call [`PublishEntity`](/reference/rest/entities/publish-entity), or
[`PublishEntities` (gRPC-only)](/reference/grpc/anduril-entitymanager-v-1/entity-manager-api/anduril-entitymanager-v-1-publish-entities)
to publish multiple entities in a single request.

#### Set identity and lifetime fields

**`entity_id`** `string`

Stable identifier for the track. Use the same value on every update so the fusion engine
can correlate successive observations into a single track.

---

**`aliases.name`** `string`

Human-readable label displayed in the Lattice common operational picture.

---

**`created_time`** `Timestamp`

Time the track was first observed. Set this once and do not change it on subsequent updates;
the fusion engine uses it to establish track age.

---

**`expiry_time`** `Timestamp`

Future time at which Lattice automatically removes your contribution to the track. Set to
approximately 10 seconds ahead of the current time on every update. While your sensor keeps
detecting the target, each new detection refreshes the expiry and keeps your contribution
live. When your sensor stops detecting, your contribution expires; the fused track persists
as long as any other sensor continues to contribute. For more information, see
[Manage update rates](#manage-update-rates).

---

**`aliases.alternate_ids`** `AlternateId[]`

Additional identifiers from the source system, such as `ALT_ID_TYPE_CALLSIGN`,
`ALT_ID_TYPE_LINK16_TRACK_NUMBER`, `ALT_ID_TYPE_VMF_URN`, or `ALT_ID_TYPE_SERIAL_NUMBER`. Populate one entry per identifier so
downstream systems can cross-reference tracks.

---

> **Warning**
>
> Streaming endpoints reject `no_expiry`. Always set a finite `expiry_time` when you
> publish over a stream using [`PublishEntities`](/reference/grpc/anduril-entitymanager-v-1/entity-manager-api/anduril-entitymanager-v-1-publish-entities).

#### Populate position and uncertainty

**`location`** `Location`

Resolved position of the track, including latitude, longitude, and HAE altitude. Populate
this field for all 3D tracks.

---

**`location_uncertainty.position_enu_cov`** `PositionCovariance`

East-North-Up (ENU) position covariance matrix expressing position uncertainty. A diagonal-only matrix
is valid when the full matrix is unavailable.

---

**`tracked.track_quality_wrapper`** `TrackQuality`

Link-16 track quality score from 0 to 15. Use this instead of `position_enu_cov` only when
your source system produces a track-quality score rather than a covariance matrix.

---

#### Set ontology

**`ontology.template`** `Ontology.Template`

Classification template that tells Lattice how to render and handle the entity. Set to
`TEMPLATE_TRACK` for resolved positional tracks, or `TEMPLATE_SIGNAL_OF_INTEREST` for RF
emitter tracks and 2D camera sensor tracks.

---

#### Set provenance and update cadence

**`provenance.integration_name`** `string`

Name of the integration publishing the track. Together with `data_type`, this pair uniquely
identifies your feed so the fusion engine can distinguish it from other sources.

---

**`provenance.data_type`** `string`

Type of data being published, such as `camera_lob` or `rf_sigint`. Together with
`integration_name`, this pair uniquely identifies your feed.

---

**`provenance.source_update_time`** `Timestamp`

Timestamp of the measurement that produced this update. Set it to the time your sensor
observed the target. Lattice uses it to detect stale tracks and rejects any update whose
`source_update_time` is earlier than or equal to the value it already holds. Publish a new
update only when your sensor produces a new detection.

---

#### Declare contributing sensors

**`relationships`** `Relationship[]`

List of sensor relationships for the track. Populate one entry per contributing sensor so
the fusion engine knows which sensors produced the observation.

---

**`relationships.related_entity_id`** `string`

Entity ID of the sensor asset that produced this track. Publish the sensor asset before any
track that references it.

---

**`relationships.relationship_id`** `string`

Stable, unique identifier for this sensor-to-track relationship. A common pattern is
`<track_id>-tracked-by-<sensor_id>`.

---

**`relationships.relationship_type.tracked_by`** `TrackedBy`

Describes the sensor system actively tracking the entity. Include
`actively_tracking_sensors` with `sensor_id`, `sensor_type`, and `operational_state` values
that match the corresponding entries in the tracking entity's top-level `sensors` component.
Set `last_measurement_timestamp` to the time of the most recent measurement.

---

> **Info**
>
> For single-sensor tracks, publish one `trackedBy` relationship. For tracks detected by
> multiple sensors in your system, publish one `trackedBy` relationship per contributing
> sensor that exists in Lattice as an asset entity.

#### Choose a line-of-bearing component by sensor modality

A single track must carry its line-of-bearing data in exactly one component, selected by the
sensing modality:

**`signal.line_of_bearing`** `LineOfBearing`

Line-of-bearing measurement for radio-frequency sensors. Use this component instead of
`tracked.line_of_bearing` when the observing sensor is an RF direction-finding system.

---

**`tracked.line_of_bearing`** `LineOfBearing`

Line-of-bearing measurement for camera and acoustic sensors. Use this component instead of
`signal.line_of_bearing` when the observing sensor is a camera or acoustic array.

---

**`bearing_elevation_covariance_rad2`** `BearingElevationCovariance`

Bearing and elevation covariance in radians squared. Populate this field on whichever
line-of-bearing component you use; the fusion engine uses it to decide whether to fuse the
bearing or render it visually only.

---

#### Improve fusion quality with optional fields

**`tracked.radar_cross_section`** `RadarCrossSection`

Measured radar cross-section of the target. Optional; the fusion engine uses it to improve
track association when the value is present.

---

**`dimensions.length_m`** `double`

Estimated length of the target in meters. Optional; the fusion engine uses it alongside
radar cross-section to improve association accuracy when the value is present.

---

#### Populate geocentric kinematics for engage targets

**`kinematics.kinematics_geocentric`** `KinematicsGeocentric`

Earth-centered, earth-fixed position and velocity of the target. Populate this field when
you use the track as an engage target; downstream fire-control systems rely on it to
compute engagement geometry.

---

## Symbology

Populate the following components on every track so downstream rendering and handling are correct:

**`mil_view.nationality`** `Nationality`

Nationality of the track, used downstream to pick the flag and the MIL-STD-2525C country code.
Set explicitly when known; leaving it as `NATIONALITY_INVALID` produces generic symbology.

---

**`symbology.mil_std_2525_c.sidc`** `string`

Valid 15-character MIL-STD-2525C Symbol Identification Code. Required for downstream
command-and-control systems such as NGC2 to render the track; entities without a SIDC fall back
to a generic icon.

---

**`indicators`** `Indicators`

Flags that describe the operational context of the track. Set `simulated` for all tracks
published during test and evaluation exercises. Additional flags, including `exercise`,
`emergency`, and `c2`, are available when applicable.

---

**`data_classification`** `DataClassification`

Classification level of the track data. Required when publishing classified content so Lattice
and downstream systems can handle the data according to its classification.

---

> **Info**
>
> MIL-STD-2525D is not supported by the current schema. Use 2525C and populate
> `symbology.mil_std_2525_c.sidc`.

## Publish a 2D bearing-only track

Use a 2D bearing-only track when your sensor, such as a camera or acoustic array, reports a
direction to the target but not a range. Populate
[`tracked.line_of_bearing`](/reference/rest/entities/publish-entity#request.body.tracked.lineOfBearing)
with the sensor's position at the time of the measurement and the angle pointing toward the target.

Define the entity model's required components. To represent a bearing-only detection:

* Set `template` to `TEMPLATE_SIGNAL_OF_INTEREST`.
* Populate `tracked.lineOfBearing.angleOfArrival` with the sensor's pose and
  bearing/elevation covariance.
* Add a `trackedBy` relationship that references the sensor's entity ID.

**`entity.json`**

```json maxLines=30 title="entity.json"
{
  "entityId": "UNIQUE_ENTITY_ID",
  "description": "Bearing-only detection from a camera sensor",
  "isLive": true,
  "createdTime": "2026-05-01T00:00:00.000Z",
  "expiryTime": "2026-05-01T00:00:10.000Z",
  "aliases": { "name": "Track-12345678" },
  "ontology": { "template": "TEMPLATE_SIGNAL_OF_INTEREST" },
  "milView": {
    "disposition": "DISPOSITION_UNKNOWN",
    "environment": "ENVIRONMENT_SURFACE"
  },
  "tracked": {
    "lineOfBearing": {
      "angleOfArrival": {
        "relativePose": {
          "pos": { "lat": 36.66633492530301, "lon": -116.9117674522639, "alt": 780.0 },
          "attEnu": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 }
        },
        "bearingElevationCovarianceRad2": { "mxx": 0.0009, "mxy": 0.0, "myy": 0.0025 }
      }
    }
  },
  "locationUncertainty": {
    "positionEnuCov": { "mxx": 25.0, "myy": 25.0, "mzz": 100.0 }
  },
  "relationships": {
    "relationships": [{
      "relatedEntityId": "SENSOR_ENTITY_ID",
      "relationshipId": "UNIQUE_ENTITY_ID-tracked-by-SENSOR_ENTITY_ID",
      "relationshipType": {
        "trackedBy": {
          "lastMeasurementTimestamp": "2026-05-01T00:00:00.000Z",
          "activelyTrackingSensors": {
            "sensors": [{
              "sensorId": "camera-01-eo",
              "sensorType": "SENSOR_TYPE_CAMERA",
              "operationalState": "OPERATIONAL_STATE_OPERATIONAL"
            }]
          }
        }
      }
    }]
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "camera_lob",
    "sourceUpdateTime": "2026-05-01T00:00:00.000Z"
  }
}
```

Take a closer look at the components that describe the bearing measurement and the sensor
that produced it:

**`tracked`**

```json title="tracked"
"tracked": {
  "lineOfBearing": {
    "angleOfArrival": {
      "relativePose": {
        // Sensor position, in latitude, longitude, and altitude meters,
        // at the time the measurement was recorded.
        "pos": { "lat": 36.66633492530301, "lon": -116.9117674522639, "alt": 780.0 },
        // Quaternion rotating the Pose frame into the ENU frame. The
        // Pose frame's +x axis points toward the target.
        "attEnu": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 }
      },
      // Bearing and elevation covariance, in radians squared. The
      // fusion engine uses this to decide whether to fuse the
      // bearing or render it visually only.
      "bearingElevationCovarianceRad2": {
        "mxx": 0.0009,
        "mxy": 0.0,
        "myy": 0.0025
      }
    }
  }
}
```

**`relationships`**

```json title="relationships"
"relationships": {
  "relationships": [
    {
      // Entity ID of the sensor that produced this detection.
      "relatedEntityId": "SENSOR_ENTITY_ID",
      // Stable, unique identifier for this relationship.
      "relationshipId": "UNIQUE_ENTITY_ID-tracked-by-SENSOR_ENTITY_ID",
      "relationshipType": {
        "trackedBy": {
          // Timestamp of the most recent measurement from this sensor.
          "lastMeasurementTimestamp": "2026-05-01T00:00:00.000Z",
          // The subset of the tracking entity's sensors that produced
          // this detection. Reuse the same sensor_id and sensor_type
          // values that appear in the tracking entity's top-level
          // `sensors` component.
          "activelyTrackingSensors": {
            "sensors": [
              {
                "sensorId": "camera-01-eo",
                "sensorType": "SENSOR_TYPE_CAMERA",
                "operationalState": "OPERATIONAL_STATE_OPERATIONAL"
              }
            ]
          }
        }
      }
    }
  ]
}
```

**`provenance`**

```json title="provenance"
"provenance": {
  // integration_name and data_type together must uniquely identify
  // this track feed.
  "integrationName": "your_integration_name",
  "dataType": "camera_lob",
  // Set to the time of the detection. Publish a new update only
  // when your sensor produces a new detection.
  "sourceUpdateTime": "2026-05-01T00:00:00.000Z"
}
```

Use the [`PublishEntity`](/reference/rest/entities/publish-entity) API method to publish the
entity:

```go title={"Go (REST)"} startLine={58} maxLines={91}
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
	"github.com/google/uuid"
)

func main() {
	// Get environment variables
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")

	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
	// entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Initialize headers for sandbox authorization
	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	// Create the client
	LatticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()

	// Continuously publish the entity
	for {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &trackId,
			Description: Lattice.String("Bearing-only detection from a camera sensor"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String(fmt.Sprintf("Track-%s", trackId[:8])),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(10 * time.Second)),
			Ontology: &Lattice.Ontology{
				Template: Lattice.OntologyTemplateTemplateSignalOfInterest.Ptr(),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionUnknown.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentSurface.Ptr(),
			},
			// 2D bearing-only tracks populate line_of_bearing on the
			// tracked component. Lattice needs bearing/elevation covariance
			// to evaluate whether the LOB is fusable into the COP.
			Tracked: &Lattice.Tracked{
				LineOfBearing: &Lattice.LineOfBearing{
					AngleOfArrival: &Lattice.AngleOfArrival{
						RelativePose: &Lattice.Pose{
							Pos: &Lattice.Lla{
								Lat: Lattice.Float64(36.66633492530301),
								Lon: Lattice.Float64(-116.9117674522639),
								Alt: Lattice.Float64(780.0),
							},
							// Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
							AttEnu: &Lattice.Quaternion{
								X: Lattice.Float64(0.0),
								Y: Lattice.Float64(0.0),
								Z: Lattice.Float64(0.0),
								W: Lattice.Float64(1.0),
							},
						},
						BearingElevationCovarianceRad2: &Lattice.TMat2{
							Mxx: Lattice.Float64(0.0009),
							Mxy: Lattice.Float64(0.0),
							Myy: Lattice.Float64(0.0025),
						},
					},
				},
			},
			// position_enu_cov is required for the track to be eligible for
			// fusion. A diagonal-only matrix is valid when cross-terms are
			// unknown.
			LocationUncertainty: &Lattice.LocationUncertainty{
				PositionEnuCov: &Lattice.EntityManagerTMat3{
					Mxx: Lattice.Float64(25.0),
					Myy: Lattice.Float64(25.0),
					Mzz: Lattice.Float64(100.0),
				},
			},
			Relationships: &Lattice.Relationships{
				Relationships: []*Lattice.Relationship{
					{
						RelatedEntityID: Lattice.String(sensorEntityId),
						RelationshipID:  Lattice.String(relationshipId),
						RelationshipType: &Lattice.RelationshipType{
							TrackedBy: &Lattice.TrackedBy{
								LastMeasurementTimestamp: Lattice.Time(latestTimestamp),
								// Echo the subset of the tracking entity's sensors
								// that produced this detection. Each entry's sensor_id
								// and sensor_type must match the corresponding entry
								// on the tracking entity's top-level `sensors` component.
								ActivelyTrackingSensors: &Lattice.Sensors{
									Sensors: []*Lattice.Sensor{
										{
											SensorID:         Lattice.String("camera-01-eo"),
											SensorType:       Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
											OperationalState: Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &Lattice.Provenance{
				// integration_name + data_type must be unique for your
				// track feed so Lattice can distinguish it from other sources.
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("camera_lob"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Println("Publishing track")
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```java title={"Java (REST)"} startLine={78} maxLines={91}
package org.example;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Aliases;
import com.anduril.types.AngleOfArrival;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerTMat3;
import com.anduril.types.LineOfBearing;
import com.anduril.types.Lla;
import com.anduril.types.LocationUncertainty;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Pose;
import com.anduril.types.Provenance;
import com.anduril.types.Quaternion;
import com.anduril.types.Relationship;
import com.anduril.types.RelationshipType;
import com.anduril.types.Relationships;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TMat2;
import com.anduril.types.Tracked;
import com.anduril.types.TrackedBy;



public class PublishTrack2dLob {
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables and ensure URL has https://
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
        // entity) when running against a live environment.
        String sensorEntityId = "<SENSOR_ENTITY_ID>";

        try {
            // Create Lattice client with Sandbox authentication
            Lattice client = Lattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Generate a unique ID for the entity
            String trackId = UUID.randomUUID().toString();
            String relationshipId = trackId + "-tracked-by-" + sensorEntityId;

            // Get creation time
            Instant creationTime = Instant.now();

            // Continuously publish the entity
            while (true) {
                try {
                    // Get current timestamp
                    Instant latestTimestamp = Instant.now();

                    // Create the entity
                    Entity entity = Entity.builder()
                        .entityId(trackId)
                        .description("Bearing-only detection from a camera sensor")
                        .aliases(Aliases.builder()
                            .name("Track-" + trackId.substring(0, 8))
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(10, ChronoUnit.SECONDS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_SIGNAL_OF_INTEREST)
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_UNKNOWN)
                            .environment(MilViewEnvironment.ENVIRONMENT_SURFACE)
                            .build())
                        // 2D bearing-only tracks populate lineOfBearing on the
                        // tracked component. Lattice needs bearing/elevation covariance
                        // to evaluate whether the LOB is fusable into the COP.
                        .tracked(Tracked.builder()
                            .lineOfBearing(LineOfBearing.builder()
                                .angleOfArrival(AngleOfArrival.builder()
                                    .relativePose(Pose.builder()
                                        .pos(Lla.builder()
                                            .lat(36.66633492530301)
                                            .lon(-116.9117674522639)
                                            .alt(780.0)
                                            .build())
                                        // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                        .attEnu(Quaternion.builder()
                                            .x(0.0)
                                            .y(0.0)
                                            .z(0.0)
                                            .w(1.0)
                                            .build())
                                        .build())
                                    .bearingElevationCovarianceRad2(TMat2.builder()
                                        .mxx(0.0009)
                                        .mxy(0.0)
                                        .myy(0.0025)
                                        .build())
                                    .build())
                                .build())
                            .build())
                        // position_enu_cov is required for the track to be
                        // eligible for fusion. A diagonal-only matrix is valid
                        // when cross-terms are unknown.
                        .locationUncertainty(LocationUncertainty.builder()
                            .positionEnuCov(EntityManagerTMat3.builder()
                                .mxx(25f)
                                .myy(25f)
                                .mzz(100f)
                                .build())
                            .build())
                        .relationships(Relationships.builder()
                            .relationships(List.of(
                                Relationship.builder()
                                    .relatedEntityId(sensorEntityId)
                                    .relationshipId(relationshipId)
                                    .relationshipType(RelationshipType.builder()
                                        .trackedBy(TrackedBy.builder()
                                            .lastMeasurementTimestamp(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                            // Echo the subset of the tracking entity's sensors
                                            // that produced this detection. Each entry's sensor_id
                                            // and sensor_type must match the corresponding entry
                                            // on the tracking entity's top-level `sensors` component.
                                            .activelyTrackingSensors(Sensors.builder()
                                                .sensors(List.of(
                                                    Sensor.builder()
                                                        .sensorId("camera-01-eo")
                                                        .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                                        .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                                        .build()
                                                ))
                                                .build())
                                            .build())
                                        .build())
                                    .build()
                            ))
                            .build())
                        .provenance(Provenance.builder()
                            // integrationName + dataType must be unique for your
                            // track feed so Lattice can distinguish it from other sources.
                            .integrationName("your_integration_name")
                            .dataType("camera_lob")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing track");

                    // Republish at least every 10 seconds to satisfy Lattice's
                    // source_update_time cadence requirement.
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    Thread.sleep(10000);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={38} maxLines={81}
from anduril import Lattice, \
    Aliases, MilView, Ontology, Provenance, \
    Tracked, LineOfBearing, AngleOfArrival, Pose, Lla, Quaternion, TMat2, \
    LocationUncertainty, EntityManagerTMat3, \
    Relationships, Relationship, RelationshipType, TrackedBy, Sensors, Sensor
from datetime import datetime, timezone, timedelta
import asyncio
import os
import sys
from uuid import uuid4

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
# entity) when running against a live environment.
sensor_entity_id = "<SENSOR_ENTITY_ID>"

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing required environment variables.")
    sys.exit(1)

client = Lattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)
track_id = str(uuid4())
relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"
async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        while(True):
            latest_timestamp = datetime.now(timezone.utc)
            client.entities.publish_entity(
                entity_id=track_id,
                description="Bearing-only detection from a camera sensor",
                aliases=Aliases(name=f"Track-{track_id[:8]}"),
                is_live=True,
                created_time=creation_time,
                expiry_time=latest_timestamp + timedelta(seconds=10),
                ontology=Ontology(template="TEMPLATE_SIGNAL_OF_INTEREST"),
                mil_view=MilView(
                    disposition="DISPOSITION_UNKNOWN",
                    environment="ENVIRONMENT_SURFACE",
                ),
                tracked=Tracked(
                    # 2D bearing-only tracks populate line_of_bearing on the
                    # tracked component. Lattice needs bearing/elevation covariance
                    # to evaluate whether the LOB is fusable into the COP.
                    line_of_bearing=LineOfBearing(
                        angle_of_arrival=AngleOfArrival(
                            relative_pose=Pose(
                                pos=Lla(
                                    lat=36.66633492530301,
                                    lon=-116.9117674522639,
                                    alt=780.0,
                                ),
                                # Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                att_enu=Quaternion(x=0.0, y=0.0, z=0.0, w=1.0),
                            ),
                            bearing_elevation_covariance_rad2=TMat2(
                                mxx=0.0009,
                                mxy=0.0,
                                myy=0.0025,
                            ),
                        ),
                    ),
                ),
                # position_enu_cov is required for the track to be eligible
                # for fusion. A diagonal-only matrix is valid when cross-terms
                # are unknown.
                location_uncertainty=LocationUncertainty(
                    position_enu_cov=EntityManagerTMat3(
                        mxx=25.0,
                        myy=25.0,
                        mzz=100.0,
                    ),
                ),
                relationships=Relationships(
                    relationships=[
                        Relationship(
                            related_entity_id=sensor_entity_id,
                            relationship_id=relationship_id,
                            relationship_type=RelationshipType(
                                tracked_by=TrackedBy(
                                    last_measurement_timestamp=latest_timestamp,
                                    # Echo the subset of the tracking
                                    # entity's sensors that produced this
                                    # detection. Each entry's sensor_id and
                                    # sensor_type must match the corresponding
                                    # entry on the tracking entity's
                                    # top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="camera-01-eo",
                                                sensor_type="SENSOR_TYPE_CAMERA",
                                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ],
                ),
                provenance=Provenance(
                    # integration_name + data_type must be unique for your
                    # track feed so Lattice can distinguish it from other sources.
                    integration_name="your_integration_name",
                    data_type="camera_lob",
                    source_update_time=latest_timestamp,
                ),
            )
            # Republish at least every 10 seconds to satisfy Lattice's
            # source_update_time cadence requirement.
            await asyncio.sleep(1)

    except asyncio.CancelledError:
        print(">>>Exiting...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={33} maxLines={79}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v4 as uuidv4 } from 'uuid';

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
    }
);

// Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
// entity) when running against a live environment.
const sensorEntityId = "<SENSOR_ENTITY_ID>";
const trackId = uuidv4();
const relationshipId = `${trackId}-tracked-by-${sensorEntityId}`;
const createdTime = new Date();

async function App() {
    try {
        const latestTimestamp = new Date();
        await client.entities.publishEntity(
            {
                entityId: trackId,
                description: "Bearing-only detection from a camera sensor",
                aliases: { name: `Track-${trackId.substring(0, 8)}` },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + 10 * 1000).toISOString(),
                ontology: {
                    template: "TEMPLATE_SIGNAL_OF_INTEREST"
                },
                milView: {
                    disposition: "DISPOSITION_UNKNOWN",
                    environment: "ENVIRONMENT_SURFACE"
                },
                // 2D bearing-only tracks populate lineOfBearing on the
                // tracked component. Lattice needs bearing/elevation covariance
                // to evaluate whether the LOB is fusable into the COP.
                tracked: {
                    lineOfBearing: {
                        angleOfArrival: {
                            relativePose: {
                                pos: {
                                    lat: 36.66633492530301,
                                    lon: -116.9117674522639,
                                    alt: 780.0
                                },
                                // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                attEnu: { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }
                            },
                            bearingElevationCovarianceRad2: {
                                mxx: 0.0009,
                                mxy: 0.0,
                                myy: 0.0025
                            }
                        }
                    }
                },
                // position_enu_cov is required for the track to be eligible
                // for fusion. A diagonal-only matrix is valid when cross-terms
                // are unknown.
                locationUncertainty: {
                    positionEnuCov: { mxx: 25.0, myy: 25.0, mzz: 100.0 }
                },
                relationships: {
                    relationships: [
                        {
                            relatedEntityId: sensorEntityId,
                            relationshipId: relationshipId,
                            relationshipType: {
                                trackedBy: {
                                    lastMeasurementTimestamp: latestTimestamp.toISOString(),
                                    // Echo the subset of the tracking entity's sensors
                                    // that produced this detection. Each entry's sensor_id
                                    // and sensor_type must match the corresponding entry
                                    // on the tracking entity's top-level `sensors` component.
                                    activelyTrackingSensors: {
                                        sensors: [
                                            {
                                                sensorId: "camera-01-eo",
                                                sensorType: "SENSOR_TYPE_CAMERA",
                                                operationalState: "OPERATIONAL_STATE_OPERATIONAL"
                                            }
                                        ]
                                    }
                                }
                            }
                        }
                    ]
                },
                provenance: {
                    // integrationName + dataType must be unique for your
                    // track feed so Lattice can distinguish it from other sources.
                    integrationName: "your_integration_name",
                    dataType: "camera_lob",
                    sourceUpdateTime: latestTimestamp.toISOString()
                }
            }
        );
        console.log(`Publishing track.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
})();

```

```rs title={"Rust (REST)"} startLine={47} maxLines={106}
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::time::Duration;
use uuid::Uuid;

// Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
// entity) when running against a live environment.
const SENSOR_ENTITY_ID: &str = "<SENSOR_ENTITY_ID>";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, SENSOR_ENTITY_ID);

    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        let entity = Entity {
            entity_id: Some(track_id.clone()),
            description: Some("Bearing-only detection from a camera sensor".to_string()),
            aliases: Some(Aliases {
                name: Some(format!("Track-{}", &track_id[..8])),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::seconds(10)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateSignalOfInterest),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionUnknown),
                environment: Some(MilViewEnvironment::EnvironmentSurface),
                ..Default::default()
            }),
            // 2D bearing-only tracks populate line_of_bearing on the tracked
            // component. Lattice needs bearing/elevation covariance to evaluate
            // whether the LOB is fusable into the COP.
            tracked: Some(Tracked {
                line_of_bearing: Some(LineOfBearing {
                    angle_of_arrival: Some(AngleOfArrival {
                        relative_pose: Some(Pose {
                            pos: Some(Lla {
                                lat: Some(36.66633492530301),
                                lon: Some(-116.9117674522639),
                                alt: Some(780.0),
                                ..Default::default()
                            }),
                            // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                            att_enu: Some(Quaternion {
                                x: Some(0.0),
                                y: Some(0.0),
                                z: Some(0.0),
                                w: Some(1.0),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        bearing_elevation_covariance_rad2: Some(TMat2 {
                            mxx: Some(0.0009),
                            mxy: Some(0.0),
                            myy: Some(0.0025),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            // position_enu_cov is required for the track to be eligible for
            // fusion. A diagonal-only matrix is valid when cross-terms are
            // unknown.
            location_uncertainty: Some(LocationUncertainty {
                position_enu_cov: Some(EntityManagerTMat3 {
                    mxx: Some(25.0),
                    myy: Some(25.0),
                    mzz: Some(100.0),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: Some(vec![Relationship {
                    related_entity_id: Some(SENSOR_ENTITY_ID.to_string()),
                    relationship_id: Some(relationship_id.clone()),
                    relationship_type: Some(RelationshipType {
                        tracked_by: Some(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp),
                            actively_tracking_sensors: Some(Sensors {
                                sensors: Some(vec![Sensor {
                                    sensor_id: Some("camera-01-eo".to_string()),
                                    sensor_type: Some(SensorSensorType::SensorTypeCamera),
                                    operational_state: Some(
                                        SensorOperationalState::OperationalStateOperational,
                                    ),
                                    ..Default::default()
                                }]),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }),
                    ..Default::default()
                }]),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                // integration_name + data_type must be unique for your track
                // feed so Lattice can distinguish it from other sources.
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("camera_lob".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            ..Default::default()
        };

        if let Err(e) = client.entities.publish_entity(&entity, None).await {
            eprintln!("Exception: {}", e);
        }

        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={75} maxLines={98}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Get environment variables
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
	// entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Setup authentication
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	// Setup gRPC connection options
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}

	// Create gRPC connection
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	// Create EntityManager client
	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()
	creationTimestamp := timestamppb.New(creationTime)

	// Continuously publish the entity
	for {
		// Get current timestamp for this update
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    trackId,
			Description: "Bearing-only detection from a camera sensor",
			Aliases: &entitymanagerv1.Aliases{
				Name: fmt.Sprintf("Track-%s", trackId[:8]),
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(10 * time.Second)),
			Ontology: &entitymanagerv1.Ontology{
				Template: entitymanagerv1.Template_TEMPLATE_SIGNAL_OF_INTEREST,
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_UNKNOWN,
				Environment: ontologyv1.Environment_ENVIRONMENT_SURFACE,
			},
			// 2D bearing-only tracks populate line_of_bearing on the
			// tracked component. Lattice needs bearing/elevation covariance
			// to evaluate whether the LOB is fusable into the COP.
			Tracked: &entitymanagerv1.Tracked{
				LineOfBearing: &entitymanagerv1.LineOfBearing{
					AngleOfArrival: &entitymanagerv1.AngleOfArrival{
						RelativePose: &_type.Pose{
							Pos: &_type.LLA{
								Lat: 36.66633492530301,
								Lon: -116.9117674522639,
								Alt: 780.0,
							},
							// Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
							AttEnu: &_type.Quaternion{
								X: 0.0,
								Y: 0.0,
								Z: 0.0,
								W: 1.0,
							},
						},
						BearingElevationCovarianceRad2: &_type.TMat2{
							Mxx: 0.0009,
							Mxy: 0.0,
							Myy: 0.0025,
						},
					},
				},
			},
			// position_enu_cov is required for the track to be eligible for
			// fusion. A diagonal-only matrix is valid when cross-terms are
			// unknown.
			LocationUncertainty: &entitymanagerv1.LocationUncertainty{
				PositionEnuCov: &entitymanagerv1.TMat3{
					Mxx: 25.0,
					Myy: 25.0,
					Mzz: 100.0,
				},
			},
			Relationships: &entitymanagerv1.Relationships{
				Relationships: []*entitymanagerv1.Relationship{
					{
						RelatedEntityId: sensorEntityId,
						RelationshipId:  relationshipId,
						RelationshipType: &entitymanagerv1.RelationshipType{
							Type: &entitymanagerv1.RelationshipType_TrackedBy{
								TrackedBy: &entitymanagerv1.TrackedBy{
									LastMeasurementTimestamp: timestamppb.New(latestTimestamp),
									// Echo the subset of the tracking entity's sensors
									// that produced this detection. Each entry's sensor_id
									// and sensor_type must match the corresponding entry
									// on the tracking entity's top-level `sensors` component.
									ActivelyTrackingSensors: &entitymanagerv1.Sensors{
										Sensors: []*entitymanagerv1.Sensor{
											{
												SensorId:         "camera-01-eo",
												SensorType:       entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
												OperationalState: entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
											},
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				// integration_name + data_type must be unique for your
				// track feed so Lattice can distinguish it from other sources.
				IntegrationName:  "your_integration_name",
				DataType:         "camera_lob",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
		}

		// Create publish request
		request := &entitymanagerv1.PublishEntityRequest{
			Entity: entity,
		}

		// Publish the entity
		_, err := client.PublishEntity(ctx, request)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing track with entity ID: %s\n", trackId)
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={67} maxLines={77}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf import Oneof
from protobuf.wkt import Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance, Tracked
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import LocationUncertainty, TMat3
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.relationship_pub_pb import (
    Relationship,
    Relationships,
    RelationshipType,
    TrackedBy,
)
from anduril.entitymanager.v1.sensors_pub_pb import (
    OperationalState,
    Sensor,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.signal_pub_pb import AngleOfArrival, LineOfBearing
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.type.coords_pub_pb import LLA, Pose, Quaternion, TMat2


def to_timestamp(dt: datetime) -> Timestamp:
    return Timestamp.from_datetime(dt)


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
    # entity) when running against a live environment.
    sensor_entity_id = "<SENSOR_ENTITY_ID>"

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    track_id = str(uuid.uuid4())
    relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"

    creation_timestamp = to_timestamp(datetime.now(timezone.utc))

    while True:
        latest = datetime.now(timezone.utc)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + timedelta(seconds=10))

        entity = Entity(
            entity_id=track_id,
            description="Bearing-only detection from a camera sensor",
            aliases=Aliases(name=f"Track-{track_id[:8]}"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.SIGNAL_OF_INTEREST),
            mil_view=MilView(
                disposition=Disposition.UNKNOWN,
                environment=Environment.SURFACE,
            ),
            # 2D bearing-only tracks populate line_of_bearing on the
            # tracked component. Lattice needs bearing/elevation covariance
            # to evaluate whether the LOB is fusable into the COP.
            tracked=Tracked(
                line_of_bearing=LineOfBearing(
                    angle_of_arrival=AngleOfArrival(
                        relative_pose=Pose(
                            pos=LLA(lat=36.66633492530301, lon=-116.9117674522639, alt=780.0),
                            # Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                            att_enu=Quaternion(x=0.0, y=0.0, z=0.0, w=1.0),
                        ),
                        bearing_elevation_covariance_rad2=TMat2(
                            mxx=0.0009,
                            mxy=0.0,
                            myy=0.0025,
                        ),
                    ),
                ),
            ),
            # position_enu_cov is required for the track to be eligible for
            # fusion. A diagonal-only matrix is valid when cross-terms are
            # unknown.
            location_uncertainty=LocationUncertainty(
                position_enu_cov=TMat3(mxx=25.0, myy=25.0, mzz=100.0),
            ),
            relationships=Relationships(
                relationships=[
                    Relationship(
                        related_entity_id=sensor_entity_id,
                        relationship_id=relationship_id,
                        relationship_type=RelationshipType(
                            type=Oneof(
                                "tracked_by",
                                TrackedBy(
                                    last_measurement_timestamp=latest_ts,
                                    # Echo the subset of the tracking entity's sensors
                                    # that produced this detection. Each entry's sensor_id
                                    # and sensor_type must match the corresponding entry
                                    # on the tracking entity's top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="camera-01-eo",
                                                sensor_type=SensorType.CAMERA,
                                                operational_state=OperationalState.OPERATIONAL,
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ),
                ],
            ),
            provenance=Provenance(
                # integration_name + data_type must be unique for your
                # track feed so Lattice can distinguish it from other sources.
                integration_name="your_integration_name",
                data_type="camera_lob",
                source_update_time=latest_ts,
            ),
        )

        try:
            client.publish_entity(PublishEntityRequest(entity=entity))
            print(f"Publishing track with entity ID: {track_id}")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        # Republish at least every 10 seconds to satisfy Lattice's
        # source_update_time cadence requirement.
        time.sleep(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={92} maxLines={101}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    relationship_type, Aliases, AngleOfArrival, Entity, LineOfBearing, LocationUncertainty, MilView,
    Ontology, OperationalState, Provenance, PublishEntityRequest, Relationship, RelationshipType,
    Relationships, Sensor, SensorType, Sensors, TMat3, Template, Tracked, TrackedBy,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::{Lla, Pose, Quaternion, TMat2};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;
use uuid::Uuid;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn add_seconds(ts: &Timestamp, seconds: i64) -> Timestamp {
    Timestamp {
        seconds: ts.seconds + seconds,
        nanos: ts.nanos,
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
    // entity) when running against a live environment.
    let sensor_entity_id = "<SENSOR_ENTITY_ID>".to_string();

    // Setup authentication
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, sensor_entity_id);
    let creation_timestamp = now_timestamp();

    // Continuously publish the entity
    loop {
        let latest_timestamp = now_timestamp();

        // 2D bearing-only tracks populate line_of_bearing on the tracked
        // component. Lattice needs bearing/elevation covariance to evaluate
        // whether the LOB is fusable into the COP.
        let entity = Entity {
            entity_id: track_id.clone(),
            description: "Bearing-only detection from a camera sensor".to_string(),
            aliases: Some(Aliases {
                name: format!("Track-{}", &track_id[..8]),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            expiry_time: Some(add_seconds(&latest_timestamp, 10)),
            ontology: Some(Ontology {
                template: Template::SignalOfInterest as i32,
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Unknown as i32,
                environment: Environment::Surface as i32,
                ..Default::default()
            }),
            tracked: Some(Tracked {
                line_of_bearing: Some(LineOfBearing {
                    angle_of_arrival: Some(AngleOfArrival {
                        relative_pose: Some(Pose {
                            pos: Some(Lla {
                                lat: 36.66633492530301,
                                lon: -116.9117674522639,
                                alt: 780.0,
                                ..Default::default()
                            }),
                            // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                            att_enu: Some(Quaternion {
                                x: 0.0,
                                y: 0.0,
                                z: 0.0,
                                w: 1.0,
                            }),
                            ..Default::default()
                        }),
                        bearing_elevation_covariance_rad2: Some(TMat2 {
                            mxx: 0.0009,
                            mxy: 0.0,
                            myy: 0.0025,
                        }),
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            // position_enu_cov is required for the track to be eligible for
            // fusion. A diagonal-only matrix is valid when cross-terms are
            // unknown.
            location_uncertainty: Some(LocationUncertainty {
                position_enu_cov: Some(TMat3 {
                    mxx: 25.0,
                    myy: 25.0,
                    mzz: 100.0,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: vec![Relationship {
                    related_entity_id: sensor_entity_id.clone(),
                    relationship_id: relationship_id.clone(),
                    relationship_type: Some(RelationshipType {
                        r#type: Some(relationship_type::Type::TrackedBy(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp.clone()),
                            // Echo the subset of the tracking entity's sensors
                            // that produced this detection. Each entry's sensor_id
                            // and sensor_type must match the corresponding entry
                            // on the tracking entity's top-level `sensors` component.
                            actively_tracking_sensors: Some(Sensors {
                                sensors: vec![Sensor {
                                    sensor_id: "camera-01-eo".to_string(),
                                    sensor_type: SensorType::Camera as i32,
                                    operational_state: OperationalState::Operational as i32,
                                    ..Default::default()
                                }],
                            }),
                        })),
                    }),
                }],
            }),
            provenance: Some(Provenance {
                // integration_name + data_type must be unique for your
                // track feed so Lattice can distinguish it from other sources.
                integration_name: "your_integration_name".to_string(),
                data_type: "camera_lob".to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            ..Default::default()
        };

        let request = Request::new(PublishEntityRequest {
            entity: Some(entity),
        });
        match client.publish_entity(request).await {
            Ok(_) => println!("Publishing track with entity ID: {}", track_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

## Publish a 3D track

Use a 3D track when your sensor can place the target in three-dimensional space. Choose the
variant that matches the measurement your sensor produces.

#### RF signal with line-of-bearing

Use this approach for a signal-of-interest track that has a bearing and an estimated range to
the emitter, such as a track produced by an RF direction-finding sensor. Set the bearing and range
in the
[`signal`](/reference/rest/entities/publish-entity#request.body.signal) component rather than
the `tracked` component.

Define the entity model's required components. To represent an RF track with bearing
and range:

* Set `template` to `TEMPLATE_SIGNAL_OF_INTEREST`.
* Populate `signal.lineOfBearing.angleOfArrival` with the sensor's pose.
* Populate `signal.lineOfBearing.rangeEstimateM` with the estimated distance and
  one-sigma uncertainty.

**`entity.json`**

```json maxLines=30 title="entity.json"
{
  "entityId": "UNIQUE_ENTITY_ID",
  "description": "RF emitter detection with estimated range",
  "isLive": true,
  "createdTime": "2026-05-01T00:00:00.000Z",
  "expiryTime": "2026-05-01T00:00:10.000Z",
  "aliases": { "name": "SOI-12345678" },
  "ontology": { "template": "TEMPLATE_SIGNAL_OF_INTEREST" },
  "milView": {
    "disposition": "DISPOSITION_UNKNOWN",
    "environment": "ENVIRONMENT_AIR"
  },
  "signal": {
    "lineOfBearing": {
      "angleOfArrival": {
        "relativePose": {
          "pos": { "lat": 50.91402185768586, "lon": 0.79203612077257, "alt": 300.0 },
          "attEnu": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 }
        },
        "bearingElevationCovarianceRad2": { "mxx": 0.0004, "mxy": 0.0, "myy": 0.0009 }
      },
      "rangeEstimateM": { "value": 12500.0, "sigma": 750.0 }
    }
  },
  "locationUncertainty": {
    "positionEnuCov": { "mxx": 400.0, "myy": 400.0, "mzz": 1600.0 }
  },
  "relationships": {
    "relationships": [{
      "relatedEntityId": "SENSOR_ENTITY_ID",
      "relationshipId": "UNIQUE_ENTITY_ID-tracked-by-SENSOR_ENTITY_ID",
      "relationshipType": {
        "trackedBy": {
          "lastMeasurementTimestamp": "2026-05-01T00:00:00.000Z",
          "activelyTrackingSensors": {
            "sensors": [{
              "sensorId": "rf-1",
              "sensorType": "SENSOR_TYPE_RF",
              "operationalState": "OPERATIONAL_STATE_OPERATIONAL"
            }]
          }
        }
      }
    }]
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "rf_sigint",
    "sourceUpdateTime": "2026-05-01T00:00:00.000Z"
  }
}
```

Take a closer look at the `signal` component and its range estimate:

**`signal`**

```json title="signal"
"signal": {
  "lineOfBearing": {
    "angleOfArrival": {
      "relativePose": {
        // Sensor position and attitude at the time of the measurement.
        "pos": { "lat": 50.91402185768586, "lon": 0.79203612077257, "alt": 300.0 },
        "attEnu": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 }
      },
      "bearingElevationCovarianceRad2": { "mxx": 0.0004, "mxy": 0.0, "myy": 0.0009 }
    },
    // Estimated distance from the sensor to the emitter.
    // Populate sigma with the one-sigma uncertainty.
    "rangeEstimateM": { "value": 12500.0, "sigma": 750.0 }
  }
}
```

Use the [`PublishEntity`](/reference/rest/entities/publish-entity) API method to publish
the entity:

```go title={"Go (REST)"} startLine={58} maxLines={94}
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
	"github.com/google/uuid"
)

func main() {
	// Get environment variables
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")

	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the RF sensor (published as a
	// TEMPLATE_ASSET entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Initialize headers for sandbox authorization
	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	// Create the client
	LatticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()

	// Continuously publish the entity
	for {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &trackId,
			Description: Lattice.String("RF emitter detection with estimated range"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String(fmt.Sprintf("SOI-%s", trackId[:8])),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(10 * time.Second)),
			Ontology: &Lattice.Ontology{
				Template: Lattice.OntologyTemplateTemplateSignalOfInterest.Ptr(),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionUnknown.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
			},
			// 3D SIGINT tracks with a bearing and a range estimate
			// populate line_of_bearing on the signal component.
			Signal: &Lattice.Signal{
				LineOfBearing: &Lattice.LineOfBearing{
					AngleOfArrival: &Lattice.AngleOfArrival{
						RelativePose: &Lattice.Pose{
							Pos: &Lattice.Lla{
								Lat: Lattice.Float64(50.91402185768586),
								Lon: Lattice.Float64(0.79203612077257),
								Alt: Lattice.Float64(300.0),
							},
							// Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
							AttEnu: &Lattice.Quaternion{
								X: Lattice.Float64(0.0),
								Y: Lattice.Float64(0.0),
								Z: Lattice.Float64(0.0),
								W: Lattice.Float64(1.0),
							},
						},
						BearingElevationCovarianceRad2: &Lattice.TMat2{
							Mxx: Lattice.Float64(0.0004),
							Mxy: Lattice.Float64(0.0),
							Myy: Lattice.Float64(0.0009),
						},
					},
					// Estimated distance from the sensor to the emitter,
					// with a one-sigma uncertainty in meters.
					RangeEstimateM: &Lattice.Measurement{
						Value: Lattice.Float64(12500.0),
						Sigma: Lattice.Float64(750.0),
					},
				},
			},
			// position_enu_cov is required for the track to be eligible for
			// fusion. A diagonal-only matrix is valid when cross-terms are
			// unknown.
			LocationUncertainty: &Lattice.LocationUncertainty{
				PositionEnuCov: &Lattice.EntityManagerTMat3{
					Mxx: Lattice.Float64(400.0),
					Myy: Lattice.Float64(400.0),
					Mzz: Lattice.Float64(1600.0),
				},
			},
			Relationships: &Lattice.Relationships{
				Relationships: []*Lattice.Relationship{
					{
						RelatedEntityID: Lattice.String(sensorEntityId),
						RelationshipID:  Lattice.String(relationshipId),
						RelationshipType: &Lattice.RelationshipType{
							TrackedBy: &Lattice.TrackedBy{
								LastMeasurementTimestamp: Lattice.Time(latestTimestamp),
								// Echo the subset of the tracking entity's sensors
								// that produced this detection. Each entry's sensor_id
								// and sensor_type must match the corresponding entry
								// on the tracking entity's top-level `sensors` component.
								ActivelyTrackingSensors: &Lattice.Sensors{
									Sensors: []*Lattice.Sensor{
										{
											SensorID:         Lattice.String("rf-1"),
											SensorType:       Lattice.SensorSensorTypeSensorTypeRf.Ptr(),
											OperationalState: Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("rf_sigint"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Println("Publishing track")
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```java title={"Java (REST)"} startLine={78} maxLines={94}
package org.example;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Aliases;
import com.anduril.types.AngleOfArrival;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerTMat3;
import com.anduril.types.LineOfBearing;
import com.anduril.types.Lla;
import com.anduril.types.LocationUncertainty;
import com.anduril.types.Measurement;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Pose;
import com.anduril.types.Provenance;
import com.anduril.types.Quaternion;
import com.anduril.types.Relationship;
import com.anduril.types.RelationshipType;
import com.anduril.types.Relationships;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.Signal;
import com.anduril.types.TMat2;
import com.anduril.types.TrackedBy;

public class PublishTrack3dSigint {
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables and ensure URL has https://
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Create Lattice client with Sandbox authentication
        Lattice client = Lattice.builder()
            .url(endpoint)
            .token(environmentToken)
            .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
            .build();

        // Replace with the real entity ID of the RF sensor (published as a
        // TEMPLATE_ASSET entity) when running against a live environment.
        String sensorEntityId = "<SENSOR_ENTITY_ID>";

        try {
            // Generate a unique ID for the entity
            String trackId = UUID.randomUUID().toString();
            String relationshipId = trackId + "-tracked-by-" + sensorEntityId;

            // Get creation time
            Instant creationTime = Instant.now();

            // Continuously publish the entity
            while (true) {
                try {
                    // Get current timestamp
                    Instant latestTimestamp = Instant.now();

                    // Create the entity
                    Entity entity = Entity.builder()
                        .entityId(trackId)
                        .description("RF emitter detection with estimated range")
                        .aliases(Aliases.builder()
                            .name("SOI-" + trackId.substring(0, 8))
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(10, ChronoUnit.SECONDS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_SIGNAL_OF_INTEREST)
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_UNKNOWN)
                            .environment(MilViewEnvironment.ENVIRONMENT_AIR)
                            .build())
                        // 3D SIGINT tracks with a bearing and a range estimate
                        // populate lineOfBearing on the signal component.
                        .signal(Signal.builder()
                            .lineOfBearing(LineOfBearing.builder()
                                .angleOfArrival(AngleOfArrival.builder()
                                    .relativePose(Pose.builder()
                                        .pos(Lla.builder()
                                            .lat(50.91402185768586)
                                            .lon(0.79203612077257)
                                            .alt(300.0)
                                            .build())
                                        // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                        .attEnu(Quaternion.builder()
                                            .x(0.0)
                                            .y(0.0)
                                            .z(0.0)
                                            .w(1.0)
                                            .build())
                                        .build())
                                    .bearingElevationCovarianceRad2(TMat2.builder()
                                        .mxx(0.0004)
                                        .mxy(0.0)
                                        .myy(0.0009)
                                        .build())
                                    .build())
                                // Estimated distance from the sensor to the emitter,
                                // with a one-sigma uncertainty in meters.
                                .rangeEstimateM(Measurement.builder()
                                    .value(12500.0)
                                    .sigma(750.0)
                                    .build())
                                .build())
                            .build())
                        // position_enu_cov is required for the track to be
                        // eligible for fusion. A diagonal-only matrix is valid
                        // when cross-terms are unknown.
                        .locationUncertainty(LocationUncertainty.builder()
                            .positionEnuCov(EntityManagerTMat3.builder()
                                .mxx(400f)
                                .myy(400f)
                                .mzz(1600f)
                                .build())
                            .build())
                        .relationships(Relationships.builder()
                            .relationships(List.of(
                                Relationship.builder()
                                    .relatedEntityId(sensorEntityId)
                                    .relationshipId(relationshipId)
                                    .relationshipType(RelationshipType.builder()
                                        .trackedBy(TrackedBy.builder()
                                            .lastMeasurementTimestamp(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                            // Echo the subset of the tracking entity's sensors
                                            // that produced this detection. Each entry's sensor_id
                                            // and sensor_type must match the corresponding entry
                                            // on the tracking entity's top-level `sensors` component.
                                            .activelyTrackingSensors(Sensors.builder()
                                                .sensors(List.of(
                                                    Sensor.builder()
                                                        .sensorId("rf-1")
                                                        .sensorType(SensorSensorType.SENSOR_TYPE_RF)
                                                        .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                                        .build()
                                                ))
                                                .build())
                                            .build())
                                        .build())
                                    .build()
                            ))
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("rf_sigint")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing track");

                    // Republish at least every 10 seconds to satisfy Lattice's
                    // source_update_time cadence requirement.
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    Thread.sleep(10000);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={38} maxLines={84}
from anduril import Lattice, \
    Aliases, MilView, Ontology, Provenance, \
    Signal, LineOfBearing, AngleOfArrival, Pose, Lla, Quaternion, Measurement, TMat2, \
    LocationUncertainty, EntityManagerTMat3, \
    Relationships, Relationship, RelationshipType, TrackedBy, Sensors, Sensor
from datetime import datetime, timezone, timedelta
import asyncio
import os
import sys
from uuid import uuid4

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Replace with the real entity ID of the RF sensor (published as a
# TEMPLATE_ASSET entity) when running against a live environment.
sensor_entity_id = "<SENSOR_ENTITY_ID>"

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing required environment variables.")
    sys.exit(1)

client = Lattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)
track_id = str(uuid4())
relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"
async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        while(True):
            latest_timestamp = datetime.now(timezone.utc)
            client.entities.publish_entity(
                entity_id=track_id,
                description="RF emitter detection with estimated range",
                aliases=Aliases(name=f"SOI-{track_id[:8]}"),
                is_live=True,
                created_time=creation_time,
                expiry_time=latest_timestamp + timedelta(seconds=10),
                ontology=Ontology(template="TEMPLATE_SIGNAL_OF_INTEREST"),
                mil_view=MilView(
                    disposition="DISPOSITION_UNKNOWN",
                    environment="ENVIRONMENT_AIR",
                ),
                signal=Signal(
                    # 3D SIGINT tracks with a bearing and a range estimate
                    # populate line_of_bearing on the signal component.
                    line_of_bearing=LineOfBearing(
                        angle_of_arrival=AngleOfArrival(
                            relative_pose=Pose(
                                pos=Lla(
                                    lat=50.91402185768586,
                                    lon=0.79203612077257,
                                    alt=300.0,
                                ),
                                # Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                att_enu=Quaternion(x=0.0, y=0.0, z=0.0, w=1.0),
                            ),
                            bearing_elevation_covariance_rad2=TMat2(
                                mxx=0.0004,
                                mxy=0.0,
                                myy=0.0009,
                            ),
                        ),
                        # Estimated distance from the sensor to the emitter,
                        # with a one-sigma uncertainty in meters.
                        range_estimate_m=Measurement(
                            value=12500.0,
                            sigma=750.0,
                        ),
                    ),
                ),
                # position_enu_cov is required for the track to be eligible
                # for fusion. A diagonal-only matrix is valid when cross-terms
                # are unknown.
                location_uncertainty=LocationUncertainty(
                    position_enu_cov=EntityManagerTMat3(
                        mxx=400.0,
                        myy=400.0,
                        mzz=1600.0,
                    ),
                ),
                relationships=Relationships(
                    relationships=[
                        Relationship(
                            related_entity_id=sensor_entity_id,
                            relationship_id=relationship_id,
                            relationship_type=RelationshipType(
                                tracked_by=TrackedBy(
                                    last_measurement_timestamp=latest_timestamp,
                                    # Echo the subset of the tracking
                                    # entity's sensors that produced this
                                    # detection. Each entry's sensor_id and
                                    # sensor_type must match the corresponding
                                    # entry on the tracking entity's
                                    # top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="rf-1",
                                                sensor_type="SENSOR_TYPE_RF",
                                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ],
                ),
                provenance=Provenance(
                    integration_name="your_integration_name",
                    data_type="rf_sigint",
                    source_update_time=latest_timestamp,
                ),
            )
            await asyncio.sleep(1)

    except asyncio.CancelledError:
        print(">>>Exiting...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())
    
```

```ts title={"TypeScript (REST)"} startLine={33} maxLines={82}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v4 as uuidv4 } from 'uuid';

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
    }
);

// Replace with the real entity ID of the RF sensor (published as a
// TEMPLATE_ASSET entity) when running against a live environment.
const sensorEntityId = "<SENSOR_ENTITY_ID>";
const trackId = uuidv4();
const relationshipId = `${trackId}-tracked-by-${sensorEntityId}`;
const createdTime = new Date();

async function App() {
    try {
        const latestTimestamp = new Date();
        await client.entities.publishEntity(
            {
                entityId: trackId,
                description: "RF emitter detection with estimated range",
                aliases: { name: `SOI-${trackId.substring(0, 8)}` },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + 10 * 1000).toISOString(),
                ontology: {
                    template: "TEMPLATE_SIGNAL_OF_INTEREST"
                },
                milView: {
                    disposition: "DISPOSITION_UNKNOWN",
                    environment: "ENVIRONMENT_AIR"
                },
                // 3D SIGINT tracks with a bearing and a range estimate
                // populate lineOfBearing on the signal component.
                signal: {
                    lineOfBearing: {
                        angleOfArrival: {
                            relativePose: {
                                pos: {
                                    lat: 50.91402185768586,
                                    lon: 0.79203612077257,
                                    alt: 300.0
                                },
                                // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                attEnu: { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }
                            },
                            bearingElevationCovarianceRad2: {
                                mxx: 0.0004,
                                mxy: 0.0,
                                myy: 0.0009
                            }
                        },
                        // Estimated distance from the sensor to the emitter,
                        // with a one-sigma uncertainty in meters.
                        rangeEstimateM: {
                            value: 12500.0,
                            sigma: 750.0
                        }
                    }
                },
                // position_enu_cov is required for the track to be eligible
                // for fusion. A diagonal-only matrix is valid when cross-terms
                // are unknown.
                locationUncertainty: {
                    positionEnuCov: { mxx: 400.0, myy: 400.0, mzz: 1600.0 }
                },
                relationships: {
                    relationships: [
                        {
                            relatedEntityId: sensorEntityId,
                            relationshipId: relationshipId,
                            relationshipType: {
                                trackedBy: {
                                    lastMeasurementTimestamp: latestTimestamp.toISOString(),
                                    // Echo the subset of the tracking entity's sensors
                                    // that produced this detection. Each entry's sensor_id
                                    // and sensor_type must match the corresponding entry
                                    // on the tracking entity's top-level `sensors` component.
                                    activelyTrackingSensors: {
                                        sensors: [
                                            {
                                                sensorId: "rf-1",
                                                sensorType: "SENSOR_TYPE_RF",
                                                operationalState: "OPERATIONAL_STATE_OPERATIONAL"
                                            }
                                        ]
                                    }
                                }
                            }
                        }
                    ]
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "rf_sigint",
                    sourceUpdateTime: latestTimestamp.toISOString()
                }
            }
        );
        console.log(`Publishing track.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
})();

```

```rs title={"Rust (REST)"} startLine={47} maxLines={110}
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::time::Duration;
use uuid::Uuid;

// Replace with the real entity ID of the RF sensor (published as a
// TEMPLATE_ASSET entity) when running against a live environment.
const SENSOR_ENTITY_ID: &str = "<SENSOR_ENTITY_ID>";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, SENSOR_ENTITY_ID);

    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        let entity = Entity {
            entity_id: Some(track_id.clone()),
            description: Some("RF emitter detection with estimated range".to_string()),
            aliases: Some(Aliases {
                name: Some(format!("SOI-{}", &track_id[..8])),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::seconds(10)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateSignalOfInterest),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionUnknown),
                environment: Some(MilViewEnvironment::EnvironmentAir),
                ..Default::default()
            }),
            signal: Some(Signal {
                // 3D SIGINT tracks with a bearing and a range estimate populate
                // line_of_bearing on the signal component.
                line_of_bearing: Some(LineOfBearing {
                    angle_of_arrival: Some(AngleOfArrival {
                        relative_pose: Some(Pose {
                            pos: Some(Lla {
                                lat: Some(50.91402185768586),
                                lon: Some(0.79203612077257),
                                alt: Some(300.0),
                                ..Default::default()
                            }),
                            // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                            att_enu: Some(Quaternion {
                                x: Some(0.0),
                                y: Some(0.0),
                                z: Some(0.0),
                                w: Some(1.0),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        bearing_elevation_covariance_rad2: Some(TMat2 {
                            mxx: Some(0.0004),
                            mxy: Some(0.0),
                            myy: Some(0.0009),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }),
                    // Estimated distance from the sensor to the emitter, with a
                    // one-sigma uncertainty in meters.
                    range_estimate_m: Some(Measurement {
                        value: Some(12500.0),
                        sigma: Some(750.0),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            // position_enu_cov is required for the track to be eligible for
            // fusion. A diagonal-only matrix is valid when cross-terms are
            // unknown.
            location_uncertainty: Some(LocationUncertainty {
                position_enu_cov: Some(EntityManagerTMat3 {
                    mxx: Some(400.0),
                    myy: Some(400.0),
                    mzz: Some(1600.0),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: Some(vec![Relationship {
                    related_entity_id: Some(SENSOR_ENTITY_ID.to_string()),
                    relationship_id: Some(relationship_id.clone()),
                    relationship_type: Some(RelationshipType {
                        tracked_by: Some(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp),
                            actively_tracking_sensors: Some(Sensors {
                                sensors: Some(vec![Sensor {
                                    sensor_id: Some("rf-1".to_string()),
                                    sensor_type: Some(SensorSensorType::SensorTypeRf),
                                    operational_state: Some(
                                        SensorOperationalState::OperationalStateOperational,
                                    ),
                                    ..Default::default()
                                }]),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }),
                    ..Default::default()
                }]),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("rf_sigint".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            ..Default::default()
        };

        if let Err(e) = client.entities.publish_entity(&entity, None).await {
            eprintln!("Exception: {}", e);
        }

        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={76} maxLines={105}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// Get environment variables
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the RF sensor (published as a
	// TEMPLATE_ASSET entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Setup authentication
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	// Setup gRPC connection options
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}

	// Create gRPC connection
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	// Create EntityManager client
	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()
	creationTimestamp := timestamppb.New(creationTime)

	// Continuously publish the entity
	for {
		// Get current timestamp for this update
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    trackId,
			Description: "RF emitter detection with estimated range",
			Aliases: &entitymanagerv1.Aliases{
				Name: fmt.Sprintf("SOI-%s", trackId[:8]),
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(10 * time.Second)),
			Ontology: &entitymanagerv1.Ontology{
				Template: entitymanagerv1.Template_TEMPLATE_SIGNAL_OF_INTEREST,
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_UNKNOWN,
				Environment: ontologyv1.Environment_ENVIRONMENT_AIR,
			},
			// 3D SIGINT tracks with a bearing and a range estimate
			// populate line_of_bearing on the signal component.
			Signal: &entitymanagerv1.Signal{
				Report: &entitymanagerv1.Signal_LineOfBearing{
					LineOfBearing: &entitymanagerv1.LineOfBearing{
						AngleOfArrival: &entitymanagerv1.AngleOfArrival{
							RelativePose: &_type.Pose{
								Pos: &_type.LLA{
									Lat: 50.91402185768586,
									Lon: 0.79203612077257,
									Alt: 300.0,
								},
								// Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
								AttEnu: &_type.Quaternion{
									X: 0.0,
									Y: 0.0,
									Z: 0.0,
									W: 1.0,
								},
							},
							BearingElevationCovarianceRad2: &_type.TMat2{
								Mxx: 0.0004,
								Mxy: 0.0,
								Myy: 0.0009,
							},
						},
						// Estimated distance from the sensor to the emitter,
						// with a one-sigma uncertainty in meters.
						DetectionRange: &entitymanagerv1.LineOfBearing_RangeEstimateM{
							RangeEstimateM: &entitymanagerv1.Measurement{
								Value: wrapperspb.Double(12500.0),
								Sigma: wrapperspb.Double(750.0),
							},
						},
					},
				},
			},
			// position_enu_cov is required for the track to be eligible for
			// fusion. A diagonal-only matrix is valid when cross-terms are
			// unknown.
			LocationUncertainty: &entitymanagerv1.LocationUncertainty{
				PositionEnuCov: &entitymanagerv1.TMat3{
					Mxx: 400.0,
					Myy: 400.0,
					Mzz: 1600.0,
				},
			},
			Relationships: &entitymanagerv1.Relationships{
				Relationships: []*entitymanagerv1.Relationship{
					{
						RelatedEntityId: sensorEntityId,
						RelationshipId:  relationshipId,
						RelationshipType: &entitymanagerv1.RelationshipType{
							Type: &entitymanagerv1.RelationshipType_TrackedBy{
								TrackedBy: &entitymanagerv1.TrackedBy{
									LastMeasurementTimestamp: timestamppb.New(latestTimestamp),
									// Echo the subset of the tracking entity's sensors
									// that produced this detection. Each entry's sensor_id
									// and sensor_type must match the corresponding entry
									// on the tracking entity's top-level `sensors` component.
									ActivelyTrackingSensors: &entitymanagerv1.Sensors{
										Sensors: []*entitymanagerv1.Sensor{
											{
												SensorId:         "rf-1",
												SensorType:       entitymanagerv1.SensorType_SENSOR_TYPE_RF,
												OperationalState: entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
											},
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "rf_sigint",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
		}

		// Create publish request
		request := &entitymanagerv1.PublishEntityRequest{
			Entity: entity,
		}

		// Publish the entity
		_, err := client.PublishEntity(ctx, request)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing track with entity ID: %s\n", trackId)
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={72} maxLines={82}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf import Oneof
from protobuf.wkt import DoubleValue, Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import LocationUncertainty, TMat3
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.relationship_pub_pb import (
    Relationship,
    Relationships,
    RelationshipType,
    TrackedBy,
)
from anduril.entitymanager.v1.sensors_pub_pb import (
    OperationalState,
    Sensor,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.signal_pub_pb import (
    AngleOfArrival,
    LineOfBearing,
    Measurement,
    Signal,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.type.coords_pub_pb import LLA, Pose, Quaternion, TMat2


def to_timestamp(dt: datetime) -> Timestamp:
    return Timestamp.from_datetime(dt)


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Replace with the real entity ID of the RF sensor (published as a
    # TEMPLATE_ASSET entity) when running against a live environment.
    sensor_entity_id = "<SENSOR_ENTITY_ID>"

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    track_id = str(uuid.uuid4())
    relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"

    creation_timestamp = to_timestamp(datetime.now(timezone.utc))

    while True:
        latest = datetime.now(timezone.utc)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + timedelta(seconds=10))

        entity = Entity(
            entity_id=track_id,
            description="RF emitter detection with estimated range",
            aliases=Aliases(name=f"SOI-{track_id[:8]}"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.SIGNAL_OF_INTEREST),
            mil_view=MilView(
                disposition=Disposition.UNKNOWN,
                environment=Environment.AIR,
            ),
            # 3D SIGINT tracks with a bearing and a range estimate
            # populate line_of_bearing on the signal component.
            signal=Signal(
                report=Oneof(
                    "line_of_bearing",
                    LineOfBearing(
                        angle_of_arrival=AngleOfArrival(
                            relative_pose=Pose(
                                pos=LLA(lat=50.91402185768586, lon=0.79203612077257, alt=300.0),
                                # Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                                att_enu=Quaternion(x=0.0, y=0.0, z=0.0, w=1.0),
                            ),
                            bearing_elevation_covariance_rad2=TMat2(mxx=0.0004, mxy=0.0, myy=0.0009),
                        ),
                        # Estimated distance from the sensor to the emitter,
                        # with a one-sigma uncertainty in meters.
                        detection_range=Oneof(
                            "range_estimate_m",
                            Measurement(
                                value=DoubleValue(value=12500.0),
                                sigma=DoubleValue(value=750.0),
                            ),
                        ),
                    ),
                ),
            ),
            # position_enu_cov is required for the track to be eligible for
            # fusion. A diagonal-only matrix is valid when cross-terms are
            # unknown.
            location_uncertainty=LocationUncertainty(
                position_enu_cov=TMat3(mxx=400.0, myy=400.0, mzz=1600.0),
            ),
            relationships=Relationships(
                relationships=[
                    Relationship(
                        related_entity_id=sensor_entity_id,
                        relationship_id=relationship_id,
                        relationship_type=RelationshipType(
                            type=Oneof(
                                "tracked_by",
                                TrackedBy(
                                    last_measurement_timestamp=latest_ts,
                                    # Echo the subset of the tracking entity's sensors
                                    # that produced this detection. Each entry's sensor_id
                                    # and sensor_type must match the corresponding entry
                                    # on the tracking entity's top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="rf-1",
                                                sensor_type=SensorType.RF,
                                                operational_state=OperationalState.OPERATIONAL,
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ),
                ],
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="rf_sigint",
                source_update_time=latest_ts,
            ),
        )

        try:
            client.publish_entity(PublishEntityRequest(entity=entity))
            print(f"Publishing track with entity ID: {track_id}")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        # Republish at least every 10 seconds to satisfy Lattice's
        # source_update_time cadence requirement.
        time.sleep(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={92} maxLines={106}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    line_of_bearing, relationship_type, signal, Aliases, AngleOfArrival, Entity, LineOfBearing,
    LocationUncertainty, Measurement, MilView, Ontology, OperationalState, Provenance,
    PublishEntityRequest, Relationship, RelationshipType, Relationships, Sensor, SensorType,
    Sensors, Signal, TMat3, Template, TrackedBy,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::{Lla, Pose, Quaternion, TMat2};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;
use uuid::Uuid;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn add_seconds(ts: &Timestamp, seconds: i64) -> Timestamp {
    Timestamp {
        seconds: ts.seconds + seconds,
        nanos: ts.nanos,
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Replace with the real entity ID of the RF sensor (published as a
    // TEMPLATE_ASSET entity) when running against a live environment.
    let sensor_entity_id = "<SENSOR_ENTITY_ID>".to_string();

    // Setup authentication
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, sensor_entity_id);
    let creation_timestamp = now_timestamp();

    // Continuously publish the entity
    loop {
        let latest_timestamp = now_timestamp();

        // 3D SIGINT tracks with a bearing and a range estimate populate
        // line_of_bearing on the signal component.
        let entity = Entity {
            entity_id: track_id.clone(),
            description: "RF emitter detection with estimated range".to_string(),
            aliases: Some(Aliases {
                name: format!("SOI-{}", &track_id[..8]),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            expiry_time: Some(add_seconds(&latest_timestamp, 10)),
            ontology: Some(Ontology {
                template: Template::SignalOfInterest as i32,
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Unknown as i32,
                environment: Environment::Air as i32,
                ..Default::default()
            }),
            signal: Some(Signal {
                report: Some(signal::Report::LineOfBearing(LineOfBearing {
                    angle_of_arrival: Some(AngleOfArrival {
                        relative_pose: Some(Pose {
                            pos: Some(Lla {
                                lat: 50.91402185768586,
                                lon: 0.79203612077257,
                                alt: 300.0,
                                ..Default::default()
                            }),
                            // Identity quaternion: the bearing points due east (ENU +X). Rotate it to point at the target.
                            att_enu: Some(Quaternion {
                                x: 0.0,
                                y: 0.0,
                                z: 0.0,
                                w: 1.0,
                            }),
                            ..Default::default()
                        }),
                        bearing_elevation_covariance_rad2: Some(TMat2 {
                            mxx: 0.0004,
                            mxy: 0.0,
                            myy: 0.0009,
                        }),
                    }),
                    // Estimated distance from the sensor to the emitter,
                    // with a one-sigma uncertainty in meters.
                    detection_range: Some(line_of_bearing::DetectionRange::RangeEstimateM(
                        Measurement {
                            value: Some(12500.0),
                            sigma: Some(750.0),
                        },
                    )),
                })),
                ..Default::default()
            }),
            // position_enu_cov is required for the track to be eligible for
            // fusion. A diagonal-only matrix is valid when cross-terms are
            // unknown.
            location_uncertainty: Some(LocationUncertainty {
                position_enu_cov: Some(TMat3 {
                    mxx: 400.0,
                    myy: 400.0,
                    mzz: 1600.0,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: vec![Relationship {
                    related_entity_id: sensor_entity_id.clone(),
                    relationship_id: relationship_id.clone(),
                    relationship_type: Some(RelationshipType {
                        r#type: Some(relationship_type::Type::TrackedBy(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp.clone()),
                            // Echo the subset of the tracking entity's sensors
                            // that produced this detection. Each entry's sensor_id
                            // and sensor_type must match the corresponding entry
                            // on the tracking entity's top-level `sensors` component.
                            actively_tracking_sensors: Some(Sensors {
                                sensors: vec![Sensor {
                                    sensor_id: "rf-1".to_string(),
                                    sensor_type: SensorType::Rf as i32,
                                    operational_state: OperationalState::Operational as i32,
                                    ..Default::default()
                                }],
                            }),
                        })),
                    }),
                }],
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "rf_sigint".to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            ..Default::default()
        };

        let request = Request::new(PublishEntityRequest {
            entity: Some(entity),
        });
        match client.publish_entity(request).await {
            Ok(_) => println!("Publishing track with entity ID: {}", track_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

#### Resolved 3D detection

Use this approach when your sensor, such as a LiDAR or tracking radar, produces a resolved 3D
position for the target. Populate
[`location`](/reference/rest/entities/publish-entity#request.body.location) with position and velocity,
and populate [`location_uncertainty`](/reference/rest/entities/publish-entity#request.body.locationUncertainty)
with ENU covariance matrices.

Define the entity model's required components. To represent a resolved 3D track:

* Set `template` to `TEMPLATE_TRACK`.
* Populate `location.position` with latitude, longitude, and HAE altitude.
* Populate `location.velocityEnu` with east, north, and up velocity in meters per second.
* Populate `locationUncertainty.positionEnuCov` and `locationUncertainty.velocityEnuCov`
  with the upper triangle of each 3x3 covariance matrix.

**`entity.json`**

```json maxLines=30 title="entity.json"
{
  "entityId": "UNIQUE_ENTITY_ID",
  "description": "Resolved 3D track from radar",
  "isLive": true,
  "createdTime": "2026-05-01T00:00:00.000Z",
  "expiryTime": "2026-05-01T00:00:10.000Z",
  "aliases": { "name": "Track-12345678" },
  "ontology": { "template": "TEMPLATE_TRACK" },
  "milView": {
    "disposition": "DISPOSITION_UNKNOWN",
    "environment": "ENVIRONMENT_AIR"
  },
  "location": {
    "position": {
      "latitudeDegrees": 34.045,
      "longitudeDegrees": -117.99,
      "altitudeHaeMeters": 512.12
    },
    "velocityEnu": { "e": 4.81, "n": -31.65, "u": -11.74 }
  },
  "locationUncertainty": {
    "positionEnuCov": { "mxx": 25.0, "myy": 25.0, "mzz": 100.0 },
    "velocityEnuCov": { "mxx": 1.0, "myy": 1.0, "mzz": 4.0 }
  },
  "relationships": {
    "relationships": [{
      "relatedEntityId": "SENSOR_ENTITY_ID",
      "relationshipId": "UNIQUE_ENTITY_ID-tracked-by-SENSOR_ENTITY_ID",
      "relationshipType": {
        "trackedBy": {
          "lastMeasurementTimestamp": "2026-05-01T00:00:00.000Z",
          "activelyTrackingSensors": {
            "sensors": [{
              "sensorId": "panel-1",
              "sensorType": "SENSOR_TYPE_RADAR",
              "operationalState": "OPERATIONAL_STATE_OPERATIONAL"
            }]
          }
        }
      }
    }]
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "radar_track",
    "sourceUpdateTime": "2026-05-01T00:00:00.000Z"
  }
}
```

Take a closer look at the position, velocity, and uncertainty components:

**`location`**

```json title="location"
"location": {
  "position": {
    // Set position in WGS-84 latitude and longitude degrees.
    "latitudeDegrees": 34.045,
    "longitudeDegrees": -117.99,
    // Set altitude as height above the WGS-84 ellipsoid.
    "altitudeHaeMeters": 512.12
  },
  // Velocity in the local ENU frame, in meters per second.
  "velocityEnu": { "e": 4.81, "n": -31.65, "u": -11.74 }
}
```

**`locationUncertainty`**

```json title="locationUncertainty"
"locationUncertainty": {
  // Upper triangle of the position covariance matrix. It is
  // valid to populate only the diagonal if the full matrix
  // is unknown.
  "positionEnuCov": {
    "mxx": 25.0,
    "myy": 25.0,
    "mzz": 100.0
  },
  // Upper triangle of the velocity covariance matrix.
  "velocityEnuCov": {
    "mxx": 1.0,
    "myy": 1.0,
    "mzz": 4.0
  }
}
```

**`relationships`**

```json title="relationships"
"relationships": {
  "relationships": [
    {
      "relatedEntityId": "SENSOR_ENTITY_ID",
      "relationshipId": "UNIQUE_ENTITY_ID-tracked-by-SENSOR_ENTITY_ID",
      "relationshipType": {
        "trackedBy": {
          "lastMeasurementTimestamp": "2026-05-01T00:00:00.000Z",
          // List the sensors on the tracking entity that are
          // actively contributing to this track. Each entry must
          // match a sensor_id and sensor_type on the referenced
          // sensor asset.
          "activelyTrackingSensors": {
            "sensors": [
              {
                "sensorId": "panel-1",
                "sensorType": "SENSOR_TYPE_RADAR",
                "operationalState": "OPERATIONAL_STATE_OPERATIONAL"
              }
            ]
          }
        }
      }
    }
  ]
}
```

Use the [`PublishEntity`](/reference/rest/entities/publish-entity) API method to publish
the entity:

```go title={"Go (REST)"} startLine={58} maxLines={77}
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
	"github.com/google/uuid"
)

func main() {
	// Get environment variables
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")

	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the sensor (published
	// as a TEMPLATE_ASSET entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Initialize headers for sandbox authorization
	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	// Create the client
	LatticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()

	// Continuously publish the entity
	for {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &trackId,
			Description: Lattice.String("Resolved 3D track from radar"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String(fmt.Sprintf("Track-%s", trackId[:8])),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(10 * time.Second)),
			Ontology: &Lattice.Ontology{
				Template: Lattice.OntologyTemplateTemplateTrack.Ptr(),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionUnknown.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
			},
			Location: &Lattice.Location{
				Position: &Lattice.Position{
					LatitudeDegrees:  Lattice.Float64(34.045),
					LongitudeDegrees: Lattice.Float64(-117.99),
					AltitudeHaeMeters: Lattice.Float64(512.12),
				},
				VelocityEnu: &Lattice.Enu{
					E: Lattice.Float64(4.81),
					N: Lattice.Float64(-31.65),
					U: Lattice.Float64(-11.74),
				},
			},
			LocationUncertainty: &Lattice.LocationUncertainty{
				// Populate at least the diagonal (mxx, myy, mzz) of each
				// covariance matrix. Off-diagonal terms are optional.
				PositionEnuCov: &Lattice.EntityManagerTMat3{
					Mxx: Lattice.Float64(25.0),
					Myy: Lattice.Float64(25.0),
					Mzz: Lattice.Float64(100.0),
				},
				VelocityEnuCov: &Lattice.EntityManagerTMat3{
					Mxx: Lattice.Float64(1.0),
					Myy: Lattice.Float64(1.0),
					Mzz: Lattice.Float64(4.0),
				},
			},
			Relationships: &Lattice.Relationships{
				Relationships: []*Lattice.Relationship{
					{
						RelatedEntityID: Lattice.String(sensorEntityId),
						RelationshipID:  Lattice.String(relationshipId),
						RelationshipType: &Lattice.RelationshipType{
							TrackedBy: &Lattice.TrackedBy{
								LastMeasurementTimestamp: Lattice.Time(latestTimestamp),
								// Echo the subset of the tracking entity's sensors
								// that produced this detection. Each entry's sensor_id
								// and sensor_type must match the corresponding entry
								// on the tracking entity's top-level `sensors` component.
								ActivelyTrackingSensors: &Lattice.Sensors{
									Sensors: []*Lattice.Sensor{
										{
											SensorID:         Lattice.String("panel-1"),
											SensorType:       Lattice.SensorSensorTypeSensorTypeRadar.Ptr(),
											OperationalState: Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("radar_track"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Println("Publishing track")
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```java title={"Java (REST)"} startLine={74} maxLines={77}
package org.example;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Aliases;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerTMat3;
import com.anduril.types.Enu;
import com.anduril.types.Location;
import com.anduril.types.LocationUncertainty;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Provenance;
import com.anduril.types.Relationship;
import com.anduril.types.RelationshipType;
import com.anduril.types.Relationships;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TrackedBy;



public class PublishTrack3dKinematic {
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");

        // Check required variables and ensure URL has https://
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;

        // Replace with the real entity ID of the sensor (published
        // as a TEMPLATE_ASSET entity) when running against a live environment.
        String sensorEntityId = "<SENSOR_ENTITY_ID>";

        try {
            // Create Lattice client with Sandbox authentication
            Lattice client = Lattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();

            // Generate a unique ID for the entity
            String trackId = UUID.randomUUID().toString();
            String relationshipId = trackId + "-tracked-by-" + sensorEntityId;

            // Get creation time
            Instant creationTime = Instant.now();

            // Continuously publish the entity
            while (true) {
                try {
                    // Get current timestamp
                    Instant latestTimestamp = Instant.now();

                    // Create the entity
                    Entity entity = Entity.builder()
                        .entityId(trackId)
                        .description("Resolved 3D track from radar")
                        .aliases(Aliases.builder()
                            .name("Track-" + trackId.substring(0, 8))
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(10, ChronoUnit.SECONDS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_TRACK)
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_UNKNOWN)
                            .environment(MilViewEnvironment.ENVIRONMENT_AIR)
                            .build())
                        .location(Location.builder()
                            .position(Position.builder()
                                .latitudeDegrees(34.045)
                                .longitudeDegrees(-117.99)
                                .altitudeHaeMeters(512.12)
                                .build())
                            .velocityEnu(Enu.builder()
                                .e(4.81)
                                .n(-31.65)
                                .u(-11.74)
                                .build())
                            .build())
                        .locationUncertainty(LocationUncertainty.builder()
                            // Populate at least the diagonal (mxx, myy, mzz) of each
                            // covariance matrix. Off-diagonal terms are optional.
                            .positionEnuCov(EntityManagerTMat3.builder()
                                .mxx(25f)
                                .myy(25f)
                                .mzz(100f)
                                .build())
                            .velocityEnuCov(EntityManagerTMat3.builder()
                                .mxx(1f)
                                .myy(1f)
                                .mzz(4f)
                                .build())
                            .build())
                        .relationships(Relationships.builder()
                            .relationships(List.of(
                                Relationship.builder()
                                    .relatedEntityId(sensorEntityId)
                                    .relationshipId(relationshipId)
                                    .relationshipType(RelationshipType.builder()
                                        .trackedBy(TrackedBy.builder()
                                            .lastMeasurementTimestamp(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                            // Echo the subset of the tracking entity's sensors
                                            // that produced this detection. Each entry's sensor_id
                                            // and sensor_type must match the corresponding entry
                                            // on the tracking entity's top-level `sensors` component.
                                            .activelyTrackingSensors(Sensors.builder()
                                                .sensors(List.of(
                                                    Sensor.builder()
                                                        .sensorId("panel-1")
                                                        .sensorType(SensorSensorType.SENSOR_TYPE_RADAR)
                                                        .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                                        .build()
                                                ))
                                                .build())
                                            .build())
                                        .build())
                                    .build()
                            ))
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("radar_track")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing track");

                    // Republish at least every 10 seconds to satisfy Lattice's
                    // source_update_time cadence requirement.
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    Thread.sleep(10000);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={37} maxLines={72}
from anduril import Lattice, \
    Aliases, MilView, Ontology, Provenance, \
    Location, Position, Enu, LocationUncertainty, EntityManagerTMat3, \
    Relationships, Relationship, RelationshipType, TrackedBy, Sensors, Sensor
from datetime import datetime, timezone, timedelta
import asyncio
import os
import sys
from uuid import uuid4

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')

# Replace with the real entity ID of the sensor (published
# as a TEMPLATE_ASSET entity) when running against a live environment.
sensor_entity_id = "<SENSOR_ENTITY_ID>"

# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing required environment variables.")
    sys.exit(1)

client = Lattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)
track_id = str(uuid4())
relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"
async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        while(True):
            latest_timestamp = datetime.now(timezone.utc)
            client.entities.publish_entity(
                entity_id=track_id,
                description="Resolved 3D track from radar",
                aliases=Aliases(name=f"Track-{track_id[:8]}"),
                is_live=True,
                created_time=creation_time,
                expiry_time=latest_timestamp + timedelta(seconds=10),
                ontology=Ontology(template="TEMPLATE_TRACK"),
                mil_view=MilView(
                    disposition="DISPOSITION_UNKNOWN",
                    environment="ENVIRONMENT_AIR",
                ),
                location=Location(
                    position=Position(
                        latitude_degrees=34.045,
                        longitude_degrees=-117.99,
                        altitude_hae_meters=512.12,
                    ),
                    velocity_enu=Enu(
                        e=4.81,
                        n=-31.65,
                        u=-11.74,
                    ),
                ),
                location_uncertainty=LocationUncertainty(
                    # Populate at least the diagonal (mxx, myy, mzz) of each
                    # covariance matrix. Off-diagonal terms are optional.
                    position_enu_cov=EntityManagerTMat3(
                        mxx=25.0,
                        myy=25.0,
                        mzz=100.0,
                    ),
                    velocity_enu_cov=EntityManagerTMat3(
                        mxx=1.0,
                        myy=1.0,
                        mzz=4.0,
                    ),
                ),
                relationships=Relationships(
                    relationships=[
                        Relationship(
                            related_entity_id=sensor_entity_id,
                            relationship_id=relationship_id,
                            relationship_type=RelationshipType(
                                tracked_by=TrackedBy(
                                    last_measurement_timestamp=latest_timestamp,
                                    # Echo the subset of the tracking
                                    # entity's sensors that produced this
                                    # detection. Each entry's sensor_id and
                                    # sensor_type must match the corresponding
                                    # entry on the tracking entity's
                                    # top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="panel-1",
                                                sensor_type="SENSOR_TYPE_RADAR",
                                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ],
                ),
                provenance=Provenance(
                    integration_name="your_integration_name",
                    data_type="radar_track",
                    source_update_time=latest_timestamp,
                ),
            )
            await asyncio.sleep(1)

    except asyncio.CancelledError:
        print(">>>Exiting...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())

```

```ts title={"TypeScript (REST)"} startLine={33} maxLines={74}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v4 as uuidv4 } from 'uuid';

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
    }
);

// Replace with the real entity ID of the sensor (published
// as a TEMPLATE_ASSET entity) when running against a live environment.
const sensorEntityId = "<SENSOR_ENTITY_ID>";
const trackId = uuidv4();
const relationshipId = `${trackId}-tracked-by-${sensorEntityId}`;
const createdTime = new Date();

async function App() {
    try {
        const latestTimestamp = new Date();
        await client.entities.publishEntity(
            {
                entityId: trackId,
                description: "Resolved 3D track from radar",
                aliases: { name: `Track-${trackId.substring(0, 8)}` },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + 10 * 1000).toISOString(),
                ontology: {
                    template: "TEMPLATE_TRACK"
                },
                milView: {
                    disposition: "DISPOSITION_UNKNOWN",
                    environment: "ENVIRONMENT_AIR"
                },
                location: {
                    position: {
                        latitudeDegrees: 34.045,
                        longitudeDegrees: -117.99,
                        altitudeHaeMeters: 512.12
                    },
                    velocityEnu: {
                        e: 4.81,
                        n: -31.65,
                        u: -11.74
                    }
                },
                locationUncertainty: {
                    // Populate at least the diagonal (mxx, myy, mzz) of each
                    // covariance matrix. Off-diagonal terms are optional.
                    positionEnuCov: {
                        mxx: 25.0,
                        myy: 25.0,
                        mzz: 100.0
                    },
                    velocityEnuCov: {
                        mxx: 1.0,
                        myy: 1.0,
                        mzz: 4.0
                    }
                },
                relationships: {
                    relationships: [
                        {
                            relatedEntityId: sensorEntityId,
                            relationshipId: relationshipId,
                            relationshipType: {
                                trackedBy: {
                                    lastMeasurementTimestamp: latestTimestamp.toISOString(),
                                    // Echo the subset of the tracking entity's sensors
                                    // that produced this detection. Each entry's sensor_id
                                    // and sensor_type must match the corresponding entry
                                    // on the tracking entity's top-level `sensors` component.
                                    activelyTrackingSensors: {
                                        sensors: [
                                            {
                                                sensorId: "panel-1",
                                                sensorType: "SENSOR_TYPE_RADAR",
                                                operationalState: "OPERATIONAL_STATE_OPERATIONAL"
                                            }
                                        ]
                                    }
                                }
                            }
                        }
                    ]
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "radar_track",
                    sourceUpdateTime: latestTimestamp.toISOString()
                }
            }
        );
        console.log(`Publishing track.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
})();

```

```rs title={"Rust (REST)"} startLine={47} maxLines={94}
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::time::Duration;
use uuid::Uuid;

// Replace with the real entity ID of the sensor (published as a TEMPLATE_ASSET
// entity) when running against a live environment.
const SENSOR_ENTITY_ID: &str = "<SENSOR_ENTITY_ID>";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, SENSOR_ENTITY_ID);

    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        let entity = Entity {
            entity_id: Some(track_id.clone()),
            description: Some("Resolved 3D track from radar".to_string()),
            aliases: Some(Aliases {
                name: Some(format!("Track-{}", &track_id[..8])),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::seconds(10)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateTrack),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionUnknown),
                environment: Some(MilViewEnvironment::EnvironmentAir),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(Position {
                    latitude_degrees: Some(34.045),
                    longitude_degrees: Some(-117.99),
                    altitude_hae_meters: Some(512.12),
                    ..Default::default()
                }),
                velocity_enu: Some(Enu {
                    e: Some(4.81),
                    n: Some(-31.65),
                    u: Some(-11.74),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            location_uncertainty: Some(LocationUncertainty {
                // Populate at least the diagonal (mxx, myy, mzz) of each
                // covariance matrix. Off-diagonal terms are optional.
                position_enu_cov: Some(EntityManagerTMat3 {
                    mxx: Some(25.0),
                    myy: Some(25.0),
                    mzz: Some(100.0),
                    ..Default::default()
                }),
                velocity_enu_cov: Some(EntityManagerTMat3 {
                    mxx: Some(1.0),
                    myy: Some(1.0),
                    mzz: Some(4.0),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: Some(vec![Relationship {
                    related_entity_id: Some(SENSOR_ENTITY_ID.to_string()),
                    relationship_id: Some(relationship_id.clone()),
                    relationship_type: Some(RelationshipType {
                        tracked_by: Some(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp),
                            // Echo the subset of the tracking entity's sensors
                            // that produced this detection. Each entry's
                            // sensor_id and sensor_type must match the
                            // corresponding entry on the tracking entity's
                            // top-level `sensors` component.
                            actively_tracking_sensors: Some(Sensors {
                                sensors: Some(vec![Sensor {
                                    sensor_id: Some("panel-1".to_string()),
                                    sensor_type: Some(SensorSensorType::SensorTypeRadar),
                                    operational_state: Some(
                                        SensorOperationalState::OperationalStateOperational,
                                    ),
                                    ..Default::default()
                                }]),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }),
                    ..Default::default()
                }]),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("radar_track".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            ..Default::default()
        };

        if let Err(e) = client.entities.publish_entity(&entity, None).await {
            eprintln!("Exception: {}", e);
        }

        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={76} maxLines={84}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	typepb "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// Get environment variables
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Replace with the real entity ID of the sensor (published
	// as a TEMPLATE_ASSET entity) when running against a live environment.
	sensorEntityId := "<SENSOR_ENTITY_ID>"

	// Setup authentication
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	// Setup gRPC connection options
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}

	// Create gRPC connection
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	// Create EntityManager client
	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Generate a unique ID for the entity
	trackId := uuid.New().String()
	relationshipId := fmt.Sprintf("%s-tracked-by-%s", trackId, sensorEntityId)

	// Get creation time
	creationTime := time.Now().UTC()
	creationTimestamp := timestamppb.New(creationTime)

	// Continuously publish the entity
	for {
		// Get current timestamp for this update
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    trackId,
			Description: "Resolved 3D track from radar",
			Aliases: &entitymanagerv1.Aliases{
				Name: fmt.Sprintf("Track-%s", trackId[:8]),
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(10 * time.Second)),
			Ontology: &entitymanagerv1.Ontology{
				Template: entitymanagerv1.Template_TEMPLATE_TRACK,
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_UNKNOWN,
				Environment: ontologyv1.Environment_ENVIRONMENT_AIR,
			},
			Location: &entitymanagerv1.Location{
				Position: &entitymanagerv1.Position{
					LatitudeDegrees:   34.045,
					LongitudeDegrees:  -117.99,
					AltitudeHaeMeters: wrapperspb.Double(512.12),
				},
				VelocityEnu: &typepb.ENU{
					E: 4.81,
					N: -31.65,
					U: -11.74,
				},
			},
			LocationUncertainty: &entitymanagerv1.LocationUncertainty{
				// Populate at least the diagonal (mxx, myy, mzz) of each
				// covariance matrix. Off-diagonal terms are optional.
				PositionEnuCov: &entitymanagerv1.TMat3{
					Mxx: 25.0,
					Myy: 25.0,
					Mzz: 100.0,
				},
				VelocityEnuCov: &entitymanagerv1.TMat3{
					Mxx: 1.0,
					Myy: 1.0,
					Mzz: 4.0,
				},
			},
			Relationships: &entitymanagerv1.Relationships{
				Relationships: []*entitymanagerv1.Relationship{
					{
						RelatedEntityId: sensorEntityId,
						RelationshipId:  relationshipId,
						RelationshipType: &entitymanagerv1.RelationshipType{
							Type: &entitymanagerv1.RelationshipType_TrackedBy{
								TrackedBy: &entitymanagerv1.TrackedBy{
									LastMeasurementTimestamp: timestamppb.New(latestTimestamp),
									// Echo the subset of the tracking entity's sensors
									// that produced this detection. Each entry's sensor_id
									// and sensor_type must match the corresponding entry
									// on the tracking entity's top-level `sensors` component.
									ActivelyTrackingSensors: &entitymanagerv1.Sensors{
										Sensors: []*entitymanagerv1.Sensor{
											{
												SensorId:         "panel-1",
												SensorType:       entitymanagerv1.SensorType_SENSOR_TYPE_RADAR,
												OperationalState: entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
											},
										},
									},
								},
							},
						},
					},
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "radar_track",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
		}

		// Create publish request
		request := &entitymanagerv1.PublishEntityRequest{
			Entity: entity,
		}

		// Publish the entity
		_, err := client.PublishEntity(ctx, request)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing track with entity ID: %s\n", trackId)
		}

		// Republish at least every 10 seconds to satisfy Lattice's
		// source_update_time cadence requirement.
		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={71} maxLines={64}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf import Oneof
from protobuf.wkt import DoubleValue, Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.location_pub_pb import (
    Location,
    LocationUncertainty,
    Position,
    TMat3,
)
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.relationship_pub_pb import (
    Relationship,
    Relationships,
    RelationshipType,
    TrackedBy,
)
from anduril.entitymanager.v1.sensors_pub_pb import (
    OperationalState,
    Sensor,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.type.coords_pub_pb import ENU


def to_timestamp(dt: datetime) -> Timestamp:
    return Timestamp.from_datetime(dt)


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Replace with the real entity ID of the sensor (published
    # as a TEMPLATE_ASSET entity) when running against a live environment.
    sensor_entity_id = "<SENSOR_ENTITY_ID>"

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    track_id = str(uuid.uuid4())
    relationship_id = f"{track_id}-tracked-by-{sensor_entity_id}"

    creation_timestamp = to_timestamp(datetime.now(timezone.utc))

    while True:
        latest = datetime.now(timezone.utc)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + timedelta(seconds=10))

        entity = Entity(
            entity_id=track_id,
            description="Resolved 3D track from radar",
            aliases=Aliases(name=f"Track-{track_id[:8]}"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.TRACK),
            mil_view=MilView(
                disposition=Disposition.UNKNOWN,
                environment=Environment.AIR,
            ),
            location=Location(
                position=Position(
                    latitude_degrees=34.045,
                    longitude_degrees=-117.99,
                    altitude_hae_meters=DoubleValue(value=512.12),
                ),
                velocity_enu=ENU(e=4.81, n=-31.65, u=-11.74),
            ),
            location_uncertainty=LocationUncertainty(
                # Populate at least the diagonal (mxx, myy, mzz) of each
                # covariance matrix. Off-diagonal terms are optional.
                position_enu_cov=TMat3(mxx=25.0, myy=25.0, mzz=100.0),
                velocity_enu_cov=TMat3(mxx=1.0, myy=1.0, mzz=4.0),
            ),
            relationships=Relationships(
                relationships=[
                    Relationship(
                        related_entity_id=sensor_entity_id,
                        relationship_id=relationship_id,
                        relationship_type=RelationshipType(
                            type=Oneof(
                                "tracked_by",
                                TrackedBy(
                                    last_measurement_timestamp=latest_ts,
                                    # Echo the subset of the tracking entity's sensors
                                    # that produced this detection. Each entry's sensor_id
                                    # and sensor_type must match the corresponding entry
                                    # on the tracking entity's top-level `sensors` component.
                                    actively_tracking_sensors=Sensors(
                                        sensors=[
                                            Sensor(
                                                sensor_id="panel-1",
                                                sensor_type=SensorType.RADAR,
                                                operational_state=OperationalState.OPERATIONAL,
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ),
                ],
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="radar_track",
                source_update_time=latest_ts,
            ),
        )

        try:
            client.publish_entity(PublishEntityRequest(entity=entity))
            print(f"Publishing track with entity ID: {track_id}")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        # Republish at least every 10 seconds to satisfy Lattice's
        # source_update_time cadence requirement.
        time.sleep(1)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={89} maxLines={89}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    relationship_type, Aliases, Entity, Location, LocationUncertainty, MilView, Ontology,
    OperationalState, Position, Provenance, PublishEntityRequest, Relationship, RelationshipType,
    Relationships, Sensor, SensorType, Sensors, TMat3, Template, TrackedBy,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::Enu;
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;
use uuid::Uuid;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

fn add_seconds(ts: &Timestamp, seconds: i64) -> Timestamp {
    Timestamp {
        seconds: ts.seconds + seconds,
        nanos: ts.nanos,
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    // Replace with the real entity ID of the sensor (published as a
    // TEMPLATE_ASSET entity) when running against a live environment.
    let sensor_entity_id = "<SENSOR_ENTITY_ID>".to_string();

    // Setup authentication
    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    let track_id = Uuid::new_v4().to_string();
    let relationship_id = format!("{}-tracked-by-{}", track_id, sensor_entity_id);
    let creation_timestamp = now_timestamp();

    // Continuously publish the entity
    loop {
        let latest_timestamp = now_timestamp();

        let entity = Entity {
            entity_id: track_id.clone(),
            description: "Resolved 3D track from radar".to_string(),
            aliases: Some(Aliases {
                name: format!("Track-{}", &track_id[..8]),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            expiry_time: Some(add_seconds(&latest_timestamp, 10)),
            ontology: Some(Ontology {
                template: Template::Track as i32,
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Unknown as i32,
                environment: Environment::Air as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(Position {
                    latitude_degrees: 34.045,
                    longitude_degrees: -117.99,
                    altitude_hae_meters: Some(512.12),
                    ..Default::default()
                }),
                velocity_enu: Some(Enu {
                    e: 4.81,
                    n: -31.65,
                    u: -11.74,
                }),
                ..Default::default()
            }),
            location_uncertainty: Some(LocationUncertainty {
                // Populate at least the diagonal (mxx, myy, mzz) of each
                // covariance matrix. Off-diagonal terms are optional.
                position_enu_cov: Some(TMat3 {
                    mxx: 25.0,
                    myy: 25.0,
                    mzz: 100.0,
                    ..Default::default()
                }),
                velocity_enu_cov: Some(TMat3 {
                    mxx: 1.0,
                    myy: 1.0,
                    mzz: 4.0,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            relationships: Some(Relationships {
                relationships: vec![Relationship {
                    related_entity_id: sensor_entity_id.clone(),
                    relationship_id: relationship_id.clone(),
                    relationship_type: Some(RelationshipType {
                        r#type: Some(relationship_type::Type::TrackedBy(TrackedBy {
                            last_measurement_timestamp: Some(latest_timestamp.clone()),
                            // Echo the subset of the tracking entity's sensors
                            // that produced this detection. Each entry's sensor_id
                            // and sensor_type must match the corresponding entry
                            // on the tracking entity's top-level `sensors` component.
                            actively_tracking_sensors: Some(Sensors {
                                sensors: vec![Sensor {
                                    sensor_id: "panel-1".to_string(),
                                    sensor_type: SensorType::Radar as i32,
                                    operational_state: OperationalState::Operational as i32,
                                    ..Default::default()
                                }],
                            }),
                        })),
                    }),
                }],
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "radar_track".to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            ..Default::default()
        };

        let request = Request::new(PublishEntityRequest {
            entity: Some(entity),
        });
        match client.publish_entity(request).await {
            Ok(_) => println!("Publishing track with entity ID: {}", track_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        // Republish at least every 10 seconds to satisfy Lattice's
        // source_update_time cadence requirement.
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

```

> **Info**
>
> To report a track's heading, populate `location.attitude_enu` using the same conventions as assets.
> For more information, see [Orientation conventions](/guides/entities/create-an-asset#orientation-conventions).

## Manage update rates

Your feed is one of many contributing to a track. Lattice fuses the independent observations
from every contributing sensor into a single track, and the accuracy of that fused picture
depends on each feed reporting only what its own sensor actually observes. Your sensor is not
solely responsible for keeping a track alive: when your sensor stops detecting the target,
other sensors in the environment may still be detecting it, and the fusion engine continues to
maintain the track from their contributions.

Publish a new update only when your sensor produces a new kinematic detection. Each update
must carry a `provenance.source_update_time` that reflects the time of that detection. Lattice
rejects any update whose `source_update_time` is earlier than or equal to the value it already
holds, so do not republish unchanged data to keep a track alive.

> **Warning**
>
> Don't republish stale detections to keep a track alive. Republishing an unchanged detection
> tells the fusion engine your sensor is still observing the target when it isn't, which degrades
> the aggregate picture that every other sensor contributes to. For example, republishing the same
> kinematic state in the absence of detections makes an air vehicle appear to hover.

Track liveness is governed by `expiry_time`. Set `expiry_time` to approximately 10
seconds ahead of the current time on every update. While your sensor keeps detecting the
target, each new detection refreshes the expiry and your contribution stays live. When your
sensor stops detecting, your contribution expires, and the fused track persists as long as any
other sensor continues to contribute.

The preceding examples loop to publish successive detections from a sensor, updating
`source_update_time` and `expiry_time` on each iteration. In a real integration, drive each
iteration from a new sensor measurement rather than a fixed timer.

## What's next?

* Follow your published tracks in real time with [Cue and monitor](/guides/entities/cue-and-monitor).
* Review the full entity model in the [Entities overview](/guides/entities/overview).
* Explore every field in the [`PublishEntity` API reference](/reference/rest/entities/publish-entity).