> 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 an asset

> Publish cameras, radars, and uncrewed vehicles as assets with health, sensors, and motion

An *asset* is an entity under your control, or under the control of another operator or system.
Assets may accept tasks such as search or tracking.

This page explains the components every asset publishes, then walks through three common
integrations:

* [Camera sensor](#example-camera-sensor): A fixed camera that pans, so its field of view changes over time.
* [Multi-panel radar](#example-multi-panel-radar): One radar system with four panels, each reporting its own state and coverage.
* [UxV with onboard sensors](#example-uxv-with-onboard-sensors): A moving uncrewed vehicle (UxV) that reports its attitude and carries a gimbaled camera and an RF sensor.

## Before you begin

* To publish assets, [set up the Lattice SDK](/guides/getting-started/set-up) and set up a Lattice environment.
* Learn about required components and the [entity templates](/guides/entities/overview#entity-templates) in Lattice.

> **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.

## Common asset components

In addition to the [required components](/guides/entities/overview#entity-model), every asset
publishes the following components:

**`ontology`** `Ontology` — required

Set [`template`](/reference/rest/entities/publish-entity#request.body.ontology.template) to
`TEMPLATE_ASSET`. Set [`platform_type`](/reference/rest/entities/publish-entity#request.body.ontology.platformType)
to a [recognized platform type](/guides/entities/overview#platform-types), such as `CAMERA`,
`RADAR`, or `UAV`, so Lattice renders the right icon.

---

**`mil_view`** `MilView` — required

Set the [disposition and environment](/reference/rest/entities/publish-entity#request.body.milView) of the
asset. Assets are generally under the control of friendly forces, so set `disposition` to
`DISPOSITION_FRIENDLY`, and set `environment` to where the asset operates, such as
`ENVIRONMENT_LAND` or `ENVIRONMENT_AIR`.

---

**`location`** `Location` — required

Set the asset's [position](/reference/rest/entities/publish-entity#request.body.location). Moving assets
also report velocity and attitude. For more information, see [Orientation conventions](#orientation-conventions).

---

**`health`** `Health` — required

Report whether the asset is reachable and operating correctly. All assets, including sensors, effectors, and
platforms, publish [`health`](/reference/rest/entities/publish-entity#request.body.health). Alongside the
top-level `health_status`, report one entry in `components` for each subsystem, such as a
battery or a radar panel. Lattice sets `connection_status` to `CONNECTION_STATUS_ONLINE`
while the asset publishes updates, and to `CONNECTION_STATUS_OFFLINE` after one minute without one.
Health reporting is exclusive to assets: tracks and geo-entities never report health.

---

**`sensors`** `Sensors`

Declare each sensor the asset carries in [`sensors`](/reference/rest/entities/publish-entity#request.body.sensors).
Give every sensor a stable `sensor_id`, a `sensor_type`, an `operational_state`,
and at least one field of view, so Lattice can render its coverage. Tracks that the sensor produces refer back
to the same `sensor_id`. For more information, see [Create a track](/guides/entities/create-a-track).

---

**`task_catalog`** `TaskCatalog`

List the tasks the asset accepts in [`task_catalog`](/reference/rest/entities/publish-entity#request.body.taskCatalog).
For more information, see [Integrate an agent](/guides/tasks/integrate-an-agent).

---

Set [`expiry_time`](/reference/rest/entities/publish-entity#request.body.expiryTime) in the future, and
republish the asset before it lapses. Republish at least every 30 seconds so the asset stays online, and
whenever its state changes. Set [`provenance.source_update_time`](/reference/rest/entities/publish-entity#request.body.provenance.sourceUpdateTime)
to the time of each update, because Lattice uses it to detect changes.

### Altitude references

The `position` component supports the following altitude references, specified in meters.
Populate the references available to your integration:

**`altitude_hae_meters`** `DoubleValue`

The entity's height above the World Geodetic System 1984 (WGS84) ellipsoid.

---

**`altitude_agl_meters`** `DoubleValue`

The entity's height above the terrain. This is typically measured with a radar altimeter or by
using a terrain tile set lookup.

---

**`altitude_asf_meters`** `DoubleValue`

The entity's height above the sea floor.

---

**`pressure_depth_meters`** `DoubleValue`

The depth of the entity from the surface of the water.

---

> **Info**
>
> Lattice doesn't support Mean Sea Level (MSL) references, such as EGM-96 and EGM-08. If the only
> altitude reference available to your integration is MSL, convert it to Height Above Ellipsoid (HAE)
> and populate the `altitude_hae_meters` field. To apply this conversion, use an open-source library,
> such as [EGM96 for Go](https://pkg.go.dev/github.com/westphae/geomag/pkg/egm96).

## Orientation conventions

Lattice describes direction with quaternions in a local East-North-Up (ENU) frame centered on the
entity. Most hardware reports direction as compass angles instead, so every example on this page
converts angles to quaternions. Keep the following conventions in mind:

* **Vehicle attitude**: `location.attitude_enu` rotates the entity's body frame into ENU. The body frame is front-left-up (FLU): +X points out of the nose, +Y to the left, and +Z up.
* **Sensor pointing**: `fields_of_view.center_ray_pose.orientation` rotates the sensor frame, whose +X axis is the boresight, into ENU. The orientation is absolute, not relative to the vehicle, so a sensor mounted on a moving vehicle must combine the vehicle's attitude with the mount angles.
* **Compass angles**: A compass heading or azimuth is measured clockwise from true north, while ENU yaw is measured counterclockwise from east. Convert a heading to yaw with `yaw = π/2 − heading`.
* **Heading priority**: If an entity sets both `attitude_enu` and `velocity_enu`, Lattice uses `attitude_enu` to render its heading.

Each example builds orientations from three elementary rotations, where angles are in radians and
quaternions are written as `(x, y, z, w)`:

| Rotation | About          | Quaternion                   |
| -------- | -------------- | ---------------------------- |
| `qz(a)`  | Up (yaw)       | `(0, 0, sin(a/2), cos(a/2))` |
| `qy(a)`  | Left (pitch)   | `(0, sin(a/2), 0, cos(a/2))` |
| `qx(a)`  | Forward (roll) | `(sin(a/2), 0, 0, cos(a/2))` |

Because positive rotation about the left axis tips the nose down, a nose-up pitch or an upward
elevation `e` uses `qy(−e)`. To point a boresight at azimuth `az` and elevation `el`, multiply
`qz(π/2 − az) ⊗ qy(−el)`. For example, an azimuth of 90° (due east) and an elevation of 0° produce the
identity quaternion `(0, 0, 0, 1)`, and an azimuth of 0° (due north) produces `(0, 0, 0.7071, 0.7071)`.

## Example: Camera sensor

A fixed electro-optical (EO) camera is one of the most common Lattice assets. In this example, a
camera on a mast pans between east and south. As the camera pans, the integration updates the
camera's field of view, so operators can see where it looks in the Lattice UI. You can later attach
the camera's video feed to the same entity. For more information, see
[Create streams](/guides/video/create-streams).

#### Define the entity

Define the camera's components. At one instant, while the camera points southeast, you get the
following entity object:

**`camera.json`**

```json maxLines=25 title="camera.json"
{
  "entityId": "e1374ef0-2aaa-5b42-89bf-17f16ec18402",
  "description": "EO camera streaming live video",
  "isLive": true,
  "createdTime": "2026-11-06T19:00:00Z",
  "expiryTime": "2026-11-06T19:01:00Z",
  "aliases": {
    "name": "Camera 01",
    "alternateIds": [
      { "id": "camera-01", "type": "ALT_ID_TYPE_SERIAL_NUMBER" }
    ]
  },
  "ontology": {
    "template": "TEMPLATE_ASSET",
    "platformType": "CAMERA"
  },
  "milView": {
    "disposition": "DISPOSITION_FRIENDLY",
    "environment": "ENVIRONMENT_LAND",
    "nationality": "NATIONALITY_UNITED_STATES_OF_AMERICA"
  },
  "location": {
    "position": {
      "latitudeDegrees": 36.66633492530301,
      "longitudeDegrees": -116.9117674522639,
      "altitudeHaeMeters": 780.0
    }
  },
  "health": {
    "connectionStatus": "CONNECTION_STATUS_ONLINE",
    "healthStatus": "HEALTH_STATUS_HEALTHY",
    "components": [
      {
        "id": "camera-01-eo",
        "name": "EO camera sensor",
        "health": "HEALTH_STATUS_HEALTHY"
      }
    ],
    "activeAlerts": []
  },
  "sensors": {
    "sensors": [
      {
        "sensorId": "camera-01-eo",
        "sensorType": "SENSOR_TYPE_CAMERA",
        "operationalState": "OPERATIONAL_STATE_OPERATIONAL",
        "sensorDescription": "EO camera, H.264",
        "fieldsOfView": [
          {
            "centerRayPose": {
              "pos": {
                "latitudeDegrees": 36.66633492530301,
                "longitudeDegrees": -116.9117674522639,
                "altitudeHaeMeters": 780.0
              },
              "orientation": { "x": 0.01669, "y": 0.0403, "z": -0.38232, "w": 0.923 }
            },
            "horizontalFov": 1.204,
            "verticalFov": 0.954,
            "range": 150.0,
            "mode": "SENSOR_MODE_SEARCH"
          }
        ]
      }
    ]
  },
  "provenance": {
    "integrationName": "lattice_video_integration",
    "dataType": "camera_video_feed",
    "sourceUpdateTime": "2026-11-06T19:00:00Z"
  }
}
```

In this example:

* The entity ID is a UUIDv5 derived from the camera's name, `camera-01`, so the camera keeps the same entity ID every time the integration restarts.
* `aliases.alternateIds` records the serial number, so other systems can cross-reference the camera.
* `health.components` reports the camera sensor itself, using the same ID as the sensor.
* The integration republishes every 5 seconds with a 60-second `expiryTime`, so the camera disappears shortly after the integration stops.

#### Point the field of view

The `sensors` component tells Lattice where the camera looks. Set `horizontalFov` and
`verticalFov` in radians from the lens's current zoom, and `range` in meters. Place
`centerRayPose.pos` at the camera, and set `centerRayPose.orientation` from the camera's pan
and tilt.

Pan-tilt cameras usually report pan as a compass azimuth and tilt as an elevation angle, so the
example converts both into an ENU quaternion with the `qz(π/2 − az) ⊗ qy(−el)` rotation from
[Orientation conventions](#orientation-conventions). A second helper simulates the pan sweep:

```go title={"Go (REST)"} startLine={40} maxLines={26}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to publish a camera asset entity.
// Attaching a video to an asset requires the asset to already exist as a Lattice entity, so
// publish the camera on a heartbeat before starting an ingress stream.
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

const (
	cameraName          = "camera-01"
	integrationName     = "lattice_video_integration"
	dataType            = "camera_video_feed"
	publishInterval     = 5 * time.Second
	entityExpiryTtlSecs = 60

	// Camera mount position.
	cameraLatitudeDegrees   = 36.66633492530301
	cameraLongitudeDegrees  = -116.9117674522639
	cameraAltitudeHaeMeters = 780.0

	// The camera pans back and forth between these compass azimuths (degrees clockwise
	// from true north), moving panStepDegrees on every update, at a fixed tilt.
	panMinAzimuthDegrees = 90.0
	panMaxAzimuthDegrees = 180.0
	panStepDegrees       = 3.0
	tiltElevationDegrees = -5.0
)

// pointingToQuaternionEnu converts a compass azimuth and elevation into the ENU quaternion
// (x, y, z, w) that rotates the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *Lattice.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	return &Lattice.Quaternion{
		X: Lattice.Float64(-math.Sin(halfYaw) * math.Sin(halfPitch)),
		Y: Lattice.Float64(math.Cos(halfYaw) * math.Sin(halfPitch)),
		Z: Lattice.Float64(math.Sin(halfYaw) * math.Cos(halfPitch)),
		W: Lattice.Float64(math.Cos(halfYaw) * math.Cos(halfPitch)),
	}
}

// panAzimuth returns the camera's azimuth after the given number of updates, sweeping
// back and forth between the minimum and maximum azimuth.
func panAzimuth(updateCount int) float64 {
	span := panMaxAzimuthDegrees - panMinAzimuthDegrees
	travel := math.Mod(float64(updateCount)*panStepDegrees, 2*span)
	if travel > span {
		travel = 2*span - travel
	}
	return panMinAzimuthDegrees + travel
}

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)
	}

	// 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),
	)

	// Stable entity ID derived from the camera's hardware identifier so the same
	// physical camera maps to the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(cameraName)).String()

	creationTime := time.Now().UTC()

	// Continuously publish the entity so it does not expire.
	for updateCount := 0; ; updateCount++ {
		latestTimestamp := time.Now().UTC()
		// Pan the camera and recompute where it points on every update.
		azimuthDeg := panAzimuth(updateCount)
		ctx := context.Background()

		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("EO camera streaming live video"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Camera 01"),
				AlternateIDs: []*Lattice.AlternateID{
					{
						ID:   Lattice.String(cameraName),
						Type: Lattice.AlternateIDTypeAltIDTypeSerialNumber.Ptr(),
					},
				},
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			// ExpiryTime is set in the future and paired with a shorter publish loop,
			// so the entity stays alive as long as the publisher runs.
			ExpiryTime: Lattice.Time(latestTimestamp.Add(entityExpiryTtlSecs * time.Second)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("CAMERA"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
				Nationality: Lattice.MilViewNationalityNationalityUnitedStatesOfAmerica.Ptr(),
			},
			// Overall classification of the entity's data.
			DataClassification: &Lattice.Classification{
				Default: &Lattice.ClassificationInformation{
					Level: Lattice.ClassificationInformationLevelClassificationLevelsUnclassified.Ptr(),
				},
			},
			Location: &Lattice.Location{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(cameraLatitudeDegrees),
					LongitudeDegrees:  Lattice.Float64(cameraLongitudeDegrees),
					AltitudeHaeMeters: Lattice.Float64(cameraAltitudeHaeMeters),
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String(integrationName),
				DataType:         Lattice.String(dataType),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
				ActiveAlerts:     []*Lattice.Alert{},
				UpdateTime:       Lattice.Time(latestTimestamp),
				// Per-subsystem health rolls up into the entity's overall
				// health_status; report at least the camera sensor itself.
				Components: []*Lattice.ComponentHealth{
					{
						ID:         Lattice.String("camera-01-eo"),
						Name:       Lattice.String("EO camera sensor"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
				},
			},
			// Declare the camera as a sensor so Lattice can render the sensor cone.
			Sensors: &Lattice.Sensors{
				Sensors: []*Lattice.Sensor{
					{
						SensorID:          Lattice.String("camera-01-eo"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						SensorDescription: Lattice.String("EO camera, H.264"),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								CenterRayPose: &Lattice.EntityManagerPose{
									// The center ray pose is an absolute ENU orientation
									// positioned at the camera.
									Pos: &Lattice.Position{
										LatitudeDegrees:   Lattice.Float64(cameraLatitudeDegrees),
										LongitudeDegrees:  Lattice.Float64(cameraLongitudeDegrees),
										AltitudeHaeMeters: Lattice.Float64(cameraAltitudeHaeMeters),
									},
									Orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees),
								},
								HorizontalFov: Lattice.Float64(1.204), // ~69 deg (typical EO horizontal FoV)
								VerticalFov:   Lattice.Float64(0.954), // ~54.6 deg (typical EO vertical FoV)
								Range:         Lattice.Float64(150.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
				},
			},
			TaskCatalog: &Lattice.TaskCatalog{
				TaskDefinitions: []*Lattice.TaskDefinition{
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/<org>.<package>.<version>.<task>")},
				},
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

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

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.AlternateId;
import com.anduril.types.AlternateIdType;
import com.anduril.types.Aliases;
import com.anduril.types.Classification;
import com.anduril.types.ClassificationInformation;
import com.anduril.types.ClassificationInformationLevel;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.MilViewNationality;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Provenance;
import com.anduril.types.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TaskCatalog;
import com.anduril.types.TaskDefinition;

/**
 * Publishes a camera asset entity with the Lattice SDK. Attaching a video to an asset requires the
 * asset to already exist as a Lattice entity, so publish the camera on a heartbeat before starting
 * an ingress stream.
 */
public class PublishCamera {
    private static final String CAMERA_NAME = "camera-01";
    private static final String INTEGRATION_NAME = "lattice_video_integration";
    private static final String DATA_TYPE = "camera_video_feed";
    private static final long PUBLISH_INTERVAL_MS = 5000;
    private static final long ENTITY_EXPIRY_TTL_SEC = 60;

    // Camera mount position.
    private static final double CAMERA_LATITUDE_DEGREES = 36.66633492530301;
    private static final double CAMERA_LONGITUDE_DEGREES = -116.9117674522639;
    private static final double CAMERA_ALTITUDE_HAE_METERS = 780.0;

    // The camera pans back and forth between these compass azimuths (degrees clockwise
    // from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
    private static final double PAN_MIN_AZIMUTH_DEGREES = 90.0;
    private static final double PAN_MAX_AZIMUTH_DEGREES = 180.0;
    private static final double PAN_STEP_DEGREES = 3.0;
    private static final double TILT_ELEVATION_DEGREES = -5.0;

    // The RFC 4122 URL namespace, used to derive the stable UUIDv5 entity ID.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");

    /**
     * Derives a name-based UUIDv5 (SHA-1). UUID.nameUUIDFromBytes produces v3 (MD5), which would
     * not match the entity ID the other languages derive.
     */
    private static UUID uuidV5(UUID namespace, String name) throws NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.update(ByteBuffer.allocate(16)
            .putLong(namespace.getMostSignificantBits())
            .putLong(namespace.getLeastSignificantBits())
            .array());
        byte[] hash = sha1.digest(name.getBytes(StandardCharsets.UTF_8));
        hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // version 5
        hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 4122 variant
        ByteBuffer buffer = ByteBuffer.wrap(hash);
        return new UUID(buffer.getLong(), buffer.getLong());
    }

    /**
     * Converts a compass azimuth and elevation into the ENU quaternion (x, y, z, w) that rotates
     * the sensor frame, whose +X axis is the boresight, into ENU.
     *
     * <p>The azimuth is degrees clockwise from true north and the elevation is degrees above the
     * horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
     */
    private static Quaternion pointingToQuaternionEnu(double azimuthDeg, double elevationDeg) {
        double halfYaw = (Math.PI / 2 - Math.toRadians(azimuthDeg)) / 2;
        double halfPitch = -Math.toRadians(elevationDeg) / 2;
        return Quaternion.builder()
            .x(-Math.sin(halfYaw) * Math.sin(halfPitch))
            .y(Math.cos(halfYaw) * Math.sin(halfPitch))
            .z(Math.sin(halfYaw) * Math.cos(halfPitch))
            .w(Math.cos(halfYaw) * Math.cos(halfPitch))
            .build();
    }

    /** Returns the camera azimuth after the given number of updates, sweeping back and forth. */
    private static double panAzimuth(long updateCount) {
        double span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
        double travel = (updateCount * PAN_STEP_DEGREES) % (2 * span);
        if (travel > span) {
            travel = 2 * span - travel;
        }
        return PAN_MIN_AZIMUTH_DEGREES + travel;
    }

    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;

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

            // Stable entity ID derived from the camera's hardware identifier so the same
            // physical camera maps to the same Lattice entity across restarts.
            String entityId = uuidV5(NAMESPACE_URL, CAMERA_NAME).toString();
            Instant creationTime = Instant.now();

            // Continuously publish the camera so it does not expire while the publisher runs.
            for (long updateCount = 0; ; updateCount++) {
                try {
                    Instant latestTimestamp = Instant.now();
                    // Pan the camera and recompute where it points on every update.
                    double azimuthDeg = panAzimuth(updateCount);

                    // Construct an Entity with the components Lattice needs to render a friendly
                    // land-based camera asset on the common operational picture (COP).
                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("EO camera streaming live video")
                        .aliases(Aliases.builder()
                            .name("Camera 01")
                            .alternateIds(List.of(AlternateId.builder()
                                .id(CAMERA_NAME)
                                .type(AlternateIdType.ALT_ID_TYPE_SERIAL_NUMBER)
                                .build()))
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        // ExpiryTime is set in the future and paired with a shorter publish loop,
                        // so the entity stays alive as long as the publisher runs.
                        .expiryTime(OffsetDateTime.ofInstant(
                            latestTimestamp.plus(ENTITY_EXPIRY_TTL_SEC, ChronoUnit.SECONDS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("CAMERA")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                            .nationality(MilViewNationality.NATIONALITY_UNITED_STATES_OF_AMERICA)
                            .build())
                        // Overall classification of the entity's data.
                        .dataClassification(Classification.builder()
                            .default_(ClassificationInformation.builder()
                                .level(ClassificationInformationLevel.CLASSIFICATION_LEVELS_UNCLASSIFIED)
                                .build())
                            .build())
                        .location(Location.builder()
                            .position(Position.builder()
                                .latitudeDegrees(CAMERA_LATITUDE_DEGREES)
                                .longitudeDegrees(CAMERA_LONGITUDE_DEGREES)
                                .altitudeHaeMeters(CAMERA_ALTITUDE_HAE_METERS)
                                .build())
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName(INTEGRATION_NAME)
                            .dataType(DATA_TYPE)
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(HealthHealthStatus.HEALTH_STATUS_HEALTHY)
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            // Per-subsystem health rolls up into the entity's overall
                            // health_status; report at least the camera sensor itself.
                            .components(List.of(ComponentHealth.builder()
                                .id("camera-01-eo")
                                .name("EO camera sensor")
                                .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                .build()))
                            .build())
                        // Declare the camera as a sensor so Lattice can render the sensor cone.
                        .sensors(Sensors.builder()
                            .sensors(List.of(Sensor.builder()
                                .sensorId("camera-01-eo")
                                .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                .sensorDescription("EO camera, H.264")
                                .fieldsOfView(List.of(FieldOfView.builder()
                                    // The center ray pose is an absolute ENU orientation
                                    // positioned at the camera.
                                    .centerRayPose(EntityManagerPose.builder()
                                        .pos(Position.builder()
                                            .latitudeDegrees(CAMERA_LATITUDE_DEGREES)
                                            .longitudeDegrees(CAMERA_LONGITUDE_DEGREES)
                                            .altitudeHaeMeters(CAMERA_ALTITUDE_HAE_METERS)
                                            .build())
                                        .orientation(pointingToQuaternionEnu(azimuthDeg, TILT_ELEVATION_DEGREES))
                                        .build())
                                    .horizontalFov(1.204f) // ~69 deg (typical EO horizontal FoV)
                                    .verticalFov(0.954f) // ~54.6 deg (typical EO vertical FoV)
                                    .range(150.0f)
                                    .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                    .build()))
                                .build()))
                            .build())
                        .taskCatalog(TaskCatalog.builder()
                            .taskDefinitions(List.of(TaskDefinition.builder()
                                .taskSpecificationUrl("type.googleapis.com/<org>.<package>.<version>.<task>")
                                .build()))
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset with entity ID: " + entityId);

                    Thread.sleep(PUBLISH_INTERVAL_MS);
                } catch (Exception e) {
                    System.err.println("Error publishing entity: " + e.getMessage());
                    Thread.sleep(PUBLISH_INTERVAL_MS);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={53} maxLines={24}
# This Python example uses the public Lattice REST SDK (anduril-lattice-sdk) to publish a
# camera asset entity. Attaching a video to an asset requires the asset to already exist as a
# Lattice entity, so publish the camera on a heartbeat before starting an ingress stream.

import math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    AlternateId,
    Classification,
    ClassificationInformation,
    ComponentHealth,
    FieldOfView,
    Health,
    Lattice,
    Location,
    MilView,
    Ontology,
    Position,
    Provenance,
    Quaternion,
    Sensor,
    Sensors,
    EntityManagerPose,
    TaskCatalog,
    TaskDefinition,
)

CAMERA_NAME = "camera-01"
INTEGRATION_NAME = "lattice_video_integration"
DATA_TYPE = "camera_video_feed"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY_TTL_SEC = 60

# Camera mount position.
CAMERA_LATITUDE_DEGREES = 36.66633492530301
CAMERA_LONGITUDE_DEGREES = -116.9117674522639
CAMERA_ALTITUDE_HAE_METERS = 780.0

# The camera pans back and forth between these compass azimuths (degrees clockwise
# from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
PAN_MIN_AZIMUTH_DEGREES = 90.0
PAN_MAX_AZIMUTH_DEGREES = 180.0
PAN_STEP_DEGREES = 3.0
TILT_ELEVATION_DEGREES = -5.0


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), already unit-normalized.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


def pan_azimuth(update_count: int) -> float:
    """Return the camera azimuth after the given number of updates, sweeping back and forth."""
    span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES
    travel = (update_count * PAN_STEP_DEGREES) % (2 * span)
    if travel > span:
        travel = 2 * span - travel
    return PAN_MIN_AZIMUTH_DEGREES + travel


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

    # 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.", file=sys.stderr)
        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}"},
    )

    # Stable entity_id derived from the camera's hardware identifier so the
    # same physical camera maps to the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, CAMERA_NAME))

    creation_time = datetime.now(timezone.utc)

    try:
        update_count = 0
        while True:
            latest_timestamp = datetime.now(timezone.utc)
            # Pan the camera and recompute where it points on every update.
            azimuth_deg = pan_azimuth(update_count)

            client.entities.publish_entity(
                entity_id=entity_id,
                description="EO camera streaming live video",
                aliases=Aliases(
                    name="Camera 01",
                    alternate_ids=[
                        AlternateId(id=CAMERA_NAME, type="ALT_ID_TYPE_SERIAL_NUMBER"),
                    ],
                ),
                is_live=True,
                created_time=creation_time,
                # ExpiryTime is set in the future and paired with a shorter publish loop,
                # so the entity stays alive as long as the publisher runs.
                expiry_time=latest_timestamp + timedelta(seconds=ENTITY_EXPIRY_TTL_SEC),
                ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
                mil_view=MilView(
                    disposition="DISPOSITION_FRIENDLY",
                    environment="ENVIRONMENT_LAND",
                    nationality="NATIONALITY_UNITED_STATES_OF_AMERICA",
                ),
                # Overall classification of the entity's data.
                data_classification=Classification(
                    default=ClassificationInformation(
                        level="CLASSIFICATION_LEVELS_UNCLASSIFIED",
                    ),
                ),
                location=Location(
                    position=Position(
                        latitude_degrees=CAMERA_LATITUDE_DEGREES,
                        longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                        altitude_hae_meters=CAMERA_ALTITUDE_HAE_METERS,
                    ),
                ),
                provenance=Provenance(
                    integration_name=INTEGRATION_NAME,
                    data_type=DATA_TYPE,
                    source_update_time=latest_timestamp,
                ),
                health=Health(
                    connection_status="CONNECTION_STATUS_ONLINE",
                    health_status="HEALTH_STATUS_HEALTHY",
                    active_alerts=[],
                    update_time=latest_timestamp,
                    # Per-subsystem health rolls up into the entity's overall
                    # health_status; report at least the camera sensor itself.
                    components=[
                        ComponentHealth(
                            id="camera-01-eo",
                            name="EO camera sensor",
                            health="HEALTH_STATUS_HEALTHY",
                            update_time=latest_timestamp,
                        ),
                    ],
                ),
                # Declare the camera as a sensor so Lattice can render the sensor cone.
                sensors=Sensors(
                    sensors=[
                        Sensor(
                            sensor_id="camera-01-eo",
                            sensor_type="SENSOR_TYPE_CAMERA",
                            operational_state="OPERATIONAL_STATE_OPERATIONAL",
                            sensor_description="EO camera, H.264",
                            fields_of_view=[
                                FieldOfView(
                                    # The center ray pose is an absolute ENU orientation
                                    # positioned at the camera.
                                    center_ray_pose=EntityManagerPose(
                                        pos=Position(
                                            latitude_degrees=CAMERA_LATITUDE_DEGREES,
                                            longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                                            altitude_hae_meters=CAMERA_ALTITUDE_HAE_METERS,
                                        ),
                                        orientation=pointing_to_quaternion_enu(azimuth_deg, TILT_ELEVATION_DEGREES),
                                    ),
                                    horizontal_fov=1.204,  # ~69 deg (typical EO horizontal FoV)
                                    vertical_fov=0.954,  # ~54.6 deg (typical EO vertical FoV)
                                    range=150.0,
                                    mode="SENSOR_MODE_SEARCH",
                                ),
                            ],
                        ),
                    ],
                ),
                task_catalog=TaskCatalog(
                    task_definitions=[
                        TaskDefinition(task_specification_url="type.googleapis.com/<org>.<package>.<version>.<task>"),
                    ],
                ),
            )
            print(f"Publishing asset with entity ID: {entity_id}")
            update_count += 1
            time.sleep(PUBLISH_INTERVAL_SEC)

    except (KeyboardInterrupt, SystemExit):
        print(">>> Exiting...")
    except Exception as error:
        print(f"Error publishing entity: {error}", file=sys.stderr)


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={43} maxLines={26}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } 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}`  }
    }
);

const cameraName = "camera-01";
const integrationName = "lattice_video_integration";
const dataType = "camera_video_feed";
const publishIntervalMs = 5000;
const entityExpiryTtlSecs = 60;

// Camera mount position.
const cameraLatitudeDegrees = 36.66633492530301;
const cameraLongitudeDegrees = -116.9117674522639;
const cameraAltitudeHaeMeters = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving panStepDegrees on every update, at a fixed tilt.
const panMinAzimuthDegrees = 90.0;
const panMaxAzimuthDegrees = 180.0;
const panStepDegrees = 3.0;
const tiltElevationDegrees = -5.0;

const degToRad = (degrees: number) => degrees * Math.PI / 180;

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w) that rotates
// the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
function pointingToQuaternionEnu(azimuthDeg: number, elevationDeg: number) {
    const halfYaw = (Math.PI / 2 - degToRad(azimuthDeg)) / 2;
    const halfPitch = -degToRad(elevationDeg) / 2;
    return {
        x: -Math.sin(halfYaw) * Math.sin(halfPitch),
        y: Math.cos(halfYaw) * Math.sin(halfPitch),
        z: Math.sin(halfYaw) * Math.cos(halfPitch),
        w: Math.cos(halfYaw) * Math.cos(halfPitch)
    };
}

// Return the camera azimuth after the given number of updates, sweeping back and forth
// between the minimum and maximum azimuth.
function panAzimuth(updateCount: number): number {
    const span = panMaxAzimuthDegrees - panMinAzimuthDegrees;
    let travel = (updateCount * panStepDegrees) % (2 * span);
    if (travel > span) {
        travel = 2 * span - travel;
    }
    return panMinAzimuthDegrees + travel;
}

let updateCount = 0;

// Stable entity ID derived from the camera's hardware identifier so the same
// physical camera maps to the same Lattice entity across restarts.
const entityId = uuidv5(cameraName, uuidv5.URL);
const creationTime = new Date().toISOString();

async function App() {
    const latestTimestamp = new Date();
    // Pan the camera and recompute where it points on every update.
    const azimuthDeg = panAzimuth(updateCount);
    updateCount += 1;
    try {
        // Attaching a video to an asset requires the asset to already exist as a Lattice
        // entity, so publish the camera on a heartbeat before starting an ingress stream.
        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "EO camera streaming live video",
                aliases: {
                    name: "Camera 01",
                    alternateIds: [
                        { id: cameraName, type: "ALT_ID_TYPE_SERIAL_NUMBER" }
                    ]
                },
                isLive: true,
                createdTime: creationTime,
                // ExpiryTime is set in the future and paired with a shorter publish loop,
                // so the entity stays alive as long as the publisher runs.
                expiryTime: new Date(latestTimestamp.getTime() + entityExpiryTtlSecs * 1000).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "CAMERA"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_LAND",
                    nationality: "NATIONALITY_UNITED_STATES_OF_AMERICA"
                },
                // Overall classification of the entity's data.
                dataClassification: {
                    default: {
                        level: "CLASSIFICATION_LEVELS_UNCLASSIFIED"
                    }
                },
                location: {
                    position: {
                        latitudeDegrees: cameraLatitudeDegrees,
                        longitudeDegrees: cameraLongitudeDegrees,
                        altitudeHaeMeters: cameraAltitudeHaeMeters
                    }
                },
                provenance: {
                    integrationName: integrationName,
                    dataType: dataType,
                    sourceUpdateTime: latestTimestamp.toISOString()
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    healthStatus: "HEALTH_STATUS_HEALTHY",
                    activeAlerts: [],
                    updateTime: latestTimestamp.toISOString(),
                    // Per-subsystem health rolls up into the entity's overall
                    // healthStatus; report at least the camera sensor itself.
                    components: [
                        {
                            id: "camera-01-eo",
                            name: "EO camera sensor",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        }
                    ]
                },
                // Declare the camera as a sensor so Lattice can render the sensor cone.
                sensors: {
                    sensors: [
                        {
                            sensorId: "camera-01-eo",
                            sensorType: "SENSOR_TYPE_CAMERA",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            sensorDescription: "EO camera, H.264",
                            fieldsOfView: [
                                {
                                    // The center ray pose is an absolute ENU orientation
                                    // positioned at the camera.
                                    centerRayPose: {
                                        pos: {
                                            latitudeDegrees: cameraLatitudeDegrees,
                                            longitudeDegrees: cameraLongitudeDegrees,
                                            altitudeHaeMeters: cameraAltitudeHaeMeters
                                        },
                                        orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees)
                                    },
                                    horizontalFov: 1.204, // ~69 deg (typical EO horizontal FoV)
                                    verticalFov: 0.954, // ~54.6 deg (typical EO vertical FoV)
                                    range: 150.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        }
                    ]
                },
                taskCatalog: {
                    taskDefinitions: [
                        { taskSpecificationUrl: "type.googleapis.com/<org>.<package>.<version>.<task>" }
                    ]
                }
            }
        );
        console.log(`Publishing asset with entity ID: ${entityId}`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}

(async function runIndefinitely() {
    while (true) {
        await App();
        await new Promise(resolve => setTimeout(resolve, publishIntervalMs));
    }
})();

```

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

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

const CAMERA_NAME: &str = "camera-01";
const INTEGRATION_NAME: &str = "lattice_video_integration";
const DATA_TYPE: &str = "camera_video_feed";
const PUBLISH_INTERVAL_SECS: u64 = 5;
const ENTITY_EXPIRY_TTL_SECS: i64 = 60;

// Camera mount position.
const CAMERA_LATITUDE_DEGREES: f64 = 36.66633492530301;
const CAMERA_LONGITUDE_DEGREES: f64 = -116.9117674522639;
const CAMERA_ALTITUDE_HAE_METERS: f64 = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
const PAN_MIN_AZIMUTH_DEGREES: f64 = 90.0;
const PAN_MAX_AZIMUTH_DEGREES: f64 = 180.0;
const PAN_STEP_DEGREES: f64 = 3.0;
const TILT_ELEVATION_DEGREES: f64 = -5.0;

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
/// The azimuth is degrees clockwise from true north and the elevation is degrees above
/// the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already
/// unit-normalized.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (std::f64::consts::FRAC_PI_2 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: Some(-half_yaw.sin() * half_pitch.sin()),
        y: Some(half_yaw.cos() * half_pitch.sin()),
        z: Some(half_yaw.sin() * half_pitch.cos()),
        w: Some(half_yaw.cos() * half_pitch.cos()),
    }
}

/// Return the camera azimuth after the given number of updates, sweeping back and forth
/// between the minimum and maximum azimuth.
fn pan_azimuth(update_count: u64) -> f64 {
    let span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
    let mut travel = (update_count as f64 * PAN_STEP_DEGREES) % (2.0 * span);
    if travel > span {
        travel = 2.0 * span - travel;
    }
    PAN_MIN_AZIMUTH_DEGREES + travel
}

/// The camera's mount position, shared by the entity location and the field of view.
fn camera_position() -> Position {
    Position {
        latitude_degrees: Some(CAMERA_LATITUDE_DEGREES),
        longitude_degrees: Some(CAMERA_LONGITUDE_DEGREES),
        altitude_hae_meters: Some(CAMERA_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

#[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)?;

    // Stable entity_id derived from the camera's hardware identifier so the
    // same physical camera maps to the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, CAMERA_NAME.as_bytes()).to_string();
    let creation_time = Utc::now().fixed_offset();

    // Refresh the entity on a heartbeat so it does not expire while the publisher runs.
    let mut update_count: u64 = 0;
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        // Pan the camera and recompute where it points on every update.
        let azimuth_deg = pan_azimuth(update_count);
        update_count += 1;

        let entity = Entity {
            entity_id: Some(entity_id.clone()),
            description: Some("EO camera streaming live video".to_string()),
            aliases: Some(Aliases {
                name: Some("Camera 01".to_string()),
                alternate_ids: Some(vec![AlternateId {
                    id: Some(CAMERA_NAME.to_string()),
                    r#type: Some(AlternateIdType::AltIdTypeSerialNumber),
                }]),
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            // ExpiryTime is set in the future and paired with a shorter publish loop,
            // so the entity stays alive as long as the publisher runs.
            expiry_time: Some(latest_timestamp + chrono::Duration::seconds(ENTITY_EXPIRY_TTL_SECS)),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("CAMERA".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentLand),
                nationality: Some(MilViewNationality::NationalityUnitedStatesOfAmerica),
            }),
            // Overall classification of the entity's data.
            data_classification: Some(Classification {
                default: Some(ClassificationInformation {
                    level: Some(ClassificationInformationLevel::ClassificationLevelsUnclassified),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(camera_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some(INTEGRATION_NAME.to_string()),
                data_type: Some(DATA_TYPE.to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                health_status: Some(HealthHealthStatus::HealthStatusHealthy),
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
                // Per-subsystem health rolls up into the entity's overall
                // health_status; report at least the camera sensor itself.
                components: Some(vec![ComponentHealth {
                    id: Some("camera-01-eo".to_string()),
                    name: Some("EO camera sensor".to_string()),
                    health: Some(ComponentHealthHealth::HealthStatusHealthy),
                    update_time: Some(latest_timestamp),
                    ..Default::default()
                }]),
            }),
            // Declare the camera as a sensor so Lattice can render the sensor cone.
            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),
                    sensor_description: Some("EO camera, H.264".to_string()),
                    fields_of_view: Some(vec![FieldOfView {
                        // The center ray pose is an absolute ENU orientation
                        // positioned at the camera.
                        center_ray_pose: Some(EntityManagerPose {
                            pos: Some(camera_position()),
                            orientation: Some(pointing_to_quaternion_enu(
                                azimuth_deg,
                                TILT_ELEVATION_DEGREES,
                            )),
                        }),
                        horizontal_fov: Some(1.204), // ~69 deg (typical EO horizontal FoV)
                        vertical_fov: Some(0.954),   // ~54.6 deg (typical EO vertical FoV)
                        range: Some(150.0),
                        mode: Some(FieldOfViewMode::SensorModeSearch),
                        ..Default::default()
                    }]),
                    ..Default::default()
                }]),
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: Some(vec![TaskDefinition {
                    task_specification_url: Some(
                        "type.googleapis.com/<org>.<package>.<version>.<task>".to_string(),
                    ),
                }]),
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", entity_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

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

```

```go title={"Go (gRPC)"} startLine={47} maxLines={26}
// 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"
	"math"
	"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"

	"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"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	tasksv2 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/tasks/v2"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
)

const (
	cameraName      = "camera-01"
	integrationName = "lattice_video_integration"
	dataType        = "camera_video_feed"
	publishInterval = 5 * time.Second
	entityExpiryTTL = 60 * time.Second
	publishTimeout  = 10 * time.Second

	// Camera mount position.
	cameraLatitudeDegrees   = 36.66633492530301
	cameraLongitudeDegrees  = -116.9117674522639
	cameraAltitudeHaeMeters = 780.0

	// The camera pans back and forth between these compass azimuths (degrees clockwise
	// from true north), moving panStepDegrees on every update, at a fixed tilt.
	panMinAzimuthDegrees = 90.0
	panMaxAzimuthDegrees = 180.0
	panStepDegrees       = 3.0
	tiltElevationDegrees = -5.0
)

// pointingToQuaternionEnu converts a compass azimuth and elevation into the ENU quaternion
// (x, y, z, w) that rotates the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *_type.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	return &_type.Quaternion{
		X: -math.Sin(halfYaw) * math.Sin(halfPitch),
		Y: math.Cos(halfYaw) * math.Sin(halfPitch),
		Z: math.Sin(halfYaw) * math.Cos(halfPitch),
		W: math.Cos(halfYaw) * math.Cos(halfPitch),
	}
}

// panAzimuth returns the camera's azimuth after the given number of updates, sweeping
// back and forth between the minimum and maximum azimuth.
func panAzimuth(updateCount int) float64 {
	span := panMaxAzimuthDegrees - panMinAzimuthDegrees
	travel := math.Mod(float64(updateCount)*panStepDegrees, 2*span)
	if travel > span {
		travel = 2*span - travel
	}
	return panMinAzimuthDegrees + travel
}

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

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}

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

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stable entity_id derived from the camera's hardware identifier so the
	// same physical camera maps to the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(cameraName)).String()

	creationTimestamp := timestamppb.New(time.Now().UTC())

	for updateCount := 0; ; updateCount++ {
		latestTimestamp := time.Now().UTC()
		// Pan the camera and recompute where it points on every update.
		azimuthDeg := panAzimuth(updateCount)
		ctx, cancel := context.WithTimeout(context.Background(), publishTimeout)

		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "EO camera streaming live video",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Camera 01",
				AlternateIds: []*entitymanagerv1.AlternateId{
					{
						Id:   cameraName,
						Type: entitymanagerv1.AltIdType_ALT_ID_TYPE_SERIAL_NUMBER,
					},
				},
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(entityExpiryTTL)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "CAMERA",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
				Nationality: ontologyv1.Nationality_NATIONALITY_UNITED_STATES_OF_AMERICA,
			},
			// Overall classification of the entity's data.
			DataClassification: &entitymanagerv1.Classification{
				Default: &entitymanagerv1.ClassificationInformation{
					Level: entitymanagerv1.ClassificationLevels_CLASSIFICATION_LEVELS_UNCLASSIFIED,
				},
			},
			Location: &entitymanagerv1.Location{
				Position: &entitymanagerv1.Position{
					LatitudeDegrees:   cameraLatitudeDegrees,
					LongitudeDegrees:  cameraLongitudeDegrees,
					AltitudeHaeMeters: wrapperspb.Double(cameraAltitudeHaeMeters),
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  integrationName,
				DataType:         dataType,
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
				ActiveAlerts:     []*entitymanagerv1.Alert{},
				UpdateTime:       timestamppb.New(latestTimestamp),
				// Per-subsystem health rolls up into the entity's overall
				// health_status; report at least the camera sensor itself.
				Components: []*entitymanagerv1.ComponentHealth{
					{
						Id:         "camera-01-eo",
						Name:       "EO camera sensor",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
				},
			},
			Sensors: &entitymanagerv1.Sensors{
				Sensors: []*entitymanagerv1.Sensor{
					{
						SensorId:          "camera-01-eo",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						SensorDescription: "EO camera, H.264",
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								CenterRayPose: &entitymanagerv1.Pose{
									// The center ray pose is an absolute ENU orientation
									// positioned at the camera.
									Pos: &entitymanagerv1.Position{
										LatitudeDegrees:   cameraLatitudeDegrees,
										LongitudeDegrees:  cameraLongitudeDegrees,
										AltitudeHaeMeters: wrapperspb.Double(cameraAltitudeHaeMeters),
									},
									Orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees),
								},
								HorizontalFov: 1.204, // ~69 deg (typical EO horizontal FoV)
								VerticalFov:   0.954, // ~54.6 deg (typical EO vertical FoV)
								Range:         wrapperspb.Float(150.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
				},
			},
			TaskCatalog: &tasksv2.TaskCatalog{
				TaskDefinitions: []*tasksv2.TaskDefinition{
					{TaskSpecificationUrl: "type.googleapis.com/<org>.<package>.<version>.<task>"},
				},
			},
		}

		_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: entity})
		cancel()

		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

```py title={"Python (gRPC)"} startLine={73} maxLines={24}
# 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 math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, Timestamp

from anduril.entitymanager.v1.classification_pub_pb import (
    Classification,
    ClassificationInformation,
    ClassificationLevels,
)
from anduril.entitymanager.v1.entity_pub_pb import (
    Aliases,
    AlternateId,
    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.health_status_pub_pb import (
    ComponentHealth,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import AltIdType, Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment, Nationality
from anduril.tasks.v2.catalog_pub_pb import TaskCatalog, TaskDefinition
from anduril.type.coords_pub_pb import Quaternion


CAMERA_NAME = "camera-01"
INTEGRATION_NAME = "lattice_video_integration"
DATA_TYPE = "camera_video_feed"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY_TTL_SEC = 60
PUBLISH_TIMEOUT_SEC = 10

# Camera mount position.
CAMERA_LATITUDE_DEGREES = 36.66633492530301
CAMERA_LONGITUDE_DEGREES = -116.9117674522639
CAMERA_ALTITUDE_HAE_METERS = 780.0

# The camera pans back and forth between these compass azimuths (degrees clockwise
# from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
PAN_MIN_AZIMUTH_DEGREES = 90.0
PAN_MAX_AZIMUTH_DEGREES = 180.0
PAN_STEP_DEGREES = 3.0
TILT_ELEVATION_DEGREES = -5.0


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


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), already unit-normalized.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


def pan_azimuth(update_count: int) -> float:
    """Return the camera azimuth after the given number of updates, sweeping back and forth."""
    span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES
    travel = (update_count * PAN_STEP_DEGREES) % (2 * span)
    if travel > span:
        travel = 2 * span - travel
    return PAN_MIN_AZIMUTH_DEGREES + travel


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)

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

    # Stable entity_id derived from the camera's hardware identifier so the
    # same physical camera maps to the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, CAMERA_NAME))

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

    update_count = 0
    while True:
        latest = datetime.now(timezone.utc)
        # Pan the camera and recompute where it points on every update.
        azimuth_deg = pan_azimuth(update_count)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + timedelta(seconds=ENTITY_EXPIRY_TTL_SEC))

        entity = Entity(
            entity_id=entity_id,
            description="EO camera streaming live video",
            aliases=Aliases(
                name="Camera 01",
                alternate_ids=[
                    AlternateId(id=CAMERA_NAME, type=AltIdType.SERIAL_NUMBER),
                ],
            ),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.LAND,
                nationality=Nationality.UNITED_STATES_OF_AMERICA,
            ),
            # Overall classification of the entity's data.
            data_classification=Classification(
                default=ClassificationInformation(
                    level=ClassificationLevels.UNCLASSIFIED,
                ),
            ),
            location=Location(
                position=Position(
                    latitude_degrees=CAMERA_LATITUDE_DEGREES,
                    longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                    altitude_hae_meters=DoubleValue(value=CAMERA_ALTITUDE_HAE_METERS),
                ),
            ),
            provenance=Provenance(
                integration_name=INTEGRATION_NAME,
                data_type=DATA_TYPE,
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                health_status=HealthStatus.HEALTHY,
                active_alerts=[],
                update_time=latest_ts,
                # Per-subsystem health rolls up into the entity's overall
                # health_status; report at least the camera sensor itself.
                components=[
                    ComponentHealth(
                        id="camera-01-eo",
                        name="EO camera sensor",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                ],
            ),
            sensors=Sensors(
                sensors=[
                    Sensor(
                        sensor_id="camera-01-eo",
                        sensor_type=SensorType.CAMERA,
                        operational_state=OperationalState.OPERATIONAL,
                        sensor_description="EO camera, H.264",
                        fields_of_view=[
                            FieldOfView(
                                # The center ray pose is an absolute ENU orientation
                                # positioned at the camera.
                                center_ray_pose=Pose(
                                    pos=Position(
                                        latitude_degrees=CAMERA_LATITUDE_DEGREES,
                                        longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                                        altitude_hae_meters=DoubleValue(value=CAMERA_ALTITUDE_HAE_METERS),
                                    ),
                                    orientation=pointing_to_quaternion_enu(azimuth_deg, TILT_ELEVATION_DEGREES),
                                ),
                                horizontal_fov=1.204,  # ~69 deg (typical EO horizontal FoV)
                                vertical_fov=0.954,  # ~54.6 deg (typical EO vertical FoV)
                                range=FloatValue(value=150.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                ],
            ),
            task_catalog=TaskCatalog(
                task_definitions=[
                    TaskDefinition(task_specification_url="type.googleapis.com/<org>.<package>.<version>.<task>"),
                ],
            ),
        )

        try:
            client.publish_entity(
                PublishEntityRequest(entity=entity),
                timeout_ms=PUBLISH_TIMEOUT_SEC * 1000,
            )
            print(f"Publishing asset with entity ID: {entity_id}")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        update_count += 1
        time.sleep(PUBLISH_INTERVAL_SEC)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={47} maxLines={27}
// 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::{
    Aliases, AltIdType, AlternateId, Classification, ClassificationInformation,
    ClassificationLevels, ComponentHealth, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position,
    Provenance, PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment, Nationality,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::Quaternion;
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::tasks::v2::{
    TaskCatalog, TaskDefinition,
};
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};

const CAMERA_NAME: &str = "camera-01";
const INTEGRATION_NAME: &str = "lattice_video_integration";
const DATA_TYPE: &str = "camera_video_feed";
const PUBLISH_INTERVAL_SECS: u64 = 5;
const ENTITY_EXPIRY_TTL_SECS: i64 = 60;

// Camera mount position.
const CAMERA_LATITUDE_DEGREES: f64 = 36.66633492530301;
const CAMERA_LONGITUDE_DEGREES: f64 = -116.9117674522639;
const CAMERA_ALTITUDE_HAE_METERS: f64 = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
const PAN_MIN_AZIMUTH_DEGREES: f64 = 90.0;
const PAN_MAX_AZIMUTH_DEGREES: f64 = 180.0;
const PAN_STEP_DEGREES: f64 = 3.0;
const TILT_ELEVATION_DEGREES: f64 = -5.0;

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
/// The azimuth is degrees clockwise from true north and the elevation is degrees above
/// the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already
/// unit-normalized.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (std::f64::consts::FRAC_PI_2 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: -half_yaw.sin() * half_pitch.sin(),
        y: half_yaw.cos() * half_pitch.sin(),
        z: half_yaw.sin() * half_pitch.cos(),
        w: half_yaw.cos() * half_pitch.cos(),
    }
}

/// Return the camera azimuth after the given number of updates, sweeping back and forth
/// between the minimum and maximum azimuth.
fn pan_azimuth(update_count: u64) -> f64 {
    let span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
    let mut travel = (update_count as f64 * PAN_STEP_DEGREES) % (2.0 * span);
    if travel > span {
        travel = 2.0 * span - travel;
    }
    PAN_MIN_AZIMUTH_DEGREES + travel
}

/// The camera's mount position, shared by the entity location and the field of view.
fn camera_position() -> Position {
    Position {
        latitude_degrees: CAMERA_LATITUDE_DEGREES,
        longitude_degrees: CAMERA_LONGITUDE_DEGREES,
        altitude_hae_meters: Some(CAMERA_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

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");

    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)
        },
    );

    // Stable entity_id derived from the camera's hardware identifier so the
    // same physical camera maps to the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, CAMERA_NAME.as_bytes()).to_string();
    let creation_timestamp = now_timestamp();

    // Refresh the entity on a heartbeat so it does not expire while the publisher runs.
    let mut update_count: u64 = 0;
    loop {
        let latest_timestamp = now_timestamp();
        // Pan the camera and recompute where it points on every update.
        let azimuth_deg = pan_azimuth(update_count);
        update_count += 1;

        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "EO camera streaming live video".to_string(),
            aliases: Some(Aliases {
                name: "Camera 01".to_string(),
                alternate_ids: vec![AlternateId {
                    id: CAMERA_NAME.to_string(),
                    r#type: AltIdType::SerialNumber as i32,
                }],
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            // ExpiryTime is set in the future and paired with a shorter publish loop,
            // so the entity stays alive as long as the publisher runs.
            expiry_time: Some(add_seconds(&latest_timestamp, ENTITY_EXPIRY_TTL_SECS)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "CAMERA".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Land as i32,
                nationality: Nationality::UnitedStatesOfAmerica as i32,
            }),
            // Overall classification of the entity's data.
            data_classification: Some(Classification {
                default: Some(ClassificationInformation {
                    level: ClassificationLevels::Unclassified as i32,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(camera_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: INTEGRATION_NAME.to_string(),
                data_type: DATA_TYPE.to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                health_status: HealthStatus::Healthy as i32,
                active_alerts: vec![],
                update_time: Some(latest_timestamp.clone()),
                // Per-subsystem health rolls up into the entity's overall
                // health_status; report at least the camera sensor itself.
                components: vec![ComponentHealth {
                    id: "camera-01-eo".to_string(),
                    name: "EO camera sensor".to_string(),
                    health: HealthStatus::Healthy as i32,
                    update_time: Some(latest_timestamp.clone()),
                    ..Default::default()
                }],
            }),
            // Declare the camera as a sensor so Lattice can render the sensor cone.
            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,
                    sensor_description: "EO camera, H.264".to_string(),
                    fields_of_view: vec![FieldOfView {
                        // The center ray pose is an absolute ENU orientation
                        // positioned at the camera.
                        center_ray_pose: Some(Pose {
                            pos: Some(camera_position()),
                            orientation: Some(pointing_to_quaternion_enu(
                                azimuth_deg,
                                TILT_ELEVATION_DEGREES,
                            )),
                            ..Default::default()
                        }),
                        horizontal_fov: 1.204, // ~69 deg (typical EO horizontal FoV)
                        vertical_fov: 0.954,   // ~54.6 deg (typical EO vertical FoV)
                        range: Some(150.0),
                        mode: SensorMode::Search as i32,
                        ..Default::default()
                    }],
                    ..Default::default()
                }],
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: vec![TaskDefinition {
                    task_specification_url: "type.googleapis.com/<org>.<package>.<version>.<task>"
                        .to_string(),
                }],
            }),
            ..Default::default()
        };

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

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

```

Keep `sensorId` stable across updates. Tracks that the camera produces refer to it in their
`trackedBy` relationship.

#### Publish the entity

On every update, read the camera's current pan, recompute the orientation, and publish the
entity with the [`PublishEntity`](/reference/rest/entities/publish-entity) API method:

```go title={"Go (REST)"} startLine={101} maxLines={75}
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to publish a camera asset entity.
// Attaching a video to an asset requires the asset to already exist as a Lattice entity, so
// publish the camera on a heartbeat before starting an ingress stream.
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

const (
	cameraName          = "camera-01"
	integrationName     = "lattice_video_integration"
	dataType            = "camera_video_feed"
	publishInterval     = 5 * time.Second
	entityExpiryTtlSecs = 60

	// Camera mount position.
	cameraLatitudeDegrees   = 36.66633492530301
	cameraLongitudeDegrees  = -116.9117674522639
	cameraAltitudeHaeMeters = 780.0

	// The camera pans back and forth between these compass azimuths (degrees clockwise
	// from true north), moving panStepDegrees on every update, at a fixed tilt.
	panMinAzimuthDegrees = 90.0
	panMaxAzimuthDegrees = 180.0
	panStepDegrees       = 3.0
	tiltElevationDegrees = -5.0
)

// pointingToQuaternionEnu converts a compass azimuth and elevation into the ENU quaternion
// (x, y, z, w) that rotates the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *Lattice.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	return &Lattice.Quaternion{
		X: Lattice.Float64(-math.Sin(halfYaw) * math.Sin(halfPitch)),
		Y: Lattice.Float64(math.Cos(halfYaw) * math.Sin(halfPitch)),
		Z: Lattice.Float64(math.Sin(halfYaw) * math.Cos(halfPitch)),
		W: Lattice.Float64(math.Cos(halfYaw) * math.Cos(halfPitch)),
	}
}

// panAzimuth returns the camera's azimuth after the given number of updates, sweeping
// back and forth between the minimum and maximum azimuth.
func panAzimuth(updateCount int) float64 {
	span := panMaxAzimuthDegrees - panMinAzimuthDegrees
	travel := math.Mod(float64(updateCount)*panStepDegrees, 2*span)
	if travel > span {
		travel = 2*span - travel
	}
	return panMinAzimuthDegrees + travel
}

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)
	}

	// 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),
	)

	// Stable entity ID derived from the camera's hardware identifier so the same
	// physical camera maps to the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(cameraName)).String()

	creationTime := time.Now().UTC()

	// Continuously publish the entity so it does not expire.
	for updateCount := 0; ; updateCount++ {
		latestTimestamp := time.Now().UTC()
		// Pan the camera and recompute where it points on every update.
		azimuthDeg := panAzimuth(updateCount)
		ctx := context.Background()

		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("EO camera streaming live video"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Camera 01"),
				AlternateIDs: []*Lattice.AlternateID{
					{
						ID:   Lattice.String(cameraName),
						Type: Lattice.AlternateIDTypeAltIDTypeSerialNumber.Ptr(),
					},
				},
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			// ExpiryTime is set in the future and paired with a shorter publish loop,
			// so the entity stays alive as long as the publisher runs.
			ExpiryTime: Lattice.Time(latestTimestamp.Add(entityExpiryTtlSecs * time.Second)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("CAMERA"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
				Nationality: Lattice.MilViewNationalityNationalityUnitedStatesOfAmerica.Ptr(),
			},
			// Overall classification of the entity's data.
			DataClassification: &Lattice.Classification{
				Default: &Lattice.ClassificationInformation{
					Level: Lattice.ClassificationInformationLevelClassificationLevelsUnclassified.Ptr(),
				},
			},
			Location: &Lattice.Location{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(cameraLatitudeDegrees),
					LongitudeDegrees:  Lattice.Float64(cameraLongitudeDegrees),
					AltitudeHaeMeters: Lattice.Float64(cameraAltitudeHaeMeters),
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String(integrationName),
				DataType:         Lattice.String(dataType),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
				ActiveAlerts:     []*Lattice.Alert{},
				UpdateTime:       Lattice.Time(latestTimestamp),
				// Per-subsystem health rolls up into the entity's overall
				// health_status; report at least the camera sensor itself.
				Components: []*Lattice.ComponentHealth{
					{
						ID:         Lattice.String("camera-01-eo"),
						Name:       Lattice.String("EO camera sensor"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
				},
			},
			// Declare the camera as a sensor so Lattice can render the sensor cone.
			Sensors: &Lattice.Sensors{
				Sensors: []*Lattice.Sensor{
					{
						SensorID:          Lattice.String("camera-01-eo"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						SensorDescription: Lattice.String("EO camera, H.264"),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								CenterRayPose: &Lattice.EntityManagerPose{
									// The center ray pose is an absolute ENU orientation
									// positioned at the camera.
									Pos: &Lattice.Position{
										LatitudeDegrees:   Lattice.Float64(cameraLatitudeDegrees),
										LongitudeDegrees:  Lattice.Float64(cameraLongitudeDegrees),
										AltitudeHaeMeters: Lattice.Float64(cameraAltitudeHaeMeters),
									},
									Orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees),
								},
								HorizontalFov: Lattice.Float64(1.204), // ~69 deg (typical EO horizontal FoV)
								VerticalFov:   Lattice.Float64(0.954), // ~54.6 deg (typical EO vertical FoV)
								Range:         Lattice.Float64(150.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
				},
			},
			TaskCatalog: &Lattice.TaskCatalog{
				TaskDefinitions: []*Lattice.TaskDefinition{
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/<org>.<package>.<version>.<task>")},
				},
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

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

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.AlternateId;
import com.anduril.types.AlternateIdType;
import com.anduril.types.Aliases;
import com.anduril.types.Classification;
import com.anduril.types.ClassificationInformation;
import com.anduril.types.ClassificationInformationLevel;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
import com.anduril.types.MilView;
import com.anduril.types.MilViewDisposition;
import com.anduril.types.MilViewEnvironment;
import com.anduril.types.MilViewNationality;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Provenance;
import com.anduril.types.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TaskCatalog;
import com.anduril.types.TaskDefinition;

/**
 * Publishes a camera asset entity with the Lattice SDK. Attaching a video to an asset requires the
 * asset to already exist as a Lattice entity, so publish the camera on a heartbeat before starting
 * an ingress stream.
 */
public class PublishCamera {
    private static final String CAMERA_NAME = "camera-01";
    private static final String INTEGRATION_NAME = "lattice_video_integration";
    private static final String DATA_TYPE = "camera_video_feed";
    private static final long PUBLISH_INTERVAL_MS = 5000;
    private static final long ENTITY_EXPIRY_TTL_SEC = 60;

    // Camera mount position.
    private static final double CAMERA_LATITUDE_DEGREES = 36.66633492530301;
    private static final double CAMERA_LONGITUDE_DEGREES = -116.9117674522639;
    private static final double CAMERA_ALTITUDE_HAE_METERS = 780.0;

    // The camera pans back and forth between these compass azimuths (degrees clockwise
    // from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
    private static final double PAN_MIN_AZIMUTH_DEGREES = 90.0;
    private static final double PAN_MAX_AZIMUTH_DEGREES = 180.0;
    private static final double PAN_STEP_DEGREES = 3.0;
    private static final double TILT_ELEVATION_DEGREES = -5.0;

    // The RFC 4122 URL namespace, used to derive the stable UUIDv5 entity ID.
    private static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8");

    /**
     * Derives a name-based UUIDv5 (SHA-1). UUID.nameUUIDFromBytes produces v3 (MD5), which would
     * not match the entity ID the other languages derive.
     */
    private static UUID uuidV5(UUID namespace, String name) throws NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.update(ByteBuffer.allocate(16)
            .putLong(namespace.getMostSignificantBits())
            .putLong(namespace.getLeastSignificantBits())
            .array());
        byte[] hash = sha1.digest(name.getBytes(StandardCharsets.UTF_8));
        hash[6] = (byte) ((hash[6] & 0x0f) | 0x50); // version 5
        hash[8] = (byte) ((hash[8] & 0x3f) | 0x80); // RFC 4122 variant
        ByteBuffer buffer = ByteBuffer.wrap(hash);
        return new UUID(buffer.getLong(), buffer.getLong());
    }

    /**
     * Converts a compass azimuth and elevation into the ENU quaternion (x, y, z, w) that rotates
     * the sensor frame, whose +X axis is the boresight, into ENU.
     *
     * <p>The azimuth is degrees clockwise from true north and the elevation is degrees above the
     * horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
     */
    private static Quaternion pointingToQuaternionEnu(double azimuthDeg, double elevationDeg) {
        double halfYaw = (Math.PI / 2 - Math.toRadians(azimuthDeg)) / 2;
        double halfPitch = -Math.toRadians(elevationDeg) / 2;
        return Quaternion.builder()
            .x(-Math.sin(halfYaw) * Math.sin(halfPitch))
            .y(Math.cos(halfYaw) * Math.sin(halfPitch))
            .z(Math.sin(halfYaw) * Math.cos(halfPitch))
            .w(Math.cos(halfYaw) * Math.cos(halfPitch))
            .build();
    }

    /** Returns the camera azimuth after the given number of updates, sweeping back and forth. */
    private static double panAzimuth(long updateCount) {
        double span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
        double travel = (updateCount * PAN_STEP_DEGREES) % (2 * span);
        if (travel > span) {
            travel = 2 * span - travel;
        }
        return PAN_MIN_AZIMUTH_DEGREES + travel;
    }

    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;

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

            // Stable entity ID derived from the camera's hardware identifier so the same
            // physical camera maps to the same Lattice entity across restarts.
            String entityId = uuidV5(NAMESPACE_URL, CAMERA_NAME).toString();
            Instant creationTime = Instant.now();

            // Continuously publish the camera so it does not expire while the publisher runs.
            for (long updateCount = 0; ; updateCount++) {
                try {
                    Instant latestTimestamp = Instant.now();
                    // Pan the camera and recompute where it points on every update.
                    double azimuthDeg = panAzimuth(updateCount);

                    // Construct an Entity with the components Lattice needs to render a friendly
                    // land-based camera asset on the common operational picture (COP).
                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("EO camera streaming live video")
                        .aliases(Aliases.builder()
                            .name("Camera 01")
                            .alternateIds(List.of(AlternateId.builder()
                                .id(CAMERA_NAME)
                                .type(AlternateIdType.ALT_ID_TYPE_SERIAL_NUMBER)
                                .build()))
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        // ExpiryTime is set in the future and paired with a shorter publish loop,
                        // so the entity stays alive as long as the publisher runs.
                        .expiryTime(OffsetDateTime.ofInstant(
                            latestTimestamp.plus(ENTITY_EXPIRY_TTL_SEC, ChronoUnit.SECONDS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("CAMERA")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                            .nationality(MilViewNationality.NATIONALITY_UNITED_STATES_OF_AMERICA)
                            .build())
                        // Overall classification of the entity's data.
                        .dataClassification(Classification.builder()
                            .default_(ClassificationInformation.builder()
                                .level(ClassificationInformationLevel.CLASSIFICATION_LEVELS_UNCLASSIFIED)
                                .build())
                            .build())
                        .location(Location.builder()
                            .position(Position.builder()
                                .latitudeDegrees(CAMERA_LATITUDE_DEGREES)
                                .longitudeDegrees(CAMERA_LONGITUDE_DEGREES)
                                .altitudeHaeMeters(CAMERA_ALTITUDE_HAE_METERS)
                                .build())
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName(INTEGRATION_NAME)
                            .dataType(DATA_TYPE)
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(HealthHealthStatus.HEALTH_STATUS_HEALTHY)
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            // Per-subsystem health rolls up into the entity's overall
                            // health_status; report at least the camera sensor itself.
                            .components(List.of(ComponentHealth.builder()
                                .id("camera-01-eo")
                                .name("EO camera sensor")
                                .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                .build()))
                            .build())
                        // Declare the camera as a sensor so Lattice can render the sensor cone.
                        .sensors(Sensors.builder()
                            .sensors(List.of(Sensor.builder()
                                .sensorId("camera-01-eo")
                                .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                .sensorDescription("EO camera, H.264")
                                .fieldsOfView(List.of(FieldOfView.builder()
                                    // The center ray pose is an absolute ENU orientation
                                    // positioned at the camera.
                                    .centerRayPose(EntityManagerPose.builder()
                                        .pos(Position.builder()
                                            .latitudeDegrees(CAMERA_LATITUDE_DEGREES)
                                            .longitudeDegrees(CAMERA_LONGITUDE_DEGREES)
                                            .altitudeHaeMeters(CAMERA_ALTITUDE_HAE_METERS)
                                            .build())
                                        .orientation(pointingToQuaternionEnu(azimuthDeg, TILT_ELEVATION_DEGREES))
                                        .build())
                                    .horizontalFov(1.204f) // ~69 deg (typical EO horizontal FoV)
                                    .verticalFov(0.954f) // ~54.6 deg (typical EO vertical FoV)
                                    .range(150.0f)
                                    .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                    .build()))
                                .build()))
                            .build())
                        .taskCatalog(TaskCatalog.builder()
                            .taskDefinitions(List.of(TaskDefinition.builder()
                                .taskSpecificationUrl("type.googleapis.com/<org>.<package>.<version>.<task>")
                                .build()))
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset with entity ID: " + entityId);

                    Thread.sleep(PUBLISH_INTERVAL_MS);
                } catch (Exception e) {
                    System.err.println("Error publishing entity: " + e.getMessage());
                    Thread.sleep(PUBLISH_INTERVAL_MS);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={106} maxLines={75}
# This Python example uses the public Lattice REST SDK (anduril-lattice-sdk) to publish a
# camera asset entity. Attaching a video to an asset requires the asset to already exist as a
# Lattice entity, so publish the camera on a heartbeat before starting an ingress stream.

import math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    AlternateId,
    Classification,
    ClassificationInformation,
    ComponentHealth,
    FieldOfView,
    Health,
    Lattice,
    Location,
    MilView,
    Ontology,
    Position,
    Provenance,
    Quaternion,
    Sensor,
    Sensors,
    EntityManagerPose,
    TaskCatalog,
    TaskDefinition,
)

CAMERA_NAME = "camera-01"
INTEGRATION_NAME = "lattice_video_integration"
DATA_TYPE = "camera_video_feed"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY_TTL_SEC = 60

# Camera mount position.
CAMERA_LATITUDE_DEGREES = 36.66633492530301
CAMERA_LONGITUDE_DEGREES = -116.9117674522639
CAMERA_ALTITUDE_HAE_METERS = 780.0

# The camera pans back and forth between these compass azimuths (degrees clockwise
# from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
PAN_MIN_AZIMUTH_DEGREES = 90.0
PAN_MAX_AZIMUTH_DEGREES = 180.0
PAN_STEP_DEGREES = 3.0
TILT_ELEVATION_DEGREES = -5.0


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), already unit-normalized.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


def pan_azimuth(update_count: int) -> float:
    """Return the camera azimuth after the given number of updates, sweeping back and forth."""
    span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES
    travel = (update_count * PAN_STEP_DEGREES) % (2 * span)
    if travel > span:
        travel = 2 * span - travel
    return PAN_MIN_AZIMUTH_DEGREES + travel


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

    # 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.", file=sys.stderr)
        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}"},
    )

    # Stable entity_id derived from the camera's hardware identifier so the
    # same physical camera maps to the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, CAMERA_NAME))

    creation_time = datetime.now(timezone.utc)

    try:
        update_count = 0
        while True:
            latest_timestamp = datetime.now(timezone.utc)
            # Pan the camera and recompute where it points on every update.
            azimuth_deg = pan_azimuth(update_count)

            client.entities.publish_entity(
                entity_id=entity_id,
                description="EO camera streaming live video",
                aliases=Aliases(
                    name="Camera 01",
                    alternate_ids=[
                        AlternateId(id=CAMERA_NAME, type="ALT_ID_TYPE_SERIAL_NUMBER"),
                    ],
                ),
                is_live=True,
                created_time=creation_time,
                # ExpiryTime is set in the future and paired with a shorter publish loop,
                # so the entity stays alive as long as the publisher runs.
                expiry_time=latest_timestamp + timedelta(seconds=ENTITY_EXPIRY_TTL_SEC),
                ontology=Ontology(template="TEMPLATE_ASSET", platform_type="CAMERA"),
                mil_view=MilView(
                    disposition="DISPOSITION_FRIENDLY",
                    environment="ENVIRONMENT_LAND",
                    nationality="NATIONALITY_UNITED_STATES_OF_AMERICA",
                ),
                # Overall classification of the entity's data.
                data_classification=Classification(
                    default=ClassificationInformation(
                        level="CLASSIFICATION_LEVELS_UNCLASSIFIED",
                    ),
                ),
                location=Location(
                    position=Position(
                        latitude_degrees=CAMERA_LATITUDE_DEGREES,
                        longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                        altitude_hae_meters=CAMERA_ALTITUDE_HAE_METERS,
                    ),
                ),
                provenance=Provenance(
                    integration_name=INTEGRATION_NAME,
                    data_type=DATA_TYPE,
                    source_update_time=latest_timestamp,
                ),
                health=Health(
                    connection_status="CONNECTION_STATUS_ONLINE",
                    health_status="HEALTH_STATUS_HEALTHY",
                    active_alerts=[],
                    update_time=latest_timestamp,
                    # Per-subsystem health rolls up into the entity's overall
                    # health_status; report at least the camera sensor itself.
                    components=[
                        ComponentHealth(
                            id="camera-01-eo",
                            name="EO camera sensor",
                            health="HEALTH_STATUS_HEALTHY",
                            update_time=latest_timestamp,
                        ),
                    ],
                ),
                # Declare the camera as a sensor so Lattice can render the sensor cone.
                sensors=Sensors(
                    sensors=[
                        Sensor(
                            sensor_id="camera-01-eo",
                            sensor_type="SENSOR_TYPE_CAMERA",
                            operational_state="OPERATIONAL_STATE_OPERATIONAL",
                            sensor_description="EO camera, H.264",
                            fields_of_view=[
                                FieldOfView(
                                    # The center ray pose is an absolute ENU orientation
                                    # positioned at the camera.
                                    center_ray_pose=EntityManagerPose(
                                        pos=Position(
                                            latitude_degrees=CAMERA_LATITUDE_DEGREES,
                                            longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                                            altitude_hae_meters=CAMERA_ALTITUDE_HAE_METERS,
                                        ),
                                        orientation=pointing_to_quaternion_enu(azimuth_deg, TILT_ELEVATION_DEGREES),
                                    ),
                                    horizontal_fov=1.204,  # ~69 deg (typical EO horizontal FoV)
                                    vertical_fov=0.954,  # ~54.6 deg (typical EO vertical FoV)
                                    range=150.0,
                                    mode="SENSOR_MODE_SEARCH",
                                ),
                            ],
                        ),
                    ],
                ),
                task_catalog=TaskCatalog(
                    task_definitions=[
                        TaskDefinition(task_specification_url="type.googleapis.com/<org>.<package>.<version>.<task>"),
                    ],
                ),
            )
            print(f"Publishing asset with entity ID: {entity_id}")
            update_count += 1
            time.sleep(PUBLISH_INTERVAL_SEC)

    except (KeyboardInterrupt, SystemExit):
        print(">>> Exiting...")
    except Exception as error:
        print(f"Error publishing entity: {error}", file=sys.stderr)


if __name__ == "__main__":
    main()

```

```ts title={"TypeScript (REST)"} startLine={79} maxLines={75}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } 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}`  }
    }
);

const cameraName = "camera-01";
const integrationName = "lattice_video_integration";
const dataType = "camera_video_feed";
const publishIntervalMs = 5000;
const entityExpiryTtlSecs = 60;

// Camera mount position.
const cameraLatitudeDegrees = 36.66633492530301;
const cameraLongitudeDegrees = -116.9117674522639;
const cameraAltitudeHaeMeters = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving panStepDegrees on every update, at a fixed tilt.
const panMinAzimuthDegrees = 90.0;
const panMaxAzimuthDegrees = 180.0;
const panStepDegrees = 3.0;
const tiltElevationDegrees = -5.0;

const degToRad = (degrees: number) => degrees * Math.PI / 180;

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w) that rotates
// the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
function pointingToQuaternionEnu(azimuthDeg: number, elevationDeg: number) {
    const halfYaw = (Math.PI / 2 - degToRad(azimuthDeg)) / 2;
    const halfPitch = -degToRad(elevationDeg) / 2;
    return {
        x: -Math.sin(halfYaw) * Math.sin(halfPitch),
        y: Math.cos(halfYaw) * Math.sin(halfPitch),
        z: Math.sin(halfYaw) * Math.cos(halfPitch),
        w: Math.cos(halfYaw) * Math.cos(halfPitch)
    };
}

// Return the camera azimuth after the given number of updates, sweeping back and forth
// between the minimum and maximum azimuth.
function panAzimuth(updateCount: number): number {
    const span = panMaxAzimuthDegrees - panMinAzimuthDegrees;
    let travel = (updateCount * panStepDegrees) % (2 * span);
    if (travel > span) {
        travel = 2 * span - travel;
    }
    return panMinAzimuthDegrees + travel;
}

let updateCount = 0;

// Stable entity ID derived from the camera's hardware identifier so the same
// physical camera maps to the same Lattice entity across restarts.
const entityId = uuidv5(cameraName, uuidv5.URL);
const creationTime = new Date().toISOString();

async function App() {
    const latestTimestamp = new Date();
    // Pan the camera and recompute where it points on every update.
    const azimuthDeg = panAzimuth(updateCount);
    updateCount += 1;
    try {
        // Attaching a video to an asset requires the asset to already exist as a Lattice
        // entity, so publish the camera on a heartbeat before starting an ingress stream.
        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "EO camera streaming live video",
                aliases: {
                    name: "Camera 01",
                    alternateIds: [
                        { id: cameraName, type: "ALT_ID_TYPE_SERIAL_NUMBER" }
                    ]
                },
                isLive: true,
                createdTime: creationTime,
                // ExpiryTime is set in the future and paired with a shorter publish loop,
                // so the entity stays alive as long as the publisher runs.
                expiryTime: new Date(latestTimestamp.getTime() + entityExpiryTtlSecs * 1000).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "CAMERA"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_LAND",
                    nationality: "NATIONALITY_UNITED_STATES_OF_AMERICA"
                },
                // Overall classification of the entity's data.
                dataClassification: {
                    default: {
                        level: "CLASSIFICATION_LEVELS_UNCLASSIFIED"
                    }
                },
                location: {
                    position: {
                        latitudeDegrees: cameraLatitudeDegrees,
                        longitudeDegrees: cameraLongitudeDegrees,
                        altitudeHaeMeters: cameraAltitudeHaeMeters
                    }
                },
                provenance: {
                    integrationName: integrationName,
                    dataType: dataType,
                    sourceUpdateTime: latestTimestamp.toISOString()
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    healthStatus: "HEALTH_STATUS_HEALTHY",
                    activeAlerts: [],
                    updateTime: latestTimestamp.toISOString(),
                    // Per-subsystem health rolls up into the entity's overall
                    // healthStatus; report at least the camera sensor itself.
                    components: [
                        {
                            id: "camera-01-eo",
                            name: "EO camera sensor",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        }
                    ]
                },
                // Declare the camera as a sensor so Lattice can render the sensor cone.
                sensors: {
                    sensors: [
                        {
                            sensorId: "camera-01-eo",
                            sensorType: "SENSOR_TYPE_CAMERA",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            sensorDescription: "EO camera, H.264",
                            fieldsOfView: [
                                {
                                    // The center ray pose is an absolute ENU orientation
                                    // positioned at the camera.
                                    centerRayPose: {
                                        pos: {
                                            latitudeDegrees: cameraLatitudeDegrees,
                                            longitudeDegrees: cameraLongitudeDegrees,
                                            altitudeHaeMeters: cameraAltitudeHaeMeters
                                        },
                                        orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees)
                                    },
                                    horizontalFov: 1.204, // ~69 deg (typical EO horizontal FoV)
                                    verticalFov: 0.954, // ~54.6 deg (typical EO vertical FoV)
                                    range: 150.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        }
                    ]
                },
                taskCatalog: {
                    taskDefinitions: [
                        { taskSpecificationUrl: "type.googleapis.com/<org>.<package>.<version>.<task>" }
                    ]
                }
            }
        );
        console.log(`Publishing asset with entity ID: ${entityId}`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}

(async function runIndefinitely() {
    while (true) {
        await App();
        await new Promise(resolve => setTimeout(resolve, publishIntervalMs));
    }
})();

```

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

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

const CAMERA_NAME: &str = "camera-01";
const INTEGRATION_NAME: &str = "lattice_video_integration";
const DATA_TYPE: &str = "camera_video_feed";
const PUBLISH_INTERVAL_SECS: u64 = 5;
const ENTITY_EXPIRY_TTL_SECS: i64 = 60;

// Camera mount position.
const CAMERA_LATITUDE_DEGREES: f64 = 36.66633492530301;
const CAMERA_LONGITUDE_DEGREES: f64 = -116.9117674522639;
const CAMERA_ALTITUDE_HAE_METERS: f64 = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
const PAN_MIN_AZIMUTH_DEGREES: f64 = 90.0;
const PAN_MAX_AZIMUTH_DEGREES: f64 = 180.0;
const PAN_STEP_DEGREES: f64 = 3.0;
const TILT_ELEVATION_DEGREES: f64 = -5.0;

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
/// The azimuth is degrees clockwise from true north and the elevation is degrees above
/// the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already
/// unit-normalized.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (std::f64::consts::FRAC_PI_2 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: Some(-half_yaw.sin() * half_pitch.sin()),
        y: Some(half_yaw.cos() * half_pitch.sin()),
        z: Some(half_yaw.sin() * half_pitch.cos()),
        w: Some(half_yaw.cos() * half_pitch.cos()),
    }
}

/// Return the camera azimuth after the given number of updates, sweeping back and forth
/// between the minimum and maximum azimuth.
fn pan_azimuth(update_count: u64) -> f64 {
    let span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
    let mut travel = (update_count as f64 * PAN_STEP_DEGREES) % (2.0 * span);
    if travel > span {
        travel = 2.0 * span - travel;
    }
    PAN_MIN_AZIMUTH_DEGREES + travel
}

/// The camera's mount position, shared by the entity location and the field of view.
fn camera_position() -> Position {
    Position {
        latitude_degrees: Some(CAMERA_LATITUDE_DEGREES),
        longitude_degrees: Some(CAMERA_LONGITUDE_DEGREES),
        altitude_hae_meters: Some(CAMERA_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

#[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)?;

    // Stable entity_id derived from the camera's hardware identifier so the
    // same physical camera maps to the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, CAMERA_NAME.as_bytes()).to_string();
    let creation_time = Utc::now().fixed_offset();

    // Refresh the entity on a heartbeat so it does not expire while the publisher runs.
    let mut update_count: u64 = 0;
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        // Pan the camera and recompute where it points on every update.
        let azimuth_deg = pan_azimuth(update_count);
        update_count += 1;

        let entity = Entity {
            entity_id: Some(entity_id.clone()),
            description: Some("EO camera streaming live video".to_string()),
            aliases: Some(Aliases {
                name: Some("Camera 01".to_string()),
                alternate_ids: Some(vec![AlternateId {
                    id: Some(CAMERA_NAME.to_string()),
                    r#type: Some(AlternateIdType::AltIdTypeSerialNumber),
                }]),
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            // ExpiryTime is set in the future and paired with a shorter publish loop,
            // so the entity stays alive as long as the publisher runs.
            expiry_time: Some(latest_timestamp + chrono::Duration::seconds(ENTITY_EXPIRY_TTL_SECS)),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("CAMERA".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentLand),
                nationality: Some(MilViewNationality::NationalityUnitedStatesOfAmerica),
            }),
            // Overall classification of the entity's data.
            data_classification: Some(Classification {
                default: Some(ClassificationInformation {
                    level: Some(ClassificationInformationLevel::ClassificationLevelsUnclassified),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(camera_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some(INTEGRATION_NAME.to_string()),
                data_type: Some(DATA_TYPE.to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                health_status: Some(HealthHealthStatus::HealthStatusHealthy),
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
                // Per-subsystem health rolls up into the entity's overall
                // health_status; report at least the camera sensor itself.
                components: Some(vec![ComponentHealth {
                    id: Some("camera-01-eo".to_string()),
                    name: Some("EO camera sensor".to_string()),
                    health: Some(ComponentHealthHealth::HealthStatusHealthy),
                    update_time: Some(latest_timestamp),
                    ..Default::default()
                }]),
            }),
            // Declare the camera as a sensor so Lattice can render the sensor cone.
            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),
                    sensor_description: Some("EO camera, H.264".to_string()),
                    fields_of_view: Some(vec![FieldOfView {
                        // The center ray pose is an absolute ENU orientation
                        // positioned at the camera.
                        center_ray_pose: Some(EntityManagerPose {
                            pos: Some(camera_position()),
                            orientation: Some(pointing_to_quaternion_enu(
                                azimuth_deg,
                                TILT_ELEVATION_DEGREES,
                            )),
                        }),
                        horizontal_fov: Some(1.204), // ~69 deg (typical EO horizontal FoV)
                        vertical_fov: Some(0.954),   // ~54.6 deg (typical EO vertical FoV)
                        range: Some(150.0),
                        mode: Some(FieldOfViewMode::SensorModeSearch),
                        ..Default::default()
                    }]),
                    ..Default::default()
                }]),
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: Some(vec![TaskDefinition {
                    task_specification_url: Some(
                        "type.googleapis.com/<org>.<package>.<version>.<task>".to_string(),
                    ),
                }]),
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", entity_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

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

```

```go title={"Go (gRPC)"} startLine={108} maxLines={75}
// 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"
	"math"
	"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"

	"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"
	ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
	tasksv2 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/tasks/v2"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
)

const (
	cameraName      = "camera-01"
	integrationName = "lattice_video_integration"
	dataType        = "camera_video_feed"
	publishInterval = 5 * time.Second
	entityExpiryTTL = 60 * time.Second
	publishTimeout  = 10 * time.Second

	// Camera mount position.
	cameraLatitudeDegrees   = 36.66633492530301
	cameraLongitudeDegrees  = -116.9117674522639
	cameraAltitudeHaeMeters = 780.0

	// The camera pans back and forth between these compass azimuths (degrees clockwise
	// from true north), moving panStepDegrees on every update, at a fixed tilt.
	panMinAzimuthDegrees = 90.0
	panMaxAzimuthDegrees = 180.0
	panStepDegrees       = 3.0
	tiltElevationDegrees = -5.0
)

// pointingToQuaternionEnu converts a compass azimuth and elevation into the ENU quaternion
// (x, y, z, w) that rotates the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already unit-normalized.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *_type.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	return &_type.Quaternion{
		X: -math.Sin(halfYaw) * math.Sin(halfPitch),
		Y: math.Cos(halfYaw) * math.Sin(halfPitch),
		Z: math.Sin(halfYaw) * math.Cos(halfPitch),
		W: math.Cos(halfYaw) * math.Cos(halfPitch),
	}
}

// panAzimuth returns the camera's azimuth after the given number of updates, sweeping
// back and forth between the minimum and maximum azimuth.
func panAzimuth(updateCount int) float64 {
	span := panMaxAzimuthDegrees - panMinAzimuthDegrees
	travel := math.Mod(float64(updateCount)*panStepDegrees, 2*span)
	if travel > span {
		travel = 2*span - travel
	}
	return panMinAzimuthDegrees + travel
}

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

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}

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

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stable entity_id derived from the camera's hardware identifier so the
	// same physical camera maps to the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(cameraName)).String()

	creationTimestamp := timestamppb.New(time.Now().UTC())

	for updateCount := 0; ; updateCount++ {
		latestTimestamp := time.Now().UTC()
		// Pan the camera and recompute where it points on every update.
		azimuthDeg := panAzimuth(updateCount)
		ctx, cancel := context.WithTimeout(context.Background(), publishTimeout)

		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "EO camera streaming live video",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Camera 01",
				AlternateIds: []*entitymanagerv1.AlternateId{
					{
						Id:   cameraName,
						Type: entitymanagerv1.AltIdType_ALT_ID_TYPE_SERIAL_NUMBER,
					},
				},
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(entityExpiryTTL)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "CAMERA",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
				Nationality: ontologyv1.Nationality_NATIONALITY_UNITED_STATES_OF_AMERICA,
			},
			// Overall classification of the entity's data.
			DataClassification: &entitymanagerv1.Classification{
				Default: &entitymanagerv1.ClassificationInformation{
					Level: entitymanagerv1.ClassificationLevels_CLASSIFICATION_LEVELS_UNCLASSIFIED,
				},
			},
			Location: &entitymanagerv1.Location{
				Position: &entitymanagerv1.Position{
					LatitudeDegrees:   cameraLatitudeDegrees,
					LongitudeDegrees:  cameraLongitudeDegrees,
					AltitudeHaeMeters: wrapperspb.Double(cameraAltitudeHaeMeters),
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  integrationName,
				DataType:         dataType,
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
				ActiveAlerts:     []*entitymanagerv1.Alert{},
				UpdateTime:       timestamppb.New(latestTimestamp),
				// Per-subsystem health rolls up into the entity's overall
				// health_status; report at least the camera sensor itself.
				Components: []*entitymanagerv1.ComponentHealth{
					{
						Id:         "camera-01-eo",
						Name:       "EO camera sensor",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
				},
			},
			Sensors: &entitymanagerv1.Sensors{
				Sensors: []*entitymanagerv1.Sensor{
					{
						SensorId:          "camera-01-eo",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						SensorDescription: "EO camera, H.264",
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								CenterRayPose: &entitymanagerv1.Pose{
									// The center ray pose is an absolute ENU orientation
									// positioned at the camera.
									Pos: &entitymanagerv1.Position{
										LatitudeDegrees:   cameraLatitudeDegrees,
										LongitudeDegrees:  cameraLongitudeDegrees,
										AltitudeHaeMeters: wrapperspb.Double(cameraAltitudeHaeMeters),
									},
									Orientation: pointingToQuaternionEnu(azimuthDeg, tiltElevationDegrees),
								},
								HorizontalFov: 1.204, // ~69 deg (typical EO horizontal FoV)
								VerticalFov:   0.954, // ~54.6 deg (typical EO vertical FoV)
								Range:         wrapperspb.Float(150.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
				},
			},
			TaskCatalog: &tasksv2.TaskCatalog{
				TaskDefinitions: []*tasksv2.TaskDefinition{
					{TaskSpecificationUrl: "type.googleapis.com/<org>.<package>.<version>.<task>"},
				},
			},
		}

		_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: entity})
		cancel()

		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

```py title={"Python (gRPC)"} startLine={120} maxLines={75}
# 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 math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, Timestamp

from anduril.entitymanager.v1.classification_pub_pb import (
    Classification,
    ClassificationInformation,
    ClassificationLevels,
)
from anduril.entitymanager.v1.entity_pub_pb import (
    Aliases,
    AlternateId,
    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.health_status_pub_pb import (
    ComponentHealth,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import AltIdType, Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment, Nationality
from anduril.tasks.v2.catalog_pub_pb import TaskCatalog, TaskDefinition
from anduril.type.coords_pub_pb import Quaternion


CAMERA_NAME = "camera-01"
INTEGRATION_NAME = "lattice_video_integration"
DATA_TYPE = "camera_video_feed"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY_TTL_SEC = 60
PUBLISH_TIMEOUT_SEC = 10

# Camera mount position.
CAMERA_LATITUDE_DEGREES = 36.66633492530301
CAMERA_LONGITUDE_DEGREES = -116.9117674522639
CAMERA_ALTITUDE_HAE_METERS = 780.0

# The camera pans back and forth between these compass azimuths (degrees clockwise
# from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
PAN_MIN_AZIMUTH_DEGREES = 90.0
PAN_MAX_AZIMUTH_DEGREES = 180.0
PAN_STEP_DEGREES = 3.0
TILT_ELEVATION_DEGREES = -5.0


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


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), already unit-normalized.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


def pan_azimuth(update_count: int) -> float:
    """Return the camera azimuth after the given number of updates, sweeping back and forth."""
    span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES
    travel = (update_count * PAN_STEP_DEGREES) % (2 * span)
    if travel > span:
        travel = 2 * span - travel
    return PAN_MIN_AZIMUTH_DEGREES + travel


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)

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

    # Stable entity_id derived from the camera's hardware identifier so the
    # same physical camera maps to the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, CAMERA_NAME))

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

    update_count = 0
    while True:
        latest = datetime.now(timezone.utc)
        # Pan the camera and recompute where it points on every update.
        azimuth_deg = pan_azimuth(update_count)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + timedelta(seconds=ENTITY_EXPIRY_TTL_SEC))

        entity = Entity(
            entity_id=entity_id,
            description="EO camera streaming live video",
            aliases=Aliases(
                name="Camera 01",
                alternate_ids=[
                    AlternateId(id=CAMERA_NAME, type=AltIdType.SERIAL_NUMBER),
                ],
            ),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="CAMERA"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.LAND,
                nationality=Nationality.UNITED_STATES_OF_AMERICA,
            ),
            # Overall classification of the entity's data.
            data_classification=Classification(
                default=ClassificationInformation(
                    level=ClassificationLevels.UNCLASSIFIED,
                ),
            ),
            location=Location(
                position=Position(
                    latitude_degrees=CAMERA_LATITUDE_DEGREES,
                    longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                    altitude_hae_meters=DoubleValue(value=CAMERA_ALTITUDE_HAE_METERS),
                ),
            ),
            provenance=Provenance(
                integration_name=INTEGRATION_NAME,
                data_type=DATA_TYPE,
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                health_status=HealthStatus.HEALTHY,
                active_alerts=[],
                update_time=latest_ts,
                # Per-subsystem health rolls up into the entity's overall
                # health_status; report at least the camera sensor itself.
                components=[
                    ComponentHealth(
                        id="camera-01-eo",
                        name="EO camera sensor",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                ],
            ),
            sensors=Sensors(
                sensors=[
                    Sensor(
                        sensor_id="camera-01-eo",
                        sensor_type=SensorType.CAMERA,
                        operational_state=OperationalState.OPERATIONAL,
                        sensor_description="EO camera, H.264",
                        fields_of_view=[
                            FieldOfView(
                                # The center ray pose is an absolute ENU orientation
                                # positioned at the camera.
                                center_ray_pose=Pose(
                                    pos=Position(
                                        latitude_degrees=CAMERA_LATITUDE_DEGREES,
                                        longitude_degrees=CAMERA_LONGITUDE_DEGREES,
                                        altitude_hae_meters=DoubleValue(value=CAMERA_ALTITUDE_HAE_METERS),
                                    ),
                                    orientation=pointing_to_quaternion_enu(azimuth_deg, TILT_ELEVATION_DEGREES),
                                ),
                                horizontal_fov=1.204,  # ~69 deg (typical EO horizontal FoV)
                                vertical_fov=0.954,  # ~54.6 deg (typical EO vertical FoV)
                                range=FloatValue(value=150.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                ],
            ),
            task_catalog=TaskCatalog(
                task_definitions=[
                    TaskDefinition(task_specification_url="type.googleapis.com/<org>.<package>.<version>.<task>"),
                ],
            ),
        )

        try:
            client.publish_entity(
                PublishEntityRequest(entity=entity),
                timeout_ms=PUBLISH_TIMEOUT_SEC * 1000,
            )
            print(f"Publishing asset with entity ID: {entity_id}")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        update_count += 1
        time.sleep(PUBLISH_INTERVAL_SEC)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={145} maxLines={75}
// 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::{
    Aliases, AltIdType, AlternateId, Classification, ClassificationInformation,
    ClassificationLevels, ComponentHealth, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position,
    Provenance, PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment, Nationality,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::Quaternion;
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::tasks::v2::{
    TaskCatalog, TaskDefinition,
};
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};

const CAMERA_NAME: &str = "camera-01";
const INTEGRATION_NAME: &str = "lattice_video_integration";
const DATA_TYPE: &str = "camera_video_feed";
const PUBLISH_INTERVAL_SECS: u64 = 5;
const ENTITY_EXPIRY_TTL_SECS: i64 = 60;

// Camera mount position.
const CAMERA_LATITUDE_DEGREES: f64 = 36.66633492530301;
const CAMERA_LONGITUDE_DEGREES: f64 = -116.9117674522639;
const CAMERA_ALTITUDE_HAE_METERS: f64 = 780.0;

// The camera pans back and forth between these compass azimuths (degrees clockwise
// from true north), moving PAN_STEP_DEGREES on every update, at a fixed tilt.
const PAN_MIN_AZIMUTH_DEGREES: f64 = 90.0;
const PAN_MAX_AZIMUTH_DEGREES: f64 = 180.0;
const PAN_STEP_DEGREES: f64 = 3.0;
const TILT_ELEVATION_DEGREES: f64 = -5.0;

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
/// The azimuth is degrees clockwise from true north and the elevation is degrees above
/// the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation), which is already
/// unit-normalized.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (std::f64::consts::FRAC_PI_2 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: -half_yaw.sin() * half_pitch.sin(),
        y: half_yaw.cos() * half_pitch.sin(),
        z: half_yaw.sin() * half_pitch.cos(),
        w: half_yaw.cos() * half_pitch.cos(),
    }
}

/// Return the camera azimuth after the given number of updates, sweeping back and forth
/// between the minimum and maximum azimuth.
fn pan_azimuth(update_count: u64) -> f64 {
    let span = PAN_MAX_AZIMUTH_DEGREES - PAN_MIN_AZIMUTH_DEGREES;
    let mut travel = (update_count as f64 * PAN_STEP_DEGREES) % (2.0 * span);
    if travel > span {
        travel = 2.0 * span - travel;
    }
    PAN_MIN_AZIMUTH_DEGREES + travel
}

/// The camera's mount position, shared by the entity location and the field of view.
fn camera_position() -> Position {
    Position {
        latitude_degrees: CAMERA_LATITUDE_DEGREES,
        longitude_degrees: CAMERA_LONGITUDE_DEGREES,
        altitude_hae_meters: Some(CAMERA_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

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");

    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)
        },
    );

    // Stable entity_id derived from the camera's hardware identifier so the
    // same physical camera maps to the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, CAMERA_NAME.as_bytes()).to_string();
    let creation_timestamp = now_timestamp();

    // Refresh the entity on a heartbeat so it does not expire while the publisher runs.
    let mut update_count: u64 = 0;
    loop {
        let latest_timestamp = now_timestamp();
        // Pan the camera and recompute where it points on every update.
        let azimuth_deg = pan_azimuth(update_count);
        update_count += 1;

        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "EO camera streaming live video".to_string(),
            aliases: Some(Aliases {
                name: "Camera 01".to_string(),
                alternate_ids: vec![AlternateId {
                    id: CAMERA_NAME.to_string(),
                    r#type: AltIdType::SerialNumber as i32,
                }],
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            // ExpiryTime is set in the future and paired with a shorter publish loop,
            // so the entity stays alive as long as the publisher runs.
            expiry_time: Some(add_seconds(&latest_timestamp, ENTITY_EXPIRY_TTL_SECS)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "CAMERA".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Land as i32,
                nationality: Nationality::UnitedStatesOfAmerica as i32,
            }),
            // Overall classification of the entity's data.
            data_classification: Some(Classification {
                default: Some(ClassificationInformation {
                    level: ClassificationLevels::Unclassified as i32,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(camera_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: INTEGRATION_NAME.to_string(),
                data_type: DATA_TYPE.to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                health_status: HealthStatus::Healthy as i32,
                active_alerts: vec![],
                update_time: Some(latest_timestamp.clone()),
                // Per-subsystem health rolls up into the entity's overall
                // health_status; report at least the camera sensor itself.
                components: vec![ComponentHealth {
                    id: "camera-01-eo".to_string(),
                    name: "EO camera sensor".to_string(),
                    health: HealthStatus::Healthy as i32,
                    update_time: Some(latest_timestamp.clone()),
                    ..Default::default()
                }],
            }),
            // Declare the camera as a sensor so Lattice can render the sensor cone.
            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,
                    sensor_description: "EO camera, H.264".to_string(),
                    fields_of_view: vec![FieldOfView {
                        // The center ray pose is an absolute ENU orientation
                        // positioned at the camera.
                        center_ray_pose: Some(Pose {
                            pos: Some(camera_position()),
                            orientation: Some(pointing_to_quaternion_enu(
                                azimuth_deg,
                                TILT_ELEVATION_DEGREES,
                            )),
                            ..Default::default()
                        }),
                        horizontal_fov: 1.204, // ~69 deg (typical EO horizontal FoV)
                        vertical_fov: 0.954,   // ~54.6 deg (typical EO vertical FoV)
                        range: Some(150.0),
                        mode: SensorMode::Search as i32,
                        ..Default::default()
                    }],
                    ..Default::default()
                }],
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: vec![TaskDefinition {
                    task_specification_url: "type.googleapis.com/<org>.<package>.<version>.<task>"
                        .to_string(),
                }],
            }),
            ..Default::default()
        };

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

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

```

Republish the field of view whenever the camera pans, tilts, or zooms, so the cone in the
Lattice UI matches where the camera points.

## Example: Multi-panel radar

A ground radar often consists of several fixed panels that together cover 360 degrees. Model panels
mounted on the same platform, or operating together as one radar system, as **one asset entity**,
and list each panel as a sensor in `sensors.sensors`. Use separate asset entities only when radars
are far apart or operate as independent systems.

This example publishes a radar with four panels facing north, east, south, and west. The integration
reports each panel's state and coverage, and one panel periodically reports reduced capability.

#### Define the entity

Define the radar's components. At one instant, while Panel 3 reports reduced capability, you get
the following entity object. Panels 2 to 4 follow the same shape as Panel 1:

**`radar.json`**

```json maxLines=25 title="radar.json"
{
  "entityId": "1146af7c-80a0-58f7-ba81-06d2f1abcdaa",
  "description": "Four-panel radar asset",
  "isLive": true,
  "createdTime": "2026-11-06T18:55:00Z",
  "expiryTime": "2026-11-06T19:05:00Z",
  "aliases": { "name": "Radar 1" },
  "ontology": { "template": "TEMPLATE_ASSET", "platformType": "RADAR" },
  "milView": { "disposition": "DISPOSITION_FRIENDLY", "environment": "ENVIRONMENT_LAND" },
  "location": {
    "position": { "latitudeDegrees": 34.0, "longitudeDegrees": -118.0, "altitudeHaeMeters": 100.0 }
  },
  "health": {
    "connectionStatus": "CONNECTION_STATUS_ONLINE",
    "healthStatus": "HEALTH_STATUS_WARN",
    "components": [
      {
        "id": "panel-1",
        "name": "Panel 1",
        "health": "HEALTH_STATUS_HEALTHY",
        "messages": [{ "status": "HEALTH_STATUS_HEALTHY", "message": "Panel 1 is operating normally." }]
      },
      {
        "id": "panel-3",
        "name": "Panel 3",
        "health": "HEALTH_STATUS_WARN",
        "messages": [{ "status": "HEALTH_STATUS_WARN", "message": "Panel 3 is operating with reduced capability." }]
      },
      {
        "id": "radar-controller",
        "name": "Radar controller",
        "health": "HEALTH_STATUS_HEALTHY"
      }
    ],
    "activeAlerts": []
  },
  "sensors": {
    "sensors": [
      {
        "sensorId": "panel-1",
        "sensorDescription": "Panel 1",
        "sensorType": "SENSOR_TYPE_RADAR",
        "operationalState": "OPERATIONAL_STATE_OPERATIONAL",
        "fieldsOfView": [
          {
            "fovId": 1,
            "centerRayPose": {
              "pos": { "latitudeDegrees": 34.0, "longitudeDegrees": -118.0, "altitudeHaeMeters": 100.0 },
              "orientation": { "x": 0.06163, "y": -0.06163, "z": 0.70442, "w": 0.70442 }
            },
            "horizontalFov": 1.5708,
            "verticalFov": 0.5236,
            "range": 10000,
            "mode": "SENSOR_MODE_SEARCH"
          }
        ]
      },
      {
        "sensorId": "panel-3",
        "sensorDescription": "Panel 3",
        "sensorType": "SENSOR_TYPE_RADAR",
        "operationalState": "OPERATIONAL_STATE_DEGRADED",
        "fieldsOfView": [
          {
            "fovId": 1,
            "centerRayPose": {
              "pos": { "latitudeDegrees": 34.0, "longitudeDegrees": -118.0, "altitudeHaeMeters": 100.0 },
              "orientation": { "x": -0.06163, "y": -0.06163, "z": -0.70442, "w": 0.70442 }
            },
            "horizontalFov": 1.5708,
            "verticalFov": 0.5236,
            "range": 10000,
            "mode": "SENSOR_MODE_SEARCH"
          }
        ]
      }
    ]
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "radar_asset",
    "sourceUpdateTime": "2026-11-06T19:00:00Z"
  }
}
```

#### Describe each panel

Give each panel a stable `sensorId`, a short human-readable name in `sensorDescription`, and
`sensorType` set to `SENSOR_TYPE_RADAR`. Keep the `sensorId` values unchanged across updates:
tracks and tasks refer to individual panels by these IDs.

Each panel's field of view starts at the radar's position and points along the panel's
boresight. The example defines the panels as a table of IDs, names, and boresight azimuths, and
converts each azimuth and a 10-degree upward tilt into a quaternion:

```go title={"Go (REST)"} startLine={45} maxLines={24}
// This Go example publishes a four-panel radar as one asset entity. Each panel
// is a sensor on the asset with its own field of view.
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

const (
	radarName       = "radar-01"
	integrationName = "your_integration_name"
	dataType        = "radar_asset"
	publishInterval = 5 * time.Second
	entityExpiry    = 5 * time.Minute

	// Fixed radar position.
	radarLat = 34.0
	radarLon = -118.0
	radarHae = 100.0

	// Elevation of every panel boresight, in degrees above the horizon.
	panelElevationDeg = 10.0

	// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
	degradedFlipEvery = 3
)

// panel describes one radar panel and the compass azimuth its boresight faces.
type panel struct {
	id          string
	description string
	azimuthDeg  float64
}

var panels = []panel{
	{"panel-1", "Panel 1", 0},
	{"panel-2", "Panel 2", 90},
	{"panel-3", "Panel 3", 180},
	{"panel-4", "Panel 4", 270},
}

// pointingToQuaternionEnu returns the ENU orientation that points a sensor's
// +X boresight at a compass azimuth (degrees clockwise from true north) and an
// elevation (degrees above the horizon). The quaternion is
// qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
// azimuth of 90 and an elevation of 0 gives the identity.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *Lattice.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	sz, cz := math.Sin(halfYaw), math.Cos(halfYaw)
	sy, cy := math.Sin(halfPitch), math.Cos(halfPitch)
	return &Lattice.Quaternion{
		X: Lattice.Float64(-sz * sy),
		Y: Lattice.Float64(cz * sy),
		Z: Lattice.Float64(sz * cy),
		W: Lattice.Float64(cz * cy),
	}
}

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)
	}

	// 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),
	)

	// Stable entity ID derived from the radar's name so the same radar maps to
	// the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(radarName)).String()

	creationTime := time.Now().UTC()

	// Continuously publish the entity so it does not expire.
	for update := 0; ; update++ {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Simulate telemetry: panel-3 alternates between OPERATIONAL and
		// DEGRADED. A real integration maps hardware telemetry to these
		// states instead of using a timer.
		panel3Degraded := (update/degradedFlipEvery)%2 == 1

		// Build one sensor and one health component per panel. The panel ID
		// links the two.
		sensors := []*Lattice.Sensor{}
		components := []*Lattice.ComponentHealth{}
		anyDegraded := false
		for _, p := range panels {
			degraded := p.id == "panel-3" && panel3Degraded
			anyDegraded = anyDegraded || degraded

			operationalState := Lattice.SensorOperationalStateOperationalStateOperational
			panelHealth := Lattice.ComponentHealthHealthHealthStatusHealthy
			messageStatus := Lattice.ComponentMessageStatusHealthStatusHealthy
			message := p.description + " is operating normally."
			if degraded {
				operationalState = Lattice.SensorOperationalStateOperationalStateDegraded
				panelHealth = Lattice.ComponentHealthHealthHealthStatusWarn
				messageStatus = Lattice.ComponentMessageStatusHealthStatusWarn
				message = p.description + " is operating with reduced capability."
			}

			sensors = append(sensors, &Lattice.Sensor{
				SensorID:          Lattice.String(p.id),
				SensorDescription: Lattice.String(p.description),
				SensorType:        Lattice.SensorSensorTypeSensorTypeRadar.Ptr(),
				OperationalState:  operationalState.Ptr(),
				FieldsOfView: []*Lattice.FieldOfView{
					{
						FovID: Lattice.Int(1),
						CenterRayPose: &Lattice.EntityManagerPose{
							Pos: &Lattice.Position{
								LatitudeDegrees:   Lattice.Float64(radarLat),
								LongitudeDegrees:  Lattice.Float64(radarLon),
								AltitudeHaeMeters: Lattice.Float64(radarHae),
							},
							Orientation: pointingToQuaternionEnu(p.azimuthDeg, panelElevationDeg),
						},
						HorizontalFov: Lattice.Float64(math.Pi / 2),
						VerticalFov:   Lattice.Float64(math.Pi / 6),
						Range:         Lattice.Float64(10000.0),
						Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
					},
				},
			})
			components = append(components, &Lattice.ComponentHealth{
				ID:     Lattice.String(p.id),
				Name:   Lattice.String(p.description),
				Health: panelHealth.Ptr(),
				Messages: []*Lattice.ComponentMessage{
					{Status: messageStatus.Ptr(), Message: Lattice.String(message)},
				},
				UpdateTime: Lattice.Time(latestTimestamp),
			})
		}
		components = append(components, &Lattice.ComponentHealth{
			ID:     Lattice.String("radar-controller"),
			Name:   Lattice.String("Radar controller"),
			Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
			Messages: []*Lattice.ComponentMessage{
				{
					Status:  Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
					Message: Lattice.String("Radar controller is operating normally."),
				},
			},
			UpdateTime: Lattice.Time(latestTimestamp),
		})

		// The entity is WARN when any panel is degraded.
		healthStatus := Lattice.HealthHealthStatusHealthStatusHealthy
		if anyDegraded {
			healthStatus = Lattice.HealthHealthStatusHealthStatusWarn
		}

		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Four-panel radar asset"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Radar 1"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(entityExpiry)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("RADAR"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
			},
			Location: &Lattice.Location{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(radarLat),
					LongitudeDegrees:  Lattice.Float64(radarLon),
					AltitudeHaeMeters: Lattice.Float64(radarHae),
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String(integrationName),
				DataType:         Lattice.String(dataType),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     healthStatus.Ptr(),
				Components:       components,
				ActiveAlerts:     []*Lattice.Alert{},
				UpdateTime:       Lattice.Time(latestTimestamp),
			},
			// Publish all panels as sensors on one asset entity.
			Sensors: &Lattice.Sensors{Sensors: sensors},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

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

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.Aliases;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.ComponentMessage;
import com.anduril.types.ComponentMessageStatus;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
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.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;

/**
 * Publishes a four-panel radar as one asset entity with the Lattice SDK. Each panel is a sensor on
 * the asset with its own field of view.
 */
public class PublishAssetRadar {
    private static final String RADAR_NAME = "radar-01";
    private static final String INTEGRATION_NAME = "your_integration_name";
    private static final String DATA_TYPE = "radar_asset";
    private static final long PUBLISH_INTERVAL_MS = 5000;
    private static final long ENTITY_EXPIRY_MIN = 5;

    // Fixed radar position.
    private static final double RADAR_LAT = 34.0;
    private static final double RADAR_LON = -118.0;
    private static final double RADAR_HAE = 100.0;

    // Elevation of every panel boresight, in degrees above the horizon.
    private static final double PANEL_ELEVATION_DEG = 10.0;

    // Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
    private static final int DEGRADED_FLIP_EVERY = 3;

    // A radar panel and the compass azimuth its boresight faces.
    private static final class Panel {
        final String id;
        final String description;
        final double azimuthDeg;

        Panel(String id, String description, double azimuthDeg) {
            this.id = id;
            this.description = description;
            this.azimuthDeg = azimuthDeg;
        }
    }

    private static final List<Panel> PANELS = List.of(
        new Panel("panel-1", "Panel 1", 0),
        new Panel("panel-2", "Panel 2", 90),
        new Panel("panel-3", "Panel 3", 180),
        new Panel("panel-4", "Panel 4", 270));

    // Return the ENU orientation that points a sensor's +X boresight at a compass azimuth
    // (degrees clockwise from true north) and an elevation (degrees above the horizon). The
    // quaternion is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
    // azimuth of 90 and an elevation of 0 gives the identity.
    private static Quaternion pointingToQuaternionEnu(double azimuthDeg, double elevationDeg) {
        double halfYaw = (Math.PI / 2 - Math.toRadians(azimuthDeg)) / 2;
        double halfPitch = -Math.toRadians(elevationDeg) / 2;
        double sz = Math.sin(halfYaw);
        double cz = Math.cos(halfYaw);
        double sy = Math.sin(halfPitch);
        double cy = Math.cos(halfPitch);
        return Quaternion.builder()
            .x(-sz * sy)
            .y(cz * sy)
            .z(sz * cy)
            .w(cz * cy)
            .build();
    }

    // Return the version 5 (SHA-1, URL namespace) UUID for a name. Java only ships version 3.
    private static UUID uuidV5Url(String name) throws NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        // The URL namespace UUID, 6ba7b811-9dad-11d1-80b4-00c04fd430c8.
        sha1.update(ByteBuffer.allocate(16)
            .putLong(0x6ba7b8119dad11d1L)
            .putLong(0x80b400c04fd430c8L)
            .array());
        byte[] hash = sha1.digest(name.getBytes(StandardCharsets.UTF_8));
        hash[6] = (byte) ((hash[6] & 0x0f) | 0x50);
        hash[8] = (byte) ((hash[8] & 0x3f) | 0x80);
        ByteBuffer buffer = ByteBuffer.wrap(hash);
        return new UUID(buffer.getLong(), buffer.getLong());
    }

    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;

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

            // Stable entity ID derived from the radar's name so the same radar maps to
            // the same Lattice entity across restarts.
            String entityId = uuidV5Url(RADAR_NAME).toString();
            Instant creationTime = Instant.now();

            // Continuously publish the entity so it does not expire.
            for (int update = 0; ; update++) {
                try {
                    Instant latestTimestamp = Instant.now();
                    OffsetDateTime now = OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC);

                    // Simulate telemetry: panel-3 alternates between OPERATIONAL and
                    // DEGRADED. A real integration maps hardware telemetry to these
                    // states instead of using a timer.
                    boolean panel3Degraded = (update / DEGRADED_FLIP_EVERY) % 2 == 1;

                    // Build one sensor and one health component per panel. The panel ID
                    // links the two.
                    List<Sensor> sensors = new ArrayList<>();
                    List<ComponentHealth> components = new ArrayList<>();
                    boolean anyDegraded = false;
                    for (Panel panel : PANELS) {
                        boolean degraded = panel.id.equals("panel-3") && panel3Degraded;
                        anyDegraded = anyDegraded || degraded;

                        sensors.add(Sensor.builder()
                            .sensorId(panel.id)
                            .sensorDescription(panel.description)
                            .sensorType(SensorSensorType.SENSOR_TYPE_RADAR)
                            .operationalState(degraded
                                ? SensorOperationalState.OPERATIONAL_STATE_DEGRADED
                                : SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                            .fieldsOfView(List.of(FieldOfView.builder()
                                .fovId(1)
                                .centerRayPose(EntityManagerPose.builder()
                                    .pos(Position.builder()
                                        .latitudeDegrees(RADAR_LAT)
                                        .longitudeDegrees(RADAR_LON)
                                        .altitudeHaeMeters(RADAR_HAE)
                                        .build())
                                    .orientation(pointingToQuaternionEnu(panel.azimuthDeg, PANEL_ELEVATION_DEG))
                                    .build())
                                .horizontalFov((float) (Math.PI / 2))
                                .verticalFov((float) (Math.PI / 6))
                                .range(10000.0f)
                                .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                .build()))
                            .build());
                        components.add(ComponentHealth.builder()
                            .id(panel.id)
                            .name(panel.description)
                            .health(degraded
                                ? ComponentHealthHealth.HEALTH_STATUS_WARN
                                : ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                            .messages(List.of(ComponentMessage.builder()
                                .status(degraded
                                    ? ComponentMessageStatus.HEALTH_STATUS_WARN
                                    : ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                                .message(panel.description + (degraded
                                    ? " is operating with reduced capability."
                                    : " is operating normally."))
                                .build()))
                            .updateTime(now)
                            .build());
                    }
                    components.add(ComponentHealth.builder()
                        .id("radar-controller")
                        .name("Radar controller")
                        .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                        .messages(List.of(ComponentMessage.builder()
                            .status(ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                            .message("Radar controller is operating normally.")
                            .build()))
                        .updateTime(now)
                        .build());

                    // The entity is WARN when any panel is degraded.
                    HealthHealthStatus healthStatus = anyDegraded
                        ? HealthHealthStatus.HEALTH_STATUS_WARN
                        : HealthHealthStatus.HEALTH_STATUS_HEALTHY;

                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Four-panel radar asset")
                        .aliases(Aliases.builder()
                            .name("Radar 1")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(
                            latestTimestamp.plus(ENTITY_EXPIRY_MIN, ChronoUnit.MINUTES), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("RADAR")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                            .build())
                        .location(Location.builder()
                            .position(Position.builder()
                                .latitudeDegrees(RADAR_LAT)
                                .longitudeDegrees(RADAR_LON)
                                .altitudeHaeMeters(RADAR_HAE)
                                .build())
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName(INTEGRATION_NAME)
                            .dataType(DATA_TYPE)
                            .sourceUpdateTime(now)
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(healthStatus)
                            .components(components)
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(now)
                            .build())
                        // Publish all panels as sensors on one asset entity.
                        .sensors(Sensors.builder()
                            .sensors(sensors)
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset with entity ID: " + entityId);

                    Thread.sleep(PUBLISH_INTERVAL_MS);
                } catch (Exception e) {
                    System.err.println("Error publishing entity: " + e.getMessage());
                    Thread.sleep(PUBLISH_INTERVAL_MS);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={46} maxLines={26}
# This Python example publishes a four-panel radar as one asset entity. Each
# panel is a sensor on the asset with its own field of view.

import asyncio
import math
import os
import sys
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    ComponentHealth,
    ComponentMessage,
    EntityManagerPose,
    FieldOfView,
    Health,
    Lattice,
    Location,
    MilView,
    Ontology,
    Position,
    Provenance,
    Quaternion,
    Sensor,
    Sensors,
)

RADAR_NAME = "radar-01"
INTEGRATION_NAME = "your_integration_name"
DATA_TYPE = "radar_asset"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY = timedelta(minutes=5)

# Fixed radar position.
RADAR_LATITUDE_DEGREES = 34.0
RADAR_LONGITUDE_DEGREES = -118.0
RADAR_ALTITUDE_HAE_METERS = 100.0

# Elevation of every panel boresight, in degrees above the horizon.
PANEL_ELEVATION_DEGREES = 10.0

# Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
DEGRADED_FLIP_EVERY = 3

# Each panel's sensor ID, display name, and boresight compass azimuth (degrees
# clockwise from true north).
PANELS = [
    {"id": "panel-1", "description": "Panel 1", "azimuth_deg": 0.0},
    {"id": "panel-2", "description": "Panel 2", "azimuth_deg": 90.0},
    {"id": "panel-3", "description": "Panel 3", "azimuth_deg": 180.0},
    {"id": "panel-4", "description": "Panel 4", "azimuth_deg": 270.0},
]


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton
    product, so an azimuth of 90 and an elevation of 0 gives the identity.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


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

# 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}"},
)

# Stable entity ID derived from the radar's name so the same radar maps to the
# same Lattice entity across restarts.
entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, RADAR_NAME))


async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        update_count = 0
        while True:
            latest_timestamp = datetime.now(timezone.utc)

            # Simulate telemetry: panel-3 alternates between OPERATIONAL and
            # DEGRADED. A real integration maps hardware telemetry to these
            # states instead of using a timer.
            panel_3_degraded = (update_count // DEGRADED_FLIP_EVERY) % 2 == 1

            # Build one sensor and one health component per panel. The panel ID
            # links the two.
            sensors = []
            components = []
            any_degraded = False
            for panel in PANELS:
                degraded = panel["id"] == "panel-3" and panel_3_degraded
                any_degraded = any_degraded or degraded

                sensors.append(
                    Sensor(
                        sensor_id=panel["id"],
                        sensor_description=panel["description"],
                        sensor_type="SENSOR_TYPE_RADAR",
                        operational_state="OPERATIONAL_STATE_DEGRADED" if degraded else "OPERATIONAL_STATE_OPERATIONAL",
                        fields_of_view=[
                            FieldOfView(
                                fov_id=1,
                                # The center ray pose is an absolute ENU orientation
                                # positioned at the radar.
                                center_ray_pose=EntityManagerPose(
                                    pos=Position(
                                        latitude_degrees=RADAR_LATITUDE_DEGREES,
                                        longitude_degrees=RADAR_LONGITUDE_DEGREES,
                                        altitude_hae_meters=RADAR_ALTITUDE_HAE_METERS,
                                    ),
                                    orientation=pointing_to_quaternion_enu(panel["azimuth_deg"], PANEL_ELEVATION_DEGREES),
                                ),
                                horizontal_fov=math.pi / 2,
                                vertical_fov=math.pi / 6,
                                range=10000.0,
                                mode="SENSOR_MODE_SEARCH",
                            ),
                        ],
                    )
                )
                panel_health = "HEALTH_STATUS_WARN" if degraded else "HEALTH_STATUS_HEALTHY"
                components.append(
                    ComponentHealth(
                        id=panel["id"],
                        name=panel["description"],
                        health=panel_health,
                        messages=[
                            ComponentMessage(
                                status=panel_health,
                                message=f"{panel['description']} is operating "
                                + ("with reduced capability." if degraded else "normally."),
                            ),
                        ],
                        update_time=latest_timestamp,
                    )
                )
            components.append(
                ComponentHealth(
                    id="radar-controller",
                    name="Radar controller",
                    health="HEALTH_STATUS_HEALTHY",
                    messages=[
                        ComponentMessage(
                            status="HEALTH_STATUS_HEALTHY",
                            message="Radar controller is operating normally.",
                        ),
                    ],
                    update_time=latest_timestamp,
                )
            )

            client.entities.publish_entity(
                entity_id=entity_id,
                description="Four-panel radar asset",
                aliases=Aliases(name="Radar 1"),
                is_live=True,
                created_time=creation_time,
                expiry_time=latest_timestamp + ENTITY_EXPIRY,
                ontology=Ontology(template="TEMPLATE_ASSET", platform_type="RADAR"),
                mil_view=MilView(
                    disposition="DISPOSITION_FRIENDLY",
                    environment="ENVIRONMENT_LAND",
                ),
                location=Location(
                    position=Position(
                        latitude_degrees=RADAR_LATITUDE_DEGREES,
                        longitude_degrees=RADAR_LONGITUDE_DEGREES,
                        altitude_hae_meters=RADAR_ALTITUDE_HAE_METERS,
                    ),
                ),
                provenance=Provenance(
                    integration_name=INTEGRATION_NAME,
                    data_type=DATA_TYPE,
                    source_update_time=latest_timestamp,
                ),
                health=Health(
                    connection_status="CONNECTION_STATUS_ONLINE",
                    # The entity is WARN when any panel is degraded.
                    health_status="HEALTH_STATUS_WARN" if any_degraded else "HEALTH_STATUS_HEALTHY",
                    components=components,
                    active_alerts=[],
                    update_time=latest_timestamp,
                ),
                # Publish all panels as sensors on one asset entity.
                sensors=Sensors(sensors=sensors),
            )
            print(f"Publishing asset with entity ID: {entity_id}")
            update_count += 1
            await asyncio.sleep(PUBLISH_INTERVAL_SEC)

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


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

```

```ts title={"TypeScript (REST)"} startLine={42} maxLines={27}
// This TypeScript example publishes a four-panel radar as one asset entity. Each
// panel is a sensor on the asset with its own field of view.
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } 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}`  }
    }
);

const radarName = "radar-01";
const integrationName = "your_integration_name";
const dataType = "radar_asset";
const publishIntervalMs = 5000;
const entityExpiryMs = 5 * 60 * 1000;

// Fixed radar position.
const radarLatitudeDegrees = 34.0;
const radarLongitudeDegrees = -118.0;
const radarAltitudeHaeMeters = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const panelElevationDegrees = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const degradedFlipEvery = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
const panels = [
    { id: "panel-1", description: "Panel 1", azimuthDeg: 0 },
    { id: "panel-2", description: "Panel 2", azimuthDeg: 90 },
    { id: "panel-3", description: "Panel 3", azimuthDeg: 180 },
    { id: "panel-4", description: "Panel 4", azimuthDeg: 270 }
];

const degToRad = (degrees: number) => degrees * Math.PI / 180;

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w) that rotates
// the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so
// an azimuth of 90 and an elevation of 0 gives the identity.
function pointingToQuaternionEnu(azimuthDeg: number, elevationDeg: number) {
    const halfYaw = (Math.PI / 2 - degToRad(azimuthDeg)) / 2;
    const halfPitch = -degToRad(elevationDeg) / 2;
    return {
        x: -Math.sin(halfYaw) * Math.sin(halfPitch),
        y: Math.cos(halfYaw) * Math.sin(halfPitch),
        z: Math.sin(halfYaw) * Math.cos(halfPitch),
        w: Math.cos(halfYaw) * Math.cos(halfPitch)
    };
}

let updateCount = 0;

// Stable entity ID derived from the radar's name so the same radar maps to the
// same Lattice entity across restarts.
const entityId = uuidv5(radarName, uuidv5.URL);
const creationTime = new Date().toISOString();

async function App() {
    const latestTimestamp = new Date();
    const now = latestTimestamp.toISOString();

    // Simulate telemetry: panel-3 alternates between OPERATIONAL and DEGRADED. A real
    // integration maps hardware telemetry to these states instead of using a timer.
    const panel3Degraded = Math.floor(updateCount / degradedFlipEvery) % 2 === 1;
    updateCount += 1;

    // Build one sensor and one health component per panel. The panel ID links the two.
    const sensors = [];
    const components = [];
    let anyDegraded = false;
    for (const panel of panels) {
        const degraded = panel.id === "panel-3" && panel3Degraded;
        anyDegraded = anyDegraded || degraded;

        sensors.push({
            sensorId: panel.id,
            sensorDescription: panel.description,
            sensorType: "SENSOR_TYPE_RADAR" as const,
            operationalState: degraded
                ? "OPERATIONAL_STATE_DEGRADED" as const
                : "OPERATIONAL_STATE_OPERATIONAL" as const,
            fieldsOfView: [
                {
                    fovId: 1,
                    // The center ray pose is an absolute ENU orientation positioned at the radar.
                    centerRayPose: {
                        pos: {
                            latitudeDegrees: radarLatitudeDegrees,
                            longitudeDegrees: radarLongitudeDegrees,
                            altitudeHaeMeters: radarAltitudeHaeMeters
                        },
                        orientation: pointingToQuaternionEnu(panel.azimuthDeg, panelElevationDegrees)
                    },
                    horizontalFov: Math.PI / 2,
                    verticalFov: Math.PI / 6,
                    range: 10000.0,
                    mode: "SENSOR_MODE_SEARCH" as const
                }
            ]
        });
        const panelHealth = degraded ? "HEALTH_STATUS_WARN" as const : "HEALTH_STATUS_HEALTHY" as const;
        components.push({
            id: panel.id,
            name: panel.description,
            health: panelHealth,
            messages: [
                {
                    status: panelHealth,
                    message: `${panel.description} is operating ${degraded ? "with reduced capability." : "normally."}`
                }
            ],
            updateTime: now
        });
    }
    components.push({
        id: "radar-controller",
        name: "Radar controller",
        health: "HEALTH_STATUS_HEALTHY" as const,
        messages: [
            {
                status: "HEALTH_STATUS_HEALTHY" as const,
                message: "Radar controller is operating normally."
            }
        ],
        updateTime: now
    });

    try {
        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Four-panel radar asset",
                aliases: { name: "Radar 1" },
                isLive: true,
                createdTime: creationTime,
                expiryTime: new Date(latestTimestamp.getTime() + entityExpiryMs).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "RADAR"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_LAND"
                },
                location: {
                    position: {
                        latitudeDegrees: radarLatitudeDegrees,
                        longitudeDegrees: radarLongitudeDegrees,
                        altitudeHaeMeters: radarAltitudeHaeMeters
                    }
                },
                provenance: {
                    integrationName: integrationName,
                    dataType: dataType,
                    sourceUpdateTime: now
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    // The entity is WARN when any panel is degraded.
                    healthStatus: anyDegraded ? "HEALTH_STATUS_WARN" : "HEALTH_STATUS_HEALTHY",
                    components: components,
                    activeAlerts: [],
                    updateTime: now
                },
                // Publish all panels as sensors on one asset entity.
                sensors: { sensors: sensors }
            }
        );
        console.log(`Publishing asset with entity ID: ${entityId}`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}

(async function runIndefinitely() {
    while (true) {
        await App();
        await new Promise(resolve => setTimeout(resolve, publishIntervalMs));
    }
})();

```

```rs title={"Rust (REST)"} startLine={34} maxLines={24}
// This Rust example publishes a four-panel radar as one asset entity. Each
// panel is a sensor on the asset with its own field of view.
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::f64::consts::PI;
use std::time::Duration;
use uuid::Uuid;

const RADAR_NAME: &str = "radar-01";
const INTEGRATION_NAME: &str = "your_integration_name";
const DATA_TYPE: &str = "radar_asset";
const PUBLISH_INTERVAL: Duration = Duration::from_secs(5);

// Fixed radar position.
const RADAR_LATITUDE_DEGREES: f64 = 34.0;
const RADAR_LONGITUDE_DEGREES: f64 = -118.0;
const RADAR_ALTITUDE_HAE_METERS: f64 = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const PANEL_ELEVATION_DEGREES: f64 = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const DEGRADED_FLIP_EVERY: u32 = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
struct Panel {
    id: &'static str,
    description: &'static str,
    azimuth_deg: f64,
}

const PANELS: [Panel; 4] = [
    Panel { id: "panel-1", description: "Panel 1", azimuth_deg: 0.0 },
    Panel { id: "panel-2", description: "Panel 2", azimuth_deg: 90.0 },
    Panel { id: "panel-3", description: "Panel 3", azimuth_deg: 180.0 },
    Panel { id: "panel-4", description: "Panel 4", azimuth_deg: 270.0 },
];

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into
/// ENU. The azimuth is degrees clockwise from true north and the elevation is
/// degrees above the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation)
/// using the Hamilton product, so an azimuth of 90 and an elevation of 0 gives
/// the identity.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (PI / 2.0 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: Some(-half_yaw.sin() * half_pitch.sin()),
        y: Some(half_yaw.cos() * half_pitch.sin()),
        z: Some(half_yaw.sin() * half_pitch.cos()),
        w: Some(half_yaw.cos() * half_pitch.cos()),
    }
}

#[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)?;

    // Stable entity ID derived from the radar's name so the same radar maps to
    // the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, RADAR_NAME.as_bytes()).to_string();

    let creation_time = Utc::now().fixed_offset();
    let mut update_count: u32 = 0;
    loop {
        let latest_timestamp = Utc::now().fixed_offset();

        // Simulate telemetry: panel-3 alternates between OPERATIONAL and
        // DEGRADED. A real integration maps hardware telemetry to these
        // states instead of using a timer.
        let panel_3_degraded = (update_count / DEGRADED_FLIP_EVERY) % 2 == 1;

        // Build one sensor and one health component per panel. The panel ID
        // links the two.
        let mut sensors = Vec::new();
        let mut components = Vec::new();
        let mut any_degraded = false;
        for panel in &PANELS {
            let degraded = panel.id == "panel-3" && panel_3_degraded;
            any_degraded = any_degraded || degraded;

            sensors.push(Sensor {
                sensor_id: Some(panel.id.to_string()),
                sensor_description: Some(panel.description.to_string()),
                sensor_type: Some(SensorSensorType::SensorTypeRadar),
                operational_state: Some(if degraded {
                    SensorOperationalState::OperationalStateDegraded
                } else {
                    SensorOperationalState::OperationalStateOperational
                }),
                fields_of_view: Some(vec![FieldOfView {
                    fov_id: Some(1),
                    // The center ray pose is an absolute ENU orientation
                    // positioned at the radar.
                    center_ray_pose: Some(EntityManagerPose {
                        pos: Some(Position {
                            latitude_degrees: Some(RADAR_LATITUDE_DEGREES),
                            longitude_degrees: Some(RADAR_LONGITUDE_DEGREES),
                            altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
                            ..Default::default()
                        }),
                        orientation: Some(pointing_to_quaternion_enu(
                            panel.azimuth_deg,
                            PANEL_ELEVATION_DEGREES,
                        )),
                    }),
                    horizontal_fov: Some(PI / 2.0),
                    vertical_fov: Some(PI / 6.0),
                    range: Some(10000.0),
                    mode: Some(FieldOfViewMode::SensorModeSearch),
                    ..Default::default()
                }]),
                ..Default::default()
            });

            let (panel_health, panel_message_status, panel_message) = if degraded {
                (
                    ComponentHealthHealth::HealthStatusWarn,
                    ComponentMessageStatus::HealthStatusWarn,
                    format!("{} is operating with reduced capability.", panel.description),
                )
            } else {
                (
                    ComponentHealthHealth::HealthStatusHealthy,
                    ComponentMessageStatus::HealthStatusHealthy,
                    format!("{} is operating normally.", panel.description),
                )
            };
            components.push(ComponentHealth {
                id: Some(panel.id.to_string()),
                name: Some(panel.description.to_string()),
                health: Some(panel_health),
                messages: Some(vec![ComponentMessage {
                    status: Some(panel_message_status),
                    message: Some(panel_message),
                }]),
                update_time: Some(latest_timestamp),
            });
        }
        components.push(ComponentHealth {
            id: Some("radar-controller".to_string()),
            name: Some("Radar controller".to_string()),
            health: Some(ComponentHealthHealth::HealthStatusHealthy),
            messages: Some(vec![ComponentMessage {
                status: Some(ComponentMessageStatus::HealthStatusHealthy),
                message: Some("Radar controller is operating normally.".to_string()),
            }]),
            update_time: Some(latest_timestamp),
        });

        let entity = Entity {
            entity_id: Some(entity_id.clone()),
            description: Some("Four-panel radar asset".to_string()),
            aliases: Some(Aliases {
                name: Some("Radar 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::minutes(5)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("RADAR".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentLand),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(Position {
                    latitude_degrees: Some(RADAR_LATITUDE_DEGREES),
                    longitude_degrees: Some(RADAR_LONGITUDE_DEGREES),
                    altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some(INTEGRATION_NAME.to_string()),
                data_type: Some(DATA_TYPE.to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                // The entity is WARN when any panel is degraded.
                health_status: Some(if any_degraded {
                    HealthHealthStatus::HealthStatusWarn
                } else {
                    HealthHealthStatus::HealthStatusHealthy
                }),
                components: Some(components),
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
            }),
            // Publish all panels as sensors on one asset entity.
            sensors: Some(Sensors {
                sensors: Some(sensors),
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", entity_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        update_count += 1;
        tokio::time::sleep(PUBLISH_INTERVAL).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={53} maxLines={24}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
// It publishes a four-panel radar as one asset entity. Each panel is a sensor
// on the asset with its own field of view.
package main

import (
	"context"
	"fmt"
	"log"
	"math"
	"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"
)

const (
	radarName       = "radar-01"
	integrationName = "your_integration_name"
	dataType        = "radar_asset"
	publishInterval = 5 * time.Second
	entityExpiry    = 5 * time.Minute
	publishTimeout  = 10 * time.Second

	// Fixed radar position.
	radarLat = 34.0
	radarLon = -118.0
	radarHae = 100.0

	// Elevation of every panel boresight, in degrees above the horizon.
	panelElevationDeg = 10.0

	// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
	degradedFlipEvery = 3
)

// panel describes one radar panel and the compass azimuth its boresight faces.
type panel struct {
	id          string
	description string
	azimuthDeg  float64
}

var panels = []panel{
	{"panel-1", "Panel 1", 0},
	{"panel-2", "Panel 2", 90},
	{"panel-3", "Panel 3", 180},
	{"panel-4", "Panel 4", 270},
}

// pointingToQuaternionEnu returns the ENU orientation that points a sensor's
// +X boresight at a compass azimuth (degrees clockwise from true north) and an
// elevation (degrees above the horizon). The quaternion is
// qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
// azimuth of 90 and an elevation of 0 gives the identity.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *_type.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	sz, cz := math.Sin(halfYaw), math.Cos(halfYaw)
	sy, cy := math.Sin(halfPitch), math.Cos(halfPitch)
	return &_type.Quaternion{
		X: -sz * sy,
		Y: cz * sy,
		Z: sz * cy,
		W: cz * cy,
	}
}

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

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}

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

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stable entity_id derived from the radar's name so the same radar maps to
	// the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(radarName)).String()

	creationTimestamp := timestamppb.New(time.Now().UTC())

	// Continuously publish the entity so it does not expire.
	for update := 0; ; update++ {
		latestTimestamp := time.Now().UTC()
		latestTs := timestamppb.New(latestTimestamp)
		ctx, cancel := context.WithTimeout(context.Background(), publishTimeout)

		// Simulate telemetry: panel-3 alternates between OPERATIONAL and
		// DEGRADED. A real integration maps hardware telemetry to these
		// states instead of using a timer.
		panel3Degraded := (update/degradedFlipEvery)%2 == 1

		// Build one sensor and one health component per panel. The panel ID
		// links the two.
		sensors := []*entitymanagerv1.Sensor{}
		components := []*entitymanagerv1.ComponentHealth{}
		anyDegraded := false
		for _, p := range panels {
			degraded := p.id == "panel-3" && panel3Degraded
			anyDegraded = anyDegraded || degraded

			operationalState := entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL
			panelHealth := entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY
			message := p.description + " is operating normally."
			if degraded {
				operationalState = entitymanagerv1.OperationalState_OPERATIONAL_STATE_DEGRADED
				panelHealth = entitymanagerv1.HealthStatus_HEALTH_STATUS_WARN
				message = p.description + " is operating with reduced capability."
			}

			sensors = append(sensors, &entitymanagerv1.Sensor{
				SensorId:          p.id,
				SensorDescription: p.description,
				SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_RADAR,
				OperationalState:  operationalState,
				FieldsOfView: []*entitymanagerv1.FieldOfView{
					{
						FovId: 1,
						CenterRayPose: &entitymanagerv1.Pose{
							Pos: &entitymanagerv1.Position{
								LatitudeDegrees:   radarLat,
								LongitudeDegrees:  radarLon,
								AltitudeHaeMeters: wrapperspb.Double(radarHae),
							},
							Orientation: pointingToQuaternionEnu(p.azimuthDeg, panelElevationDeg),
						},
						HorizontalFov: math.Pi / 2,
						VerticalFov:   math.Pi / 6,
						Range:         wrapperspb.Float(10000.0),
						Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
					},
				},
			})
			components = append(components, &entitymanagerv1.ComponentHealth{
				Id:     p.id,
				Name:   p.description,
				Health: panelHealth,
				Messages: []*entitymanagerv1.ComponentMessage{
					{Status: panelHealth, Message: message},
				},
				UpdateTime: latestTs,
			})
		}
		components = append(components, &entitymanagerv1.ComponentHealth{
			Id:     "radar-controller",
			Name:   "Radar controller",
			Health: entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
			Messages: []*entitymanagerv1.ComponentMessage{
				{
					Status:  entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
					Message: "Radar controller is operating normally.",
				},
			},
			UpdateTime: latestTs,
		})

		// The entity is WARN when any panel is degraded.
		healthStatus := entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY
		if anyDegraded {
			healthStatus = entitymanagerv1.HealthStatus_HEALTH_STATUS_WARN
		}

		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Four-panel radar asset",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Radar 1",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(entityExpiry)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "RADAR",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
			},
			Location: &entitymanagerv1.Location{
				Position: &entitymanagerv1.Position{
					LatitudeDegrees:   radarLat,
					LongitudeDegrees:  radarLon,
					AltitudeHaeMeters: wrapperspb.Double(radarHae),
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  integrationName,
				DataType:         dataType,
				SourceUpdateTime: latestTs,
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     healthStatus,
				Components:       components,
				ActiveAlerts:     []*entitymanagerv1.Alert{},
				UpdateTime:       latestTs,
			},
			// Publish all panels as sensors on one asset entity.
			Sensors: &entitymanagerv1.Sensors{Sensors: sensors},
		}

		_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: entity})
		cancel()

		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

```py title={"Python (gRPC)"} startLine={57} maxLines={30}
# 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
# It publishes a four-panel radar as one asset entity. Each panel is a sensor
# on the asset with its own field of view.

import math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, 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.health_status_pub_pb import (
    ComponentHealth,
    ComponentMessage,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    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 Quaternion

RADAR_NAME = "radar-01"
INTEGRATION_NAME = "your_integration_name"
DATA_TYPE = "radar_asset"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY = timedelta(minutes=5)

# Fixed radar position.
RADAR_LATITUDE_DEGREES = 34.0
RADAR_LONGITUDE_DEGREES = -118.0
RADAR_ALTITUDE_HAE_METERS = 100.0

# Elevation of every panel boresight, in degrees above the horizon.
PANEL_ELEVATION_DEGREES = 10.0

# Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
DEGRADED_FLIP_EVERY = 3

# Each panel's sensor ID, display name, and boresight compass azimuth (degrees
# clockwise from true north).
PANELS = [
    {"id": "panel-1", "description": "Panel 1", "azimuth_deg": 0.0},
    {"id": "panel-2", "description": "Panel 2", "azimuth_deg": 90.0},
    {"id": "panel-3", "description": "Panel 3", "azimuth_deg": 180.0},
    {"id": "panel-4", "description": "Panel 4", "azimuth_deg": 270.0},
]


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


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton
    product, so an azimuth of 90 and an elevation of 0 gives the identity.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


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)

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

    # Stable entity_id derived from the radar's name so the same radar maps to
    # the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, RADAR_NAME))

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

    update_count = 0
    while True:
        latest = datetime.now(timezone.utc)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + ENTITY_EXPIRY)

        # Simulate telemetry: panel-3 alternates between OPERATIONAL and
        # DEGRADED. A real integration maps hardware telemetry to these
        # states instead of using a timer.
        panel_3_degraded = (update_count // DEGRADED_FLIP_EVERY) % 2 == 1

        # Build one sensor and one health component per panel. The panel ID
        # links the two.
        sensors = []
        components = []
        any_degraded = False
        for panel in PANELS:
            degraded = panel["id"] == "panel-3" and panel_3_degraded
            any_degraded = any_degraded or degraded

            sensors.append(
                Sensor(
                    sensor_id=panel["id"],
                    sensor_description=panel["description"],
                    sensor_type=SensorType.RADAR,
                    operational_state=OperationalState.DEGRADED if degraded else OperationalState.OPERATIONAL,
                    fields_of_view=[
                        FieldOfView(
                            fov_id=1,
                            # The center ray pose is an absolute ENU orientation
                            # positioned at the radar.
                            center_ray_pose=Pose(
                                pos=Position(
                                    latitude_degrees=RADAR_LATITUDE_DEGREES,
                                    longitude_degrees=RADAR_LONGITUDE_DEGREES,
                                    altitude_hae_meters=DoubleValue(value=RADAR_ALTITUDE_HAE_METERS),
                                ),
                                orientation=pointing_to_quaternion_enu(panel["azimuth_deg"], PANEL_ELEVATION_DEGREES),
                            ),
                            horizontal_fov=math.pi / 2,
                            vertical_fov=math.pi / 6,
                            range=FloatValue(value=10000.0),
                            mode=SensorMode.SEARCH,
                        ),
                    ],
                )
            )
            panel_health = HealthStatus.WARN if degraded else HealthStatus.HEALTHY
            components.append(
                ComponentHealth(
                    id=panel["id"],
                    name=panel["description"],
                    health=panel_health,
                    messages=[
                        ComponentMessage(
                            status=panel_health,
                            message=f"{panel['description']} is operating "
                            + ("with reduced capability." if degraded else "normally."),
                        ),
                    ],
                    update_time=latest_ts,
                )
            )
        components.append(
            ComponentHealth(
                id="radar-controller",
                name="Radar controller",
                health=HealthStatus.HEALTHY,
                messages=[
                    ComponentMessage(
                        status=HealthStatus.HEALTHY,
                        message="Radar controller is operating normally.",
                    ),
                ],
                update_time=latest_ts,
            )
        )

        entity = Entity(
            entity_id=entity_id,
            description="Four-panel radar asset",
            aliases=Aliases(name="Radar 1"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="RADAR"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.LAND,
            ),
            location=Location(
                position=Position(
                    latitude_degrees=RADAR_LATITUDE_DEGREES,
                    longitude_degrees=RADAR_LONGITUDE_DEGREES,
                    altitude_hae_meters=DoubleValue(value=RADAR_ALTITUDE_HAE_METERS),
                ),
            ),
            provenance=Provenance(
                integration_name=INTEGRATION_NAME,
                data_type=DATA_TYPE,
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                # The entity is WARN when any panel is degraded.
                health_status=HealthStatus.WARN if any_degraded else HealthStatus.HEALTHY,
                components=components,
                active_alerts=[],
                update_time=latest_ts,
            ),
            # Publish all panels as sensors on one asset entity.
            sensors=Sensors(sensors=sensors),
        )

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

        update_count += 1
        time.sleep(PUBLISH_INTERVAL_SEC)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={53} maxLines={24}
// 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
// It publishes a four-panel radar as one asset entity. Each panel is a sensor
// on the asset with its own field of view.
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, ComponentHealth, ComponentMessage, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position, Provenance,
    PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::Quaternion;
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::f64::consts::PI;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const RADAR_NAME: &str = "radar-01";
const INTEGRATION_NAME: &str = "your_integration_name";
const DATA_TYPE: &str = "radar_asset";
const PUBLISH_INTERVAL: Duration = Duration::from_secs(5);
const ENTITY_EXPIRY_SECS: i64 = 5 * 60;

// Fixed radar position.
const RADAR_LATITUDE_DEGREES: f64 = 34.0;
const RADAR_LONGITUDE_DEGREES: f64 = -118.0;
const RADAR_ALTITUDE_HAE_METERS: f64 = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const PANEL_ELEVATION_DEGREES: f64 = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const DEGRADED_FLIP_EVERY: u32 = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
struct Panel {
    id: &'static str,
    description: &'static str,
    azimuth_deg: f64,
}

const PANELS: [Panel; 4] = [
    Panel { id: "panel-1", description: "Panel 1", azimuth_deg: 0.0 },
    Panel { id: "panel-2", description: "Panel 2", azimuth_deg: 90.0 },
    Panel { id: "panel-3", description: "Panel 3", azimuth_deg: 180.0 },
    Panel { id: "panel-4", description: "Panel 4", azimuth_deg: 270.0 },
];

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
//
// The quaternion rotates the sensor frame, whose +X axis is the boresight, into
// ENU. The azimuth is degrees clockwise from true north and the elevation is
// degrees above the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation)
// using the Hamilton product, so an azimuth of 90 and an elevation of 0 gives
// the identity.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (PI / 2.0 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: -half_yaw.sin() * half_pitch.sin(),
        y: half_yaw.cos() * half_pitch.sin(),
        z: half_yaw.sin() * half_pitch.cos(),
        w: half_yaw.cos() * half_pitch.cos(),
    }
}

// The radar position, shared by the entity location and each field of view.
fn radar_position() -> Position {
    Position {
        latitude_degrees: RADAR_LATITUDE_DEGREES,
        longitude_degrees: RADAR_LONGITUDE_DEGREES,
        altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

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");

    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)
        },
    );

    // Stable entity_id derived from the radar's name so the same radar maps to
    // the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, RADAR_NAME.as_bytes()).to_string();

    let creation_timestamp = now_timestamp();
    let mut update_count: u32 = 0;

    // Continuously publish the entity so it does not expire.
    loop {
        let latest_timestamp = now_timestamp();

        // Simulate telemetry: panel-3 alternates between OPERATIONAL and
        // DEGRADED. A real integration maps hardware telemetry to these
        // states instead of using a timer.
        let panel_3_degraded = (update_count / DEGRADED_FLIP_EVERY) % 2 == 1;

        // Build one sensor and one health component per panel. The panel ID
        // links the two.
        let mut sensors = Vec::new();
        let mut components = Vec::new();
        let mut any_degraded = false;
        for panel in &PANELS {
            let degraded = panel.id == "panel-3" && panel_3_degraded;
            any_degraded = any_degraded || degraded;

            sensors.push(Sensor {
                sensor_id: panel.id.to_string(),
                sensor_description: panel.description.to_string(),
                sensor_type: SensorType::Radar as i32,
                operational_state: if degraded {
                    OperationalState::Degraded as i32
                } else {
                    OperationalState::Operational as i32
                },
                fields_of_view: vec![FieldOfView {
                    fov_id: 1,
                    // The center ray pose is an absolute ENU orientation
                    // positioned at the radar.
                    center_ray_pose: Some(Pose {
                        pos: Some(radar_position()),
                        orientation: Some(pointing_to_quaternion_enu(
                            panel.azimuth_deg,
                            PANEL_ELEVATION_DEGREES,
                        )),
                    }),
                    horizontal_fov: (PI / 2.0) as f32,
                    vertical_fov: (PI / 6.0) as f32,
                    range: Some(10000.0),
                    mode: SensorMode::Search as i32,
                    ..Default::default()
                }],
                ..Default::default()
            });

            let (panel_health, panel_message) = if degraded {
                (
                    HealthStatus::Warn,
                    format!("{} is operating with reduced capability.", panel.description),
                )
            } else {
                (
                    HealthStatus::Healthy,
                    format!("{} is operating normally.", panel.description),
                )
            };
            components.push(ComponentHealth {
                id: panel.id.to_string(),
                name: panel.description.to_string(),
                health: panel_health as i32,
                messages: vec![ComponentMessage {
                    status: panel_health as i32,
                    message: panel_message,
                }],
                update_time: Some(latest_timestamp),
            });
        }
        components.push(ComponentHealth {
            id: "radar-controller".to_string(),
            name: "Radar controller".to_string(),
            health: HealthStatus::Healthy as i32,
            messages: vec![ComponentMessage {
                status: HealthStatus::Healthy as i32,
                message: "Radar controller is operating normally.".to_string(),
            }],
            update_time: Some(latest_timestamp),
        });

        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Four-panel radar asset".to_string(),
            aliases: Some(Aliases {
                name: "Radar 1".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp),
            expiry_time: Some(add_seconds(&latest_timestamp, ENTITY_EXPIRY_SECS)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "RADAR".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Land as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(radar_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: INTEGRATION_NAME.to_string(),
                data_type: DATA_TYPE.to_string(),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                // The entity is WARN when any panel is degraded.
                health_status: if any_degraded {
                    HealthStatus::Warn as i32
                } else {
                    HealthStatus::Healthy as i32
                },
                components,
                active_alerts: vec![],
                update_time: Some(latest_timestamp),
            }),
            // Publish all panels as sensors on one asset entity.
            sensors: Some(Sensors { sensors }),
            ..Default::default()
        };

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

        update_count += 1;
        tokio::time::sleep(PUBLISH_INTERVAL).await;
    }
}

```

One panel can have several fields of view, such as a broad `SENSOR_MODE_SEARCH` volume and a
narrower `SENSOR_MODE_TRACK` beam. Give each one a `fovId` that stays stable and unique within
the panel, rather than creating extra sensor entries. Remove coverage that is no longer active
when the panel's state or mode changes.

#### Report each panel's state

Report each panel's current sensing state in `operationalState`, based on hardware telemetry:

| `operationalState`                  | When to report it                                                                   |
| ----------------------------------- | ----------------------------------------------------------------------------------- |
| `OPERATIONAL_STATE_OPERATIONAL`     | The panel is fully functional and sensing.                                          |
| `OPERATIONAL_STATE_DEGRADED`        | The panel is sensing with reduced capability, such as reduced calibration quality.  |
| `OPERATIONAL_STATE_DENIED`          | The panel is sensing but is being actively denied, such as by jamming.              |
| `OPERATIONAL_STATE_OFF`             | Sensing is deliberately disabled, such as after an operator stops transmission.     |
| `OPERATIONAL_STATE_NON_OPERATIONAL` | The panel can't operate because of a fault, rather than an intentional off command. |
| `OPERATIONAL_STATE_INVALID`         | Don't publish this value. It's the protobuf default, not an operating state.        |

A degraded or denied panel is still sensing, so don't report it as off. Mirror each panel's
condition in a matching `health.components` entry, and roll the worst condition up into the
top-level `healthStatus`. In the example, the radar reports `HEALTH_STATUS_WARN` while any panel
is degraded.

#### Publish the entity

On every update, map telemetry to each panel's state, rebuild the sensors and health components,
and publish the entity with the [`PublishEntity`](/reference/rest/entities/publish-entity) API
method. The example simulates the telemetry with a timer:

```go title={"Go (REST)"} startLine={106} maxLines={75}
// This Go example publishes a four-panel radar as one asset entity. Each panel
// is a sensor on the asset with its own field of view.
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

const (
	radarName       = "radar-01"
	integrationName = "your_integration_name"
	dataType        = "radar_asset"
	publishInterval = 5 * time.Second
	entityExpiry    = 5 * time.Minute

	// Fixed radar position.
	radarLat = 34.0
	radarLon = -118.0
	radarHae = 100.0

	// Elevation of every panel boresight, in degrees above the horizon.
	panelElevationDeg = 10.0

	// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
	degradedFlipEvery = 3
)

// panel describes one radar panel and the compass azimuth its boresight faces.
type panel struct {
	id          string
	description string
	azimuthDeg  float64
}

var panels = []panel{
	{"panel-1", "Panel 1", 0},
	{"panel-2", "Panel 2", 90},
	{"panel-3", "Panel 3", 180},
	{"panel-4", "Panel 4", 270},
}

// pointingToQuaternionEnu returns the ENU orientation that points a sensor's
// +X boresight at a compass azimuth (degrees clockwise from true north) and an
// elevation (degrees above the horizon). The quaternion is
// qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
// azimuth of 90 and an elevation of 0 gives the identity.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *Lattice.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	sz, cz := math.Sin(halfYaw), math.Cos(halfYaw)
	sy, cy := math.Sin(halfPitch), math.Cos(halfPitch)
	return &Lattice.Quaternion{
		X: Lattice.Float64(-sz * sy),
		Y: Lattice.Float64(cz * sy),
		Z: Lattice.Float64(sz * cy),
		W: Lattice.Float64(cz * cy),
	}
}

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)
	}

	// 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),
	)

	// Stable entity ID derived from the radar's name so the same radar maps to
	// the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(radarName)).String()

	creationTime := time.Now().UTC()

	// Continuously publish the entity so it does not expire.
	for update := 0; ; update++ {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Simulate telemetry: panel-3 alternates between OPERATIONAL and
		// DEGRADED. A real integration maps hardware telemetry to these
		// states instead of using a timer.
		panel3Degraded := (update/degradedFlipEvery)%2 == 1

		// Build one sensor and one health component per panel. The panel ID
		// links the two.
		sensors := []*Lattice.Sensor{}
		components := []*Lattice.ComponentHealth{}
		anyDegraded := false
		for _, p := range panels {
			degraded := p.id == "panel-3" && panel3Degraded
			anyDegraded = anyDegraded || degraded

			operationalState := Lattice.SensorOperationalStateOperationalStateOperational
			panelHealth := Lattice.ComponentHealthHealthHealthStatusHealthy
			messageStatus := Lattice.ComponentMessageStatusHealthStatusHealthy
			message := p.description + " is operating normally."
			if degraded {
				operationalState = Lattice.SensorOperationalStateOperationalStateDegraded
				panelHealth = Lattice.ComponentHealthHealthHealthStatusWarn
				messageStatus = Lattice.ComponentMessageStatusHealthStatusWarn
				message = p.description + " is operating with reduced capability."
			}

			sensors = append(sensors, &Lattice.Sensor{
				SensorID:          Lattice.String(p.id),
				SensorDescription: Lattice.String(p.description),
				SensorType:        Lattice.SensorSensorTypeSensorTypeRadar.Ptr(),
				OperationalState:  operationalState.Ptr(),
				FieldsOfView: []*Lattice.FieldOfView{
					{
						FovID: Lattice.Int(1),
						CenterRayPose: &Lattice.EntityManagerPose{
							Pos: &Lattice.Position{
								LatitudeDegrees:   Lattice.Float64(radarLat),
								LongitudeDegrees:  Lattice.Float64(radarLon),
								AltitudeHaeMeters: Lattice.Float64(radarHae),
							},
							Orientation: pointingToQuaternionEnu(p.azimuthDeg, panelElevationDeg),
						},
						HorizontalFov: Lattice.Float64(math.Pi / 2),
						VerticalFov:   Lattice.Float64(math.Pi / 6),
						Range:         Lattice.Float64(10000.0),
						Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
					},
				},
			})
			components = append(components, &Lattice.ComponentHealth{
				ID:     Lattice.String(p.id),
				Name:   Lattice.String(p.description),
				Health: panelHealth.Ptr(),
				Messages: []*Lattice.ComponentMessage{
					{Status: messageStatus.Ptr(), Message: Lattice.String(message)},
				},
				UpdateTime: Lattice.Time(latestTimestamp),
			})
		}
		components = append(components, &Lattice.ComponentHealth{
			ID:     Lattice.String("radar-controller"),
			Name:   Lattice.String("Radar controller"),
			Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
			Messages: []*Lattice.ComponentMessage{
				{
					Status:  Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
					Message: Lattice.String("Radar controller is operating normally."),
				},
			},
			UpdateTime: Lattice.Time(latestTimestamp),
		})

		// The entity is WARN when any panel is degraded.
		healthStatus := Lattice.HealthHealthStatusHealthStatusHealthy
		if anyDegraded {
			healthStatus = Lattice.HealthHealthStatusHealthStatusWarn
		}

		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Four-panel radar asset"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Radar 1"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(entityExpiry)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("RADAR"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
			},
			Location: &Lattice.Location{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(radarLat),
					LongitudeDegrees:  Lattice.Float64(radarLon),
					AltitudeHaeMeters: Lattice.Float64(radarHae),
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String(integrationName),
				DataType:         Lattice.String(dataType),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     healthStatus.Ptr(),
				Components:       components,
				ActiveAlerts:     []*Lattice.Alert{},
				UpdateTime:       Lattice.Time(latestTimestamp),
			},
			// Publish all panels as sensors on one asset entity.
			Sensors: &Lattice.Sensors{Sensors: sensors},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

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

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.Aliases;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.ComponentMessage;
import com.anduril.types.ComponentMessageStatus;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
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.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;

/**
 * Publishes a four-panel radar as one asset entity with the Lattice SDK. Each panel is a sensor on
 * the asset with its own field of view.
 */
public class PublishAssetRadar {
    private static final String RADAR_NAME = "radar-01";
    private static final String INTEGRATION_NAME = "your_integration_name";
    private static final String DATA_TYPE = "radar_asset";
    private static final long PUBLISH_INTERVAL_MS = 5000;
    private static final long ENTITY_EXPIRY_MIN = 5;

    // Fixed radar position.
    private static final double RADAR_LAT = 34.0;
    private static final double RADAR_LON = -118.0;
    private static final double RADAR_HAE = 100.0;

    // Elevation of every panel boresight, in degrees above the horizon.
    private static final double PANEL_ELEVATION_DEG = 10.0;

    // Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
    private static final int DEGRADED_FLIP_EVERY = 3;

    // A radar panel and the compass azimuth its boresight faces.
    private static final class Panel {
        final String id;
        final String description;
        final double azimuthDeg;

        Panel(String id, String description, double azimuthDeg) {
            this.id = id;
            this.description = description;
            this.azimuthDeg = azimuthDeg;
        }
    }

    private static final List<Panel> PANELS = List.of(
        new Panel("panel-1", "Panel 1", 0),
        new Panel("panel-2", "Panel 2", 90),
        new Panel("panel-3", "Panel 3", 180),
        new Panel("panel-4", "Panel 4", 270));

    // Return the ENU orientation that points a sensor's +X boresight at a compass azimuth
    // (degrees clockwise from true north) and an elevation (degrees above the horizon). The
    // quaternion is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
    // azimuth of 90 and an elevation of 0 gives the identity.
    private static Quaternion pointingToQuaternionEnu(double azimuthDeg, double elevationDeg) {
        double halfYaw = (Math.PI / 2 - Math.toRadians(azimuthDeg)) / 2;
        double halfPitch = -Math.toRadians(elevationDeg) / 2;
        double sz = Math.sin(halfYaw);
        double cz = Math.cos(halfYaw);
        double sy = Math.sin(halfPitch);
        double cy = Math.cos(halfPitch);
        return Quaternion.builder()
            .x(-sz * sy)
            .y(cz * sy)
            .z(sz * cy)
            .w(cz * cy)
            .build();
    }

    // Return the version 5 (SHA-1, URL namespace) UUID for a name. Java only ships version 3.
    private static UUID uuidV5Url(String name) throws NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        // The URL namespace UUID, 6ba7b811-9dad-11d1-80b4-00c04fd430c8.
        sha1.update(ByteBuffer.allocate(16)
            .putLong(0x6ba7b8119dad11d1L)
            .putLong(0x80b400c04fd430c8L)
            .array());
        byte[] hash = sha1.digest(name.getBytes(StandardCharsets.UTF_8));
        hash[6] = (byte) ((hash[6] & 0x0f) | 0x50);
        hash[8] = (byte) ((hash[8] & 0x3f) | 0x80);
        ByteBuffer buffer = ByteBuffer.wrap(hash);
        return new UUID(buffer.getLong(), buffer.getLong());
    }

    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;

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

            // Stable entity ID derived from the radar's name so the same radar maps to
            // the same Lattice entity across restarts.
            String entityId = uuidV5Url(RADAR_NAME).toString();
            Instant creationTime = Instant.now();

            // Continuously publish the entity so it does not expire.
            for (int update = 0; ; update++) {
                try {
                    Instant latestTimestamp = Instant.now();
                    OffsetDateTime now = OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC);

                    // Simulate telemetry: panel-3 alternates between OPERATIONAL and
                    // DEGRADED. A real integration maps hardware telemetry to these
                    // states instead of using a timer.
                    boolean panel3Degraded = (update / DEGRADED_FLIP_EVERY) % 2 == 1;

                    // Build one sensor and one health component per panel. The panel ID
                    // links the two.
                    List<Sensor> sensors = new ArrayList<>();
                    List<ComponentHealth> components = new ArrayList<>();
                    boolean anyDegraded = false;
                    for (Panel panel : PANELS) {
                        boolean degraded = panel.id.equals("panel-3") && panel3Degraded;
                        anyDegraded = anyDegraded || degraded;

                        sensors.add(Sensor.builder()
                            .sensorId(panel.id)
                            .sensorDescription(panel.description)
                            .sensorType(SensorSensorType.SENSOR_TYPE_RADAR)
                            .operationalState(degraded
                                ? SensorOperationalState.OPERATIONAL_STATE_DEGRADED
                                : SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                            .fieldsOfView(List.of(FieldOfView.builder()
                                .fovId(1)
                                .centerRayPose(EntityManagerPose.builder()
                                    .pos(Position.builder()
                                        .latitudeDegrees(RADAR_LAT)
                                        .longitudeDegrees(RADAR_LON)
                                        .altitudeHaeMeters(RADAR_HAE)
                                        .build())
                                    .orientation(pointingToQuaternionEnu(panel.azimuthDeg, PANEL_ELEVATION_DEG))
                                    .build())
                                .horizontalFov((float) (Math.PI / 2))
                                .verticalFov((float) (Math.PI / 6))
                                .range(10000.0f)
                                .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                .build()))
                            .build());
                        components.add(ComponentHealth.builder()
                            .id(panel.id)
                            .name(panel.description)
                            .health(degraded
                                ? ComponentHealthHealth.HEALTH_STATUS_WARN
                                : ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                            .messages(List.of(ComponentMessage.builder()
                                .status(degraded
                                    ? ComponentMessageStatus.HEALTH_STATUS_WARN
                                    : ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                                .message(panel.description + (degraded
                                    ? " is operating with reduced capability."
                                    : " is operating normally."))
                                .build()))
                            .updateTime(now)
                            .build());
                    }
                    components.add(ComponentHealth.builder()
                        .id("radar-controller")
                        .name("Radar controller")
                        .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                        .messages(List.of(ComponentMessage.builder()
                            .status(ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                            .message("Radar controller is operating normally.")
                            .build()))
                        .updateTime(now)
                        .build());

                    // The entity is WARN when any panel is degraded.
                    HealthHealthStatus healthStatus = anyDegraded
                        ? HealthHealthStatus.HEALTH_STATUS_WARN
                        : HealthHealthStatus.HEALTH_STATUS_HEALTHY;

                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Four-panel radar asset")
                        .aliases(Aliases.builder()
                            .name("Radar 1")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(
                            latestTimestamp.plus(ENTITY_EXPIRY_MIN, ChronoUnit.MINUTES), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("RADAR")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_LAND)
                            .build())
                        .location(Location.builder()
                            .position(Position.builder()
                                .latitudeDegrees(RADAR_LAT)
                                .longitudeDegrees(RADAR_LON)
                                .altitudeHaeMeters(RADAR_HAE)
                                .build())
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName(INTEGRATION_NAME)
                            .dataType(DATA_TYPE)
                            .sourceUpdateTime(now)
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(healthStatus)
                            .components(components)
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(now)
                            .build())
                        // Publish all panels as sensors on one asset entity.
                        .sensors(Sensors.builder()
                            .sensors(sensors)
                            .build())
                        .build();

                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset with entity ID: " + entityId);

                    Thread.sleep(PUBLISH_INTERVAL_MS);
                } catch (Exception e) {
                    System.err.println("Error publishing entity: " + e.getMessage());
                    Thread.sleep(PUBLISH_INTERVAL_MS);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}

```

```py title={"Python (REST)"} startLine={102} maxLines={75}
# This Python example publishes a four-panel radar as one asset entity. Each
# panel is a sensor on the asset with its own field of view.

import asyncio
import math
import os
import sys
import uuid
from datetime import datetime, timedelta, timezone

from anduril import (
    Aliases,
    ComponentHealth,
    ComponentMessage,
    EntityManagerPose,
    FieldOfView,
    Health,
    Lattice,
    Location,
    MilView,
    Ontology,
    Position,
    Provenance,
    Quaternion,
    Sensor,
    Sensors,
)

RADAR_NAME = "radar-01"
INTEGRATION_NAME = "your_integration_name"
DATA_TYPE = "radar_asset"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY = timedelta(minutes=5)

# Fixed radar position.
RADAR_LATITUDE_DEGREES = 34.0
RADAR_LONGITUDE_DEGREES = -118.0
RADAR_ALTITUDE_HAE_METERS = 100.0

# Elevation of every panel boresight, in degrees above the horizon.
PANEL_ELEVATION_DEGREES = 10.0

# Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
DEGRADED_FLIP_EVERY = 3

# Each panel's sensor ID, display name, and boresight compass azimuth (degrees
# clockwise from true north).
PANELS = [
    {"id": "panel-1", "description": "Panel 1", "azimuth_deg": 0.0},
    {"id": "panel-2", "description": "Panel 2", "azimuth_deg": 90.0},
    {"id": "panel-3", "description": "Panel 3", "azimuth_deg": 180.0},
    {"id": "panel-4", "description": "Panel 4", "azimuth_deg": 270.0},
]


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton
    product, so an azimuth of 90 and an elevation of 0 gives the identity.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


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

# 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}"},
)

# Stable entity ID derived from the radar's name so the same radar maps to the
# same Lattice entity across restarts.
entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, RADAR_NAME))


async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        update_count = 0
        while True:
            latest_timestamp = datetime.now(timezone.utc)

            # Simulate telemetry: panel-3 alternates between OPERATIONAL and
            # DEGRADED. A real integration maps hardware telemetry to these
            # states instead of using a timer.
            panel_3_degraded = (update_count // DEGRADED_FLIP_EVERY) % 2 == 1

            # Build one sensor and one health component per panel. The panel ID
            # links the two.
            sensors = []
            components = []
            any_degraded = False
            for panel in PANELS:
                degraded = panel["id"] == "panel-3" and panel_3_degraded
                any_degraded = any_degraded or degraded

                sensors.append(
                    Sensor(
                        sensor_id=panel["id"],
                        sensor_description=panel["description"],
                        sensor_type="SENSOR_TYPE_RADAR",
                        operational_state="OPERATIONAL_STATE_DEGRADED" if degraded else "OPERATIONAL_STATE_OPERATIONAL",
                        fields_of_view=[
                            FieldOfView(
                                fov_id=1,
                                # The center ray pose is an absolute ENU orientation
                                # positioned at the radar.
                                center_ray_pose=EntityManagerPose(
                                    pos=Position(
                                        latitude_degrees=RADAR_LATITUDE_DEGREES,
                                        longitude_degrees=RADAR_LONGITUDE_DEGREES,
                                        altitude_hae_meters=RADAR_ALTITUDE_HAE_METERS,
                                    ),
                                    orientation=pointing_to_quaternion_enu(panel["azimuth_deg"], PANEL_ELEVATION_DEGREES),
                                ),
                                horizontal_fov=math.pi / 2,
                                vertical_fov=math.pi / 6,
                                range=10000.0,
                                mode="SENSOR_MODE_SEARCH",
                            ),
                        ],
                    )
                )
                panel_health = "HEALTH_STATUS_WARN" if degraded else "HEALTH_STATUS_HEALTHY"
                components.append(
                    ComponentHealth(
                        id=panel["id"],
                        name=panel["description"],
                        health=panel_health,
                        messages=[
                            ComponentMessage(
                                status=panel_health,
                                message=f"{panel['description']} is operating "
                                + ("with reduced capability." if degraded else "normally."),
                            ),
                        ],
                        update_time=latest_timestamp,
                    )
                )
            components.append(
                ComponentHealth(
                    id="radar-controller",
                    name="Radar controller",
                    health="HEALTH_STATUS_HEALTHY",
                    messages=[
                        ComponentMessage(
                            status="HEALTH_STATUS_HEALTHY",
                            message="Radar controller is operating normally.",
                        ),
                    ],
                    update_time=latest_timestamp,
                )
            )

            client.entities.publish_entity(
                entity_id=entity_id,
                description="Four-panel radar asset",
                aliases=Aliases(name="Radar 1"),
                is_live=True,
                created_time=creation_time,
                expiry_time=latest_timestamp + ENTITY_EXPIRY,
                ontology=Ontology(template="TEMPLATE_ASSET", platform_type="RADAR"),
                mil_view=MilView(
                    disposition="DISPOSITION_FRIENDLY",
                    environment="ENVIRONMENT_LAND",
                ),
                location=Location(
                    position=Position(
                        latitude_degrees=RADAR_LATITUDE_DEGREES,
                        longitude_degrees=RADAR_LONGITUDE_DEGREES,
                        altitude_hae_meters=RADAR_ALTITUDE_HAE_METERS,
                    ),
                ),
                provenance=Provenance(
                    integration_name=INTEGRATION_NAME,
                    data_type=DATA_TYPE,
                    source_update_time=latest_timestamp,
                ),
                health=Health(
                    connection_status="CONNECTION_STATUS_ONLINE",
                    # The entity is WARN when any panel is degraded.
                    health_status="HEALTH_STATUS_WARN" if any_degraded else "HEALTH_STATUS_HEALTHY",
                    components=components,
                    active_alerts=[],
                    update_time=latest_timestamp,
                ),
                # Publish all panels as sensors on one asset entity.
                sensors=Sensors(sensors=sensors),
            )
            print(f"Publishing asset with entity ID: {entity_id}")
            update_count += 1
            await asyncio.sleep(PUBLISH_INTERVAL_SEC)

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


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

```

```ts title={"TypeScript (REST)"} startLine={81} maxLines={75}
// This TypeScript example publishes a four-panel radar as one asset entity. Each
// panel is a sensor on the asset with its own field of view.
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v5 as uuidv5 } 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}`  }
    }
);

const radarName = "radar-01";
const integrationName = "your_integration_name";
const dataType = "radar_asset";
const publishIntervalMs = 5000;
const entityExpiryMs = 5 * 60 * 1000;

// Fixed radar position.
const radarLatitudeDegrees = 34.0;
const radarLongitudeDegrees = -118.0;
const radarAltitudeHaeMeters = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const panelElevationDegrees = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const degradedFlipEvery = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
const panels = [
    { id: "panel-1", description: "Panel 1", azimuthDeg: 0 },
    { id: "panel-2", description: "Panel 2", azimuthDeg: 90 },
    { id: "panel-3", description: "Panel 3", azimuthDeg: 180 },
    { id: "panel-4", description: "Panel 4", azimuthDeg: 270 }
];

const degToRad = (degrees: number) => degrees * Math.PI / 180;

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w) that rotates
// the sensor frame, whose +X axis is the boresight, into ENU.
//
// The azimuth is degrees clockwise from true north and the elevation is degrees above the
// horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so
// an azimuth of 90 and an elevation of 0 gives the identity.
function pointingToQuaternionEnu(azimuthDeg: number, elevationDeg: number) {
    const halfYaw = (Math.PI / 2 - degToRad(azimuthDeg)) / 2;
    const halfPitch = -degToRad(elevationDeg) / 2;
    return {
        x: -Math.sin(halfYaw) * Math.sin(halfPitch),
        y: Math.cos(halfYaw) * Math.sin(halfPitch),
        z: Math.sin(halfYaw) * Math.cos(halfPitch),
        w: Math.cos(halfYaw) * Math.cos(halfPitch)
    };
}

let updateCount = 0;

// Stable entity ID derived from the radar's name so the same radar maps to the
// same Lattice entity across restarts.
const entityId = uuidv5(radarName, uuidv5.URL);
const creationTime = new Date().toISOString();

async function App() {
    const latestTimestamp = new Date();
    const now = latestTimestamp.toISOString();

    // Simulate telemetry: panel-3 alternates between OPERATIONAL and DEGRADED. A real
    // integration maps hardware telemetry to these states instead of using a timer.
    const panel3Degraded = Math.floor(updateCount / degradedFlipEvery) % 2 === 1;
    updateCount += 1;

    // Build one sensor and one health component per panel. The panel ID links the two.
    const sensors = [];
    const components = [];
    let anyDegraded = false;
    for (const panel of panels) {
        const degraded = panel.id === "panel-3" && panel3Degraded;
        anyDegraded = anyDegraded || degraded;

        sensors.push({
            sensorId: panel.id,
            sensorDescription: panel.description,
            sensorType: "SENSOR_TYPE_RADAR" as const,
            operationalState: degraded
                ? "OPERATIONAL_STATE_DEGRADED" as const
                : "OPERATIONAL_STATE_OPERATIONAL" as const,
            fieldsOfView: [
                {
                    fovId: 1,
                    // The center ray pose is an absolute ENU orientation positioned at the radar.
                    centerRayPose: {
                        pos: {
                            latitudeDegrees: radarLatitudeDegrees,
                            longitudeDegrees: radarLongitudeDegrees,
                            altitudeHaeMeters: radarAltitudeHaeMeters
                        },
                        orientation: pointingToQuaternionEnu(panel.azimuthDeg, panelElevationDegrees)
                    },
                    horizontalFov: Math.PI / 2,
                    verticalFov: Math.PI / 6,
                    range: 10000.0,
                    mode: "SENSOR_MODE_SEARCH" as const
                }
            ]
        });
        const panelHealth = degraded ? "HEALTH_STATUS_WARN" as const : "HEALTH_STATUS_HEALTHY" as const;
        components.push({
            id: panel.id,
            name: panel.description,
            health: panelHealth,
            messages: [
                {
                    status: panelHealth,
                    message: `${panel.description} is operating ${degraded ? "with reduced capability." : "normally."}`
                }
            ],
            updateTime: now
        });
    }
    components.push({
        id: "radar-controller",
        name: "Radar controller",
        health: "HEALTH_STATUS_HEALTHY" as const,
        messages: [
            {
                status: "HEALTH_STATUS_HEALTHY" as const,
                message: "Radar controller is operating normally."
            }
        ],
        updateTime: now
    });

    try {
        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Four-panel radar asset",
                aliases: { name: "Radar 1" },
                isLive: true,
                createdTime: creationTime,
                expiryTime: new Date(latestTimestamp.getTime() + entityExpiryMs).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "RADAR"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_LAND"
                },
                location: {
                    position: {
                        latitudeDegrees: radarLatitudeDegrees,
                        longitudeDegrees: radarLongitudeDegrees,
                        altitudeHaeMeters: radarAltitudeHaeMeters
                    }
                },
                provenance: {
                    integrationName: integrationName,
                    dataType: dataType,
                    sourceUpdateTime: now
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    // The entity is WARN when any panel is degraded.
                    healthStatus: anyDegraded ? "HEALTH_STATUS_WARN" : "HEALTH_STATUS_HEALTHY",
                    components: components,
                    activeAlerts: [],
                    updateTime: now
                },
                // Publish all panels as sensors on one asset entity.
                sensors: { sensors: sensors }
            }
        );
        console.log(`Publishing asset with entity ID: ${entityId}`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}

(async function runIndefinitely() {
    while (true) {
        await App();
        await new Promise(resolve => setTimeout(resolve, publishIntervalMs));
    }
})();

```

```rs title={"Rust (REST)"} startLine={98} maxLines={75}
// This Rust example publishes a four-panel radar as one asset entity. Each
// panel is a sensor on the asset with its own field of view.
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::f64::consts::PI;
use std::time::Duration;
use uuid::Uuid;

const RADAR_NAME: &str = "radar-01";
const INTEGRATION_NAME: &str = "your_integration_name";
const DATA_TYPE: &str = "radar_asset";
const PUBLISH_INTERVAL: Duration = Duration::from_secs(5);

// Fixed radar position.
const RADAR_LATITUDE_DEGREES: f64 = 34.0;
const RADAR_LONGITUDE_DEGREES: f64 = -118.0;
const RADAR_ALTITUDE_HAE_METERS: f64 = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const PANEL_ELEVATION_DEGREES: f64 = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const DEGRADED_FLIP_EVERY: u32 = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
struct Panel {
    id: &'static str,
    description: &'static str,
    azimuth_deg: f64,
}

const PANELS: [Panel; 4] = [
    Panel { id: "panel-1", description: "Panel 1", azimuth_deg: 0.0 },
    Panel { id: "panel-2", description: "Panel 2", azimuth_deg: 90.0 },
    Panel { id: "panel-3", description: "Panel 3", azimuth_deg: 180.0 },
    Panel { id: "panel-4", description: "Panel 4", azimuth_deg: 270.0 },
];

/// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
///
/// The quaternion rotates the sensor frame, whose +X axis is the boresight, into
/// ENU. The azimuth is degrees clockwise from true north and the elevation is
/// degrees above the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation)
/// using the Hamilton product, so an azimuth of 90 and an elevation of 0 gives
/// the identity.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (PI / 2.0 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: Some(-half_yaw.sin() * half_pitch.sin()),
        y: Some(half_yaw.cos() * half_pitch.sin()),
        z: Some(half_yaw.sin() * half_pitch.cos()),
        w: Some(half_yaw.cos() * half_pitch.cos()),
    }
}

#[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)?;

    // Stable entity ID derived from the radar's name so the same radar maps to
    // the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, RADAR_NAME.as_bytes()).to_string();

    let creation_time = Utc::now().fixed_offset();
    let mut update_count: u32 = 0;
    loop {
        let latest_timestamp = Utc::now().fixed_offset();

        // Simulate telemetry: panel-3 alternates between OPERATIONAL and
        // DEGRADED. A real integration maps hardware telemetry to these
        // states instead of using a timer.
        let panel_3_degraded = (update_count / DEGRADED_FLIP_EVERY) % 2 == 1;

        // Build one sensor and one health component per panel. The panel ID
        // links the two.
        let mut sensors = Vec::new();
        let mut components = Vec::new();
        let mut any_degraded = false;
        for panel in &PANELS {
            let degraded = panel.id == "panel-3" && panel_3_degraded;
            any_degraded = any_degraded || degraded;

            sensors.push(Sensor {
                sensor_id: Some(panel.id.to_string()),
                sensor_description: Some(panel.description.to_string()),
                sensor_type: Some(SensorSensorType::SensorTypeRadar),
                operational_state: Some(if degraded {
                    SensorOperationalState::OperationalStateDegraded
                } else {
                    SensorOperationalState::OperationalStateOperational
                }),
                fields_of_view: Some(vec![FieldOfView {
                    fov_id: Some(1),
                    // The center ray pose is an absolute ENU orientation
                    // positioned at the radar.
                    center_ray_pose: Some(EntityManagerPose {
                        pos: Some(Position {
                            latitude_degrees: Some(RADAR_LATITUDE_DEGREES),
                            longitude_degrees: Some(RADAR_LONGITUDE_DEGREES),
                            altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
                            ..Default::default()
                        }),
                        orientation: Some(pointing_to_quaternion_enu(
                            panel.azimuth_deg,
                            PANEL_ELEVATION_DEGREES,
                        )),
                    }),
                    horizontal_fov: Some(PI / 2.0),
                    vertical_fov: Some(PI / 6.0),
                    range: Some(10000.0),
                    mode: Some(FieldOfViewMode::SensorModeSearch),
                    ..Default::default()
                }]),
                ..Default::default()
            });

            let (panel_health, panel_message_status, panel_message) = if degraded {
                (
                    ComponentHealthHealth::HealthStatusWarn,
                    ComponentMessageStatus::HealthStatusWarn,
                    format!("{} is operating with reduced capability.", panel.description),
                )
            } else {
                (
                    ComponentHealthHealth::HealthStatusHealthy,
                    ComponentMessageStatus::HealthStatusHealthy,
                    format!("{} is operating normally.", panel.description),
                )
            };
            components.push(ComponentHealth {
                id: Some(panel.id.to_string()),
                name: Some(panel.description.to_string()),
                health: Some(panel_health),
                messages: Some(vec![ComponentMessage {
                    status: Some(panel_message_status),
                    message: Some(panel_message),
                }]),
                update_time: Some(latest_timestamp),
            });
        }
        components.push(ComponentHealth {
            id: Some("radar-controller".to_string()),
            name: Some("Radar controller".to_string()),
            health: Some(ComponentHealthHealth::HealthStatusHealthy),
            messages: Some(vec![ComponentMessage {
                status: Some(ComponentMessageStatus::HealthStatusHealthy),
                message: Some("Radar controller is operating normally.".to_string()),
            }]),
            update_time: Some(latest_timestamp),
        });

        let entity = Entity {
            entity_id: Some(entity_id.clone()),
            description: Some("Four-panel radar asset".to_string()),
            aliases: Some(Aliases {
                name: Some("Radar 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::minutes(5)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("RADAR".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentLand),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(Position {
                    latitude_degrees: Some(RADAR_LATITUDE_DEGREES),
                    longitude_degrees: Some(RADAR_LONGITUDE_DEGREES),
                    altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some(INTEGRATION_NAME.to_string()),
                data_type: Some(DATA_TYPE.to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                // The entity is WARN when any panel is degraded.
                health_status: Some(if any_degraded {
                    HealthHealthStatus::HealthStatusWarn
                } else {
                    HealthHealthStatus::HealthStatusHealthy
                }),
                components: Some(components),
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
            }),
            // Publish all panels as sensors on one asset entity.
            sensors: Some(Sensors {
                sensors: Some(sensors),
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", entity_id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        update_count += 1;
        tokio::time::sleep(PUBLISH_INTERVAL).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={116} maxLines={75}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
// It publishes a four-panel radar as one asset entity. Each panel is a sensor
// on the asset with its own field of view.
package main

import (
	"context"
	"fmt"
	"log"
	"math"
	"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"
)

const (
	radarName       = "radar-01"
	integrationName = "your_integration_name"
	dataType        = "radar_asset"
	publishInterval = 5 * time.Second
	entityExpiry    = 5 * time.Minute
	publishTimeout  = 10 * time.Second

	// Fixed radar position.
	radarLat = 34.0
	radarLon = -118.0
	radarHae = 100.0

	// Elevation of every panel boresight, in degrees above the horizon.
	panelElevationDeg = 10.0

	// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
	degradedFlipEvery = 3
)

// panel describes one radar panel and the compass azimuth its boresight faces.
type panel struct {
	id          string
	description string
	azimuthDeg  float64
}

var panels = []panel{
	{"panel-1", "Panel 1", 0},
	{"panel-2", "Panel 2", 90},
	{"panel-3", "Panel 3", 180},
	{"panel-4", "Panel 4", 270},
}

// pointingToQuaternionEnu returns the ENU orientation that points a sensor's
// +X boresight at a compass azimuth (degrees clockwise from true north) and an
// elevation (degrees above the horizon). The quaternion is
// qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton product, so an
// azimuth of 90 and an elevation of 0 gives the identity.
func pointingToQuaternionEnu(azimuthDeg, elevationDeg float64) *_type.Quaternion {
	halfYaw := (math.Pi/2 - azimuthDeg*math.Pi/180) / 2
	halfPitch := -elevationDeg * math.Pi / 180 / 2
	sz, cz := math.Sin(halfYaw), math.Cos(halfYaw)
	sy, cy := math.Sin(halfPitch), math.Cos(halfPitch)
	return &_type.Quaternion{
		X: -sz * sy,
		Y: cz * sy,
		Z: sz * cy,
		W: cz * cy,
	}
}

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

	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		log.Fatalf("Missing required environment variables")
	}

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

	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Stable entity_id derived from the radar's name so the same radar maps to
	// the same Lattice entity across restarts.
	entityId := uuid.NewSHA1(uuid.NameSpaceURL, []byte(radarName)).String()

	creationTimestamp := timestamppb.New(time.Now().UTC())

	// Continuously publish the entity so it does not expire.
	for update := 0; ; update++ {
		latestTimestamp := time.Now().UTC()
		latestTs := timestamppb.New(latestTimestamp)
		ctx, cancel := context.WithTimeout(context.Background(), publishTimeout)

		// Simulate telemetry: panel-3 alternates between OPERATIONAL and
		// DEGRADED. A real integration maps hardware telemetry to these
		// states instead of using a timer.
		panel3Degraded := (update/degradedFlipEvery)%2 == 1

		// Build one sensor and one health component per panel. The panel ID
		// links the two.
		sensors := []*entitymanagerv1.Sensor{}
		components := []*entitymanagerv1.ComponentHealth{}
		anyDegraded := false
		for _, p := range panels {
			degraded := p.id == "panel-3" && panel3Degraded
			anyDegraded = anyDegraded || degraded

			operationalState := entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL
			panelHealth := entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY
			message := p.description + " is operating normally."
			if degraded {
				operationalState = entitymanagerv1.OperationalState_OPERATIONAL_STATE_DEGRADED
				panelHealth = entitymanagerv1.HealthStatus_HEALTH_STATUS_WARN
				message = p.description + " is operating with reduced capability."
			}

			sensors = append(sensors, &entitymanagerv1.Sensor{
				SensorId:          p.id,
				SensorDescription: p.description,
				SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_RADAR,
				OperationalState:  operationalState,
				FieldsOfView: []*entitymanagerv1.FieldOfView{
					{
						FovId: 1,
						CenterRayPose: &entitymanagerv1.Pose{
							Pos: &entitymanagerv1.Position{
								LatitudeDegrees:   radarLat,
								LongitudeDegrees:  radarLon,
								AltitudeHaeMeters: wrapperspb.Double(radarHae),
							},
							Orientation: pointingToQuaternionEnu(p.azimuthDeg, panelElevationDeg),
						},
						HorizontalFov: math.Pi / 2,
						VerticalFov:   math.Pi / 6,
						Range:         wrapperspb.Float(10000.0),
						Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
					},
				},
			})
			components = append(components, &entitymanagerv1.ComponentHealth{
				Id:     p.id,
				Name:   p.description,
				Health: panelHealth,
				Messages: []*entitymanagerv1.ComponentMessage{
					{Status: panelHealth, Message: message},
				},
				UpdateTime: latestTs,
			})
		}
		components = append(components, &entitymanagerv1.ComponentHealth{
			Id:     "radar-controller",
			Name:   "Radar controller",
			Health: entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
			Messages: []*entitymanagerv1.ComponentMessage{
				{
					Status:  entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
					Message: "Radar controller is operating normally.",
				},
			},
			UpdateTime: latestTs,
		})

		// The entity is WARN when any panel is degraded.
		healthStatus := entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY
		if anyDegraded {
			healthStatus = entitymanagerv1.HealthStatus_HEALTH_STATUS_WARN
		}

		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Four-panel radar asset",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Radar 1",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(entityExpiry)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "RADAR",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_LAND,
			},
			Location: &entitymanagerv1.Location{
				Position: &entitymanagerv1.Position{
					LatitudeDegrees:   radarLat,
					LongitudeDegrees:  radarLon,
					AltitudeHaeMeters: wrapperspb.Double(radarHae),
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  integrationName,
				DataType:         dataType,
				SourceUpdateTime: latestTs,
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     healthStatus,
				Components:       components,
				ActiveAlerts:     []*entitymanagerv1.Alert{},
				UpdateTime:       latestTs,
			},
			// Publish all panels as sensors on one asset entity.
			Sensors: &entitymanagerv1.Sensors{Sensors: sensors},
		}

		_, err := client.PublishEntity(ctx, &entitymanagerv1.PublishEntityRequest{Entity: entity})
		cancel()

		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Printf("Publishing asset with entity ID: %s\n", entityId)
		}

		time.Sleep(publishInterval)
	}
}

```

```py title={"Python (gRPC)"} startLine={113} maxLines={75}
# 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
# It publishes a four-panel radar as one asset entity. Each panel is a sensor
# on the asset with its own field of view.

import math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, 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.health_status_pub_pb import (
    ComponentHealth,
    ComponentMessage,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    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 Quaternion

RADAR_NAME = "radar-01"
INTEGRATION_NAME = "your_integration_name"
DATA_TYPE = "radar_asset"
PUBLISH_INTERVAL_SEC = 5
ENTITY_EXPIRY = timedelta(minutes=5)

# Fixed radar position.
RADAR_LATITUDE_DEGREES = 34.0
RADAR_LONGITUDE_DEGREES = -118.0
RADAR_ALTITUDE_HAE_METERS = 100.0

# Elevation of every panel boresight, in degrees above the horizon.
PANEL_ELEVATION_DEGREES = 10.0

# Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
DEGRADED_FLIP_EVERY = 3

# Each panel's sensor ID, display name, and boresight compass azimuth (degrees
# clockwise from true north).
PANELS = [
    {"id": "panel-1", "description": "Panel 1", "azimuth_deg": 0.0},
    {"id": "panel-2", "description": "Panel 2", "azimuth_deg": 90.0},
    {"id": "panel-3", "description": "Panel 3", "azimuth_deg": 180.0},
    {"id": "panel-4", "description": "Panel 4", "azimuth_deg": 270.0},
]


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


def pointing_to_quaternion_enu(azimuth_deg: float, elevation_deg: float) -> Quaternion:
    """Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).

    The quaternion rotates the sensor frame, whose +X axis is the boresight, into ENU.
    The azimuth is degrees clockwise from true north and the elevation is degrees above
    the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation) using the Hamilton
    product, so an azimuth of 90 and an elevation of 0 gives the identity.
    """
    half_yaw = (math.pi / 2 - math.radians(azimuth_deg)) / 2
    half_pitch = -math.radians(elevation_deg) / 2
    return Quaternion(
        x=-math.sin(half_yaw) * math.sin(half_pitch),
        y=math.cos(half_yaw) * math.sin(half_pitch),
        z=math.sin(half_yaw) * math.cos(half_pitch),
        w=math.cos(half_yaw) * math.cos(half_pitch),
    )


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)

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

    # Stable entity_id derived from the radar's name so the same radar maps to
    # the same Lattice entity across restarts.
    entity_id = str(uuid.uuid5(uuid.NAMESPACE_URL, RADAR_NAME))

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

    update_count = 0
    while True:
        latest = datetime.now(timezone.utc)
        latest_ts = to_timestamp(latest)
        expiry_ts = to_timestamp(latest + ENTITY_EXPIRY)

        # Simulate telemetry: panel-3 alternates between OPERATIONAL and
        # DEGRADED. A real integration maps hardware telemetry to these
        # states instead of using a timer.
        panel_3_degraded = (update_count // DEGRADED_FLIP_EVERY) % 2 == 1

        # Build one sensor and one health component per panel. The panel ID
        # links the two.
        sensors = []
        components = []
        any_degraded = False
        for panel in PANELS:
            degraded = panel["id"] == "panel-3" and panel_3_degraded
            any_degraded = any_degraded or degraded

            sensors.append(
                Sensor(
                    sensor_id=panel["id"],
                    sensor_description=panel["description"],
                    sensor_type=SensorType.RADAR,
                    operational_state=OperationalState.DEGRADED if degraded else OperationalState.OPERATIONAL,
                    fields_of_view=[
                        FieldOfView(
                            fov_id=1,
                            # The center ray pose is an absolute ENU orientation
                            # positioned at the radar.
                            center_ray_pose=Pose(
                                pos=Position(
                                    latitude_degrees=RADAR_LATITUDE_DEGREES,
                                    longitude_degrees=RADAR_LONGITUDE_DEGREES,
                                    altitude_hae_meters=DoubleValue(value=RADAR_ALTITUDE_HAE_METERS),
                                ),
                                orientation=pointing_to_quaternion_enu(panel["azimuth_deg"], PANEL_ELEVATION_DEGREES),
                            ),
                            horizontal_fov=math.pi / 2,
                            vertical_fov=math.pi / 6,
                            range=FloatValue(value=10000.0),
                            mode=SensorMode.SEARCH,
                        ),
                    ],
                )
            )
            panel_health = HealthStatus.WARN if degraded else HealthStatus.HEALTHY
            components.append(
                ComponentHealth(
                    id=panel["id"],
                    name=panel["description"],
                    health=panel_health,
                    messages=[
                        ComponentMessage(
                            status=panel_health,
                            message=f"{panel['description']} is operating "
                            + ("with reduced capability." if degraded else "normally."),
                        ),
                    ],
                    update_time=latest_ts,
                )
            )
        components.append(
            ComponentHealth(
                id="radar-controller",
                name="Radar controller",
                health=HealthStatus.HEALTHY,
                messages=[
                    ComponentMessage(
                        status=HealthStatus.HEALTHY,
                        message="Radar controller is operating normally.",
                    ),
                ],
                update_time=latest_ts,
            )
        )

        entity = Entity(
            entity_id=entity_id,
            description="Four-panel radar asset",
            aliases=Aliases(name="Radar 1"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="RADAR"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.LAND,
            ),
            location=Location(
                position=Position(
                    latitude_degrees=RADAR_LATITUDE_DEGREES,
                    longitude_degrees=RADAR_LONGITUDE_DEGREES,
                    altitude_hae_meters=DoubleValue(value=RADAR_ALTITUDE_HAE_METERS),
                ),
            ),
            provenance=Provenance(
                integration_name=INTEGRATION_NAME,
                data_type=DATA_TYPE,
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                # The entity is WARN when any panel is degraded.
                health_status=HealthStatus.WARN if any_degraded else HealthStatus.HEALTHY,
                components=components,
                active_alerts=[],
                update_time=latest_ts,
            ),
            # Publish all panels as sensors on one asset entity.
            sensors=Sensors(sensors=sensors),
        )

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

        update_count += 1
        time.sleep(PUBLISH_INTERVAL_SEC)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={150} maxLines={75}
// 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
// It publishes a four-panel radar as one asset entity. Each panel is a sensor
// on the asset with its own field of view.
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    Aliases, ComponentHealth, ComponentMessage, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position, Provenance,
    PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::Quaternion;
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::f64::consts::PI;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const RADAR_NAME: &str = "radar-01";
const INTEGRATION_NAME: &str = "your_integration_name";
const DATA_TYPE: &str = "radar_asset";
const PUBLISH_INTERVAL: Duration = Duration::from_secs(5);
const ENTITY_EXPIRY_SECS: i64 = 5 * 60;

// Fixed radar position.
const RADAR_LATITUDE_DEGREES: f64 = 34.0;
const RADAR_LONGITUDE_DEGREES: f64 = -118.0;
const RADAR_ALTITUDE_HAE_METERS: f64 = 100.0;

// Elevation of every panel boresight, in degrees above the horizon.
const PANEL_ELEVATION_DEGREES: f64 = 10.0;

// Panel 3 flips between OPERATIONAL and DEGRADED every this many updates.
const DEGRADED_FLIP_EVERY: u32 = 3;

// Each panel's sensor ID, display name, and boresight compass azimuth (degrees
// clockwise from true north).
struct Panel {
    id: &'static str,
    description: &'static str,
    azimuth_deg: f64,
}

const PANELS: [Panel; 4] = [
    Panel { id: "panel-1", description: "Panel 1", azimuth_deg: 0.0 },
    Panel { id: "panel-2", description: "Panel 2", azimuth_deg: 90.0 },
    Panel { id: "panel-3", description: "Panel 3", azimuth_deg: 180.0 },
    Panel { id: "panel-4", description: "Panel 4", azimuth_deg: 270.0 },
];

// Convert a compass azimuth and elevation into an ENU quaternion (x, y, z, w).
//
// The quaternion rotates the sensor frame, whose +X axis is the boresight, into
// ENU. The azimuth is degrees clockwise from true north and the elevation is
// degrees above the horizon. The result is qz(pi/2 - azimuth) * qy(-elevation)
// using the Hamilton product, so an azimuth of 90 and an elevation of 0 gives
// the identity.
fn pointing_to_quaternion_enu(azimuth_deg: f64, elevation_deg: f64) -> Quaternion {
    let half_yaw = (PI / 2.0 - azimuth_deg.to_radians()) / 2.0;
    let half_pitch = -elevation_deg.to_radians() / 2.0;
    Quaternion {
        x: -half_yaw.sin() * half_pitch.sin(),
        y: half_yaw.cos() * half_pitch.sin(),
        z: half_yaw.sin() * half_pitch.cos(),
        w: half_yaw.cos() * half_pitch.cos(),
    }
}

// The radar position, shared by the entity location and each field of view.
fn radar_position() -> Position {
    Position {
        latitude_degrees: RADAR_LATITUDE_DEGREES,
        longitude_degrees: RADAR_LONGITUDE_DEGREES,
        altitude_hae_meters: Some(RADAR_ALTITUDE_HAE_METERS),
        ..Default::default()
    }
}

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");

    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)
        },
    );

    // Stable entity_id derived from the radar's name so the same radar maps to
    // the same Lattice entity across restarts.
    let entity_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, RADAR_NAME.as_bytes()).to_string();

    let creation_timestamp = now_timestamp();
    let mut update_count: u32 = 0;

    // Continuously publish the entity so it does not expire.
    loop {
        let latest_timestamp = now_timestamp();

        // Simulate telemetry: panel-3 alternates between OPERATIONAL and
        // DEGRADED. A real integration maps hardware telemetry to these
        // states instead of using a timer.
        let panel_3_degraded = (update_count / DEGRADED_FLIP_EVERY) % 2 == 1;

        // Build one sensor and one health component per panel. The panel ID
        // links the two.
        let mut sensors = Vec::new();
        let mut components = Vec::new();
        let mut any_degraded = false;
        for panel in &PANELS {
            let degraded = panel.id == "panel-3" && panel_3_degraded;
            any_degraded = any_degraded || degraded;

            sensors.push(Sensor {
                sensor_id: panel.id.to_string(),
                sensor_description: panel.description.to_string(),
                sensor_type: SensorType::Radar as i32,
                operational_state: if degraded {
                    OperationalState::Degraded as i32
                } else {
                    OperationalState::Operational as i32
                },
                fields_of_view: vec![FieldOfView {
                    fov_id: 1,
                    // The center ray pose is an absolute ENU orientation
                    // positioned at the radar.
                    center_ray_pose: Some(Pose {
                        pos: Some(radar_position()),
                        orientation: Some(pointing_to_quaternion_enu(
                            panel.azimuth_deg,
                            PANEL_ELEVATION_DEGREES,
                        )),
                    }),
                    horizontal_fov: (PI / 2.0) as f32,
                    vertical_fov: (PI / 6.0) as f32,
                    range: Some(10000.0),
                    mode: SensorMode::Search as i32,
                    ..Default::default()
                }],
                ..Default::default()
            });

            let (panel_health, panel_message) = if degraded {
                (
                    HealthStatus::Warn,
                    format!("{} is operating with reduced capability.", panel.description),
                )
            } else {
                (
                    HealthStatus::Healthy,
                    format!("{} is operating normally.", panel.description),
                )
            };
            components.push(ComponentHealth {
                id: panel.id.to_string(),
                name: panel.description.to_string(),
                health: panel_health as i32,
                messages: vec![ComponentMessage {
                    status: panel_health as i32,
                    message: panel_message,
                }],
                update_time: Some(latest_timestamp),
            });
        }
        components.push(ComponentHealth {
            id: "radar-controller".to_string(),
            name: "Radar controller".to_string(),
            health: HealthStatus::Healthy as i32,
            messages: vec![ComponentMessage {
                status: HealthStatus::Healthy as i32,
                message: "Radar controller is operating normally.".to_string(),
            }],
            update_time: Some(latest_timestamp),
        });

        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Four-panel radar asset".to_string(),
            aliases: Some(Aliases {
                name: "Radar 1".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp),
            expiry_time: Some(add_seconds(&latest_timestamp, ENTITY_EXPIRY_SECS)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "RADAR".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Land as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(radar_position()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: INTEGRATION_NAME.to_string(),
                data_type: DATA_TYPE.to_string(),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                // The entity is WARN when any panel is degraded.
                health_status: if any_degraded {
                    HealthStatus::Warn as i32
                } else {
                    HealthStatus::Healthy as i32
                },
                components,
                active_alerts: vec![],
                update_time: Some(latest_timestamp),
            }),
            // Publish all panels as sensors on one asset entity.
            sensors: Some(Sensors { sensors }),
            ..Default::default()
        };

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

        update_count += 1;
        tokio::time::sleep(PUBLISH_INTERVAL).await;
    }
}

```

## Example: UxV with onboard sensors

A UxV, such as a drone, reports how it moves as well as what its sensors see.
In this example, a small uncrewed aircraft flies a wide circle at 20 meters per second while it
carries two sensors:

* An EO/IR camera on a gimbal that sweeps from side to side, relative to the aircraft's nose.
* An RF direction finder fixed to the airframe, which listens in every direction.

Because each field of view is an absolute ENU orientation, the integration combines the
aircraft's attitude with each sensor's mount angles on every update.

#### Define the entity

Define the vehicle's components. At one instant, while the aircraft flies on a course of 30
degrees and climbs, you get the following entity object:

**`uxv.json`**

```json maxLines=25 title="uxv.json"
{
  "entityId": "UNIQUE_ENTITY_ID",
  "description": "Friendly drone asset",
  "isLive": true,
  "createdTime": "2026-11-06T19:00:00Z",
  "expiryTime": "2026-11-06T20:00:10Z",
  "aliases": { "name": "Drone 1" },
  "ontology": { "template": "TEMPLATE_ASSET", "platformType": "UAV" },
  "milView": { "disposition": "DISPOSITION_FRIENDLY", "environment": "ENVIRONMENT_AIR" },
  "location": {
    "position": {
      "latitudeDegrees": 50.91570322,
      "longitudeDegrees": 0.79280022,
      "altitudeHaeMeters": 317.3205
    },
    "velocityEnu": { "e": 10.0, "n": 17.3205, "u": 1.0472 },
    "attitudeEnu": { "x": 0.05907, "y": 0.00395, "z": 0.50033, "w": 0.86381 }
  },
  "health": {
    "connectionStatus": "CONNECTION_STATUS_ONLINE",
    "healthStatus": "HEALTH_STATUS_HEALTHY",
    "components": [
      {
        "id": "battery-0",
        "name": "Battery",
        "health": "HEALTH_STATUS_HEALTHY",
        "messages": [{ "status": "HEALTH_STATUS_HEALTHY", "message": "Battery at 87% charge." }]
      },
      { "id": "eoir-1", "name": "EO/IR gimbal", "health": "HEALTH_STATUS_HEALTHY" },
      { "id": "rf-1", "name": "RF direction finder", "health": "HEALTH_STATUS_HEALTHY" }
    ],
    "activeAlerts": []
  },
  "sensors": {
    "sensors": [
      {
        "sensorId": "eoir-1",
        "sensorType": "SENSOR_TYPE_CAMERA",
        "operationalState": "OPERATIONAL_STATE_OPERATIONAL",
        "sensorDescription": "EO/IR gimbal",
        "fieldsOfView": [
          {
            "centerRayPose": {
              "pos": { "latitudeDegrees": 50.91570322, "longitudeDegrees": 0.79280022, "altitudeHaeMeters": 317.3205 },
              "orientation": { "x": 0.02939, "y": 0.19768, "z": 0.13889, "w": 0.96993 }
            },
            "horizontalFov": 0.5,
            "verticalFov": 0.3,
            "range": 3000.0,
            "mode": "SENSOR_MODE_SEARCH"
          }
        ]
      },
      {
        "sensorId": "rf-1",
        "sensorType": "SENSOR_TYPE_RF",
        "operationalState": "OPERATIONAL_STATE_OPERATIONAL",
        "sensorDescription": "RF direction finder",
        "fieldsOfView": [
          {
            "centerRayPose": {
              "pos": { "latitudeDegrees": 50.91570322, "longitudeDegrees": 0.79280022, "altitudeHaeMeters": 317.3205 },
              "orientation": { "x": 0.05907, "y": 0.00395, "z": 0.50033, "w": 0.86381 }
            },
            "horizontalFov": 6.28319,
            "verticalFov": 1.0,
            "range": 10000.0,
            "mode": "SENSOR_MODE_SEARCH"
          }
        ]
      }
    ]
  },
  "taskCatalog": {
    "taskDefinitions": [
      { "taskSpecificationUrl": "type.googleapis.com/anduril.tasks.v2.VisualId" },
      { "taskSpecificationUrl": "type.googleapis.com/anduril.tasks.v2.Investigate" }
    ]
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "your_data_type",
    "sourceUpdateTime": "2026-11-06T19:00:10Z"
  }
}
```

The `taskCatalog` advertises the tasks the vehicle accepts. For more information, see
[Integrate an agent](/guides/tasks/integrate-an-agent).

#### Report motion

A moving asset reports its position, velocity, and attitude in `location`:

**`location.velocity_enu`** `ENU`

The vehicle's velocity in meters per second, in east, north, and up components. Autopilots
usually report ground speed `s` and course `c` instead, which convert as
`e = s · sin(c)` and `n = s · cos(c)`. Set `u` to the climb rate.

---

**`location.attitude_enu`** `Quaternion`

The rotation from the vehicle's front-left-up body frame into ENU. Build it from the
autopilot's heading, pitch, and roll as `qz(π/2 − heading) ⊗ qy(−pitch) ⊗ qx(roll)`,
where pitch is positive nose up and roll is positive right wing down.

---

The example defines helpers for both rotations: `attitudeToQuaternionEnu` builds the vehicle's
attitude, and `gimbalToQuaternionEnu` combines that attitude with a sensor's mount angles. If your
autopilot reports only velocity, the fallback helpers derive a heading from the velocity
vector instead:

```go title={"Go (REST)"} startLine={53} maxLines={28}
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the SDK type.
func toQuaternion(q quat) *Lattice.Quaternion {
	return &Lattice.Quaternion{
		X: Lattice.Float64(q.x),
		Y: Lattice.Float64(q.y),
		Z: Lattice.Float64(q.z),
		W: Lattice.Float64(q.w),
	}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTime := time.Now().UTC()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *Lattice.Position {
			return &Lattice.Position{
				LatitudeDegrees:   Lattice.Float64(state.lat),
				LongitudeDegrees:  Lattice.Float64(state.lon),
				AltitudeHaeMeters: Lattice.Float64(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Friendly drone asset"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Drone 1"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("UAV"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
			},
			Location: &Lattice.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &Lattice.Enu{
					E: Lattice.Float64(state.velEast),
					N: Lattice.Float64(state.velNorth),
					U: Lattice.Float64(state.climb),
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("your_data_type"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*Lattice.ComponentHealth{
					{
						ID:     Lattice.String("battery-0"),
						Name:   Lattice.String("Battery"),
						Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						Messages: []*Lattice.ComponentMessage{
							{
								Status:  Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
								Message: Lattice.String(fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent)),
							},
						},
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("eoir-1"),
						Name:       Lattice.String("EO/IR gimbal"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("rf-1"),
						Name:       Lattice.String("RF direction finder"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*Lattice.Alert{},
				UpdateTime:   Lattice.Time(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &Lattice.Sensors{
				Sensors: []*Lattice.Sensor{
					{
						SensorID:          Lattice.String("eoir-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
						SensorDescription: Lattice.String("EO/IR gimbal"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: Lattice.Float64(0.5),
								VerticalFov:   Lattice.Float64(0.3),
								Range:         Lattice.Float64(3000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
					{
						SensorID:          Lattice.String("rf-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeRf.Ptr(),
						SensorDescription: Lattice.String("RF direction finder"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: Lattice.Float64(2 * math.Pi), // Omnidirectional.
								VerticalFov:   Lattice.Float64(1.0),
								Range:         Lattice.Float64(10000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
				},
			},
			TaskCatalog: &Lattice.TaskCatalog{
				TaskDefinitions: []*Lattice.TaskDefinition{
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.VisualId")},
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.Investigate")},
				},
			},
		}

		// 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 asset")
		}

		// Wait before next request
		time.Sleep(1 * time.Second)
	}
}

```

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

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.Aliases;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.ComponentMessage;
import com.anduril.types.ComponentMessageStatus;
import com.anduril.types.Enu;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
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.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TaskCatalog;
import com.anduril.types.TaskDefinition;



public class PublishAssetDrone {
    // Flight model constants.
    private static final double TICK_SECONDS = 1.0;          // Time between updates, in seconds.
    private static final double GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
    private static final double TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
    private static final double BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
    private static final double ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
    private static final double ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
    private static final double GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
    private static final double GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
    private static final double GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
    private static final double GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
    private static final double METERS_PER_DEG = 111320.0;

    // Set to false to derive the attitude from velocity alone.
    private static final boolean AUTOPILOT_REPORTS_ATTITUDE = true;

    // Simulated state of the vehicle.
    private static class FlightState {
        double lat = 50.914;      // Degrees.
        double lon = 0.792;       // Degrees.
        double altHae = BASE_ALT_HAE;
        double courseDeg = 0.0;   // Direction of travel, degrees clockwise from north.
        double velEast, velNorth, climb; // Meters per second.
        double pitchDeg;          // Positive nose up.
        double rollDeg;           // Positive right wing down.
        double elapsed = 0.0;     // Seconds since start.
    }

    // Move the simulation forward by dt seconds.
    private static void advanceState(FlightState s, double dt) {
        s.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        s.courseDeg = (s.courseDeg + TURN_RATE_DEG_SEC * dt) % 360.0;
        double w = 2 * Math.PI / ALT_PERIOD;
        s.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * s.elapsed);
        s.climb = ALT_AMPLITUDE * w * Math.cos(w * s.elapsed);

        // Velocity from ground speed, course, and climb rate.
        double course = Math.toRadians(s.courseDeg);
        s.velEast = GROUND_SPEED * Math.sin(course);
        s.velNorth = GROUND_SPEED * Math.cos(course);

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        s.lat += s.velNorth * dt / METERS_PER_DEG;
        s.lon += s.velEast * dt / (METERS_PER_DEG * Math.cos(Math.toRadians(s.lat)));

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        s.pitchDeg = Math.toDegrees(Math.atan2(s.climb, GROUND_SPEED));
        s.rollDeg = Math.toDegrees(Math.atan(GROUND_SPEED * Math.toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
    }

    // Hamilton product a * b of two quaternions in {x, y, z, w} order.
    private static double[] multiply(double[] a, double[] b) {
        return new double[] {
            a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
            a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
            a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
            a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
        };
    }

    // Elementary rotations about the x, y, and z axes, in radians.
    private static double[] qx(double a) { return new double[] {Math.sin(a / 2), 0, 0, Math.cos(a / 2)}; }
    private static double[] qy(double a) { return new double[] {0, Math.sin(a / 2), 0, Math.cos(a / 2)}; }
    private static double[] qz(double a) { return new double[] {0, 0, Math.sin(a / 2), Math.cos(a / 2)}; }

    // Convert a compass heading (degrees clockwise from north), pitch
    // (positive nose up), and roll (positive right wing down) into the
    // attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
    // the ENU world frame.
    private static double[] attitudeToQuaternionEnu(double headingDeg, double pitchDeg, double rollDeg) {
        double yaw = Math.PI / 2 - Math.toRadians(headingDeg);
        return multiply(multiply(qz(yaw), qy(-Math.toRadians(pitchDeg))), qx(Math.toRadians(rollDeg)));
    }

    // Compose the body attitude with a gimbal pointing relative to the nose.
    // Pan is positive to the right and tilt is positive up. The result
    // rotates the sensor frame (+X is the boresight) into ENU.
    private static double[] gimbalToQuaternionEnu(double[] body, double panDeg, double tiltDeg) {
        double[] mount = multiply(qz(-Math.toRadians(panDeg)), qy(-Math.toRadians(tiltDeg)));
        return multiply(body, mount);
    }

    // Convert an ENU velocity vector into a yaw angle, in radians. Fallback
    // when your autopilot reports only velocity.
    private static double velocityToYawEnu(double velocityEast, double velocityNorth) {
        return Math.atan2(velocityNorth, velocityEast);
    }

    // Convert a yaw angle into an attitude_enu quaternion with zero pitch and
    // roll. Fallback when your autopilot reports only velocity.
    private static double[] yawToQuaternionEnu(double yawRad) {
        return qz(yawRad);
    }

    // Convert an {x, y, z, w} array into the SDK type.
    private static Quaternion toQuaternion(double[] q) {
        return Quaternion.builder().x(q[0]).y(q[1]).z(q[2]).w(q[3]).build();
    }

    private static Position position(FlightState s) {
        return Position.builder()
            .latitudeDegrees(s.lat)
            .longitudeDegrees(s.lon)
            .altitudeHaeMeters(s.altHae)
            .build();
    }

    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;
        
        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 entityId = UUID.randomUUID().toString();
            
            // Start near the origin, heading north.
            FlightState state = new FlightState();
            Instant creationTime = Instant.now();

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

                    advanceState(state, TICK_SECONDS);

                    // Heading equals course because the simulation has no wind.
                    double[] bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
                        ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
                        : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
                    // The gimbal sweeps relative to the nose. FieldOfView
                    // orientation is absolute ENU, so compose it with the
                    // body attitude.
                    double gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
                    double[] gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
                    double batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);
                    
                    // Create the entity
                    TaskDefinition visualId = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.VisualId")
                        .build();

                    TaskDefinition investigate = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.Investigate")
                        .build();

                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Friendly drone asset")
                        .aliases(Aliases.builder()
                            .name("Drone 1")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(1, ChronoUnit.HOURS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("UAV")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_AIR)
                            .build())
                        .location(Location.builder()
                            .position(position(state))
                            // Velocity in the ENU frame, in meters per second.
                            .velocityEnu(Enu.builder()
                                .e(state.velEast)
                                .n(state.velNorth)
                                .u(state.climb)
                                .build())
                            // Body-to-ENU attitude. Lattice uses it for heading.
                            .attitudeEnu(toQuaternion(bodyQuat))
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("your_data_type")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(HealthHealthStatus.HEALTH_STATUS_HEALTHY)
                            // Report the health of individual subsystems in
                            // components. Each component needs a stable id, a
                            // display name, and a health status.
                            .components(List.of(
                                ComponentHealth.builder()
                                    .id("battery-0")
                                    .name("Battery")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .messages(List.of(
                                        ComponentMessage.builder()
                                            .status(ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                                            .message(String.format("Battery at %.0f%% charge.", batteryPercent))
                                            .build()
                                    ))
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("eoir-1")
                                    .name("EO/IR gimbal")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("rf-1")
                                    .name("RF direction finder")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build()
                            ))
                            // Live list of active alerts for the asset. Remove
                            // entries when the underlying condition clears;
                            // Lattice does not filter stale entries
                            // automatically.
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        // Declare the sensors carried by the asset. Each
                        // entry requires a stable sensor_id, a sensor_type,
                        // and at least one field of view so Lattice can
                        // render the sensor cone.
                        .sensors(Sensors.builder()
                            .sensors(List.of(
                                Sensor.builder()
                                    .sensorId("eoir-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                    .sensorDescription("EO/IR gimbal")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(gimbalQuat))
                                                .build())
                                            .horizontalFov(0.5f)
                                            .verticalFov(0.3f)
                                            .range(3000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build(),
                                Sensor.builder()
                                    .sensorId("rf-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_RF)
                                    .sensorDescription("RF direction finder")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        // Body-fixed, forward-facing mount.
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(bodyQuat))
                                                .build())
                                            .horizontalFov((float) (2 * Math.PI)) // Omnidirectional.
                                            .verticalFov(1.0f)
                                            .range(10000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build()
                            ))
                            .build())
                        .taskCatalog(TaskCatalog.builder()
                            .taskDefinitions(Arrays.asList(visualId, investigate))
                            .build())
                        .build();
                    
                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset.");
                    
                    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={69} maxLines={33}
from anduril import Lattice, Aliases, MilView, Location, Position,\
      Ontology, Provenance, Health, ComponentHealth, ComponentMessage,\
      TaskCatalog, TaskDefinition,\
      Sensors, Sensor, FieldOfView, EntityManagerPose, Quaternion, Enu
from datetime import datetime, timezone, timedelta
import asyncio
import math
import os
import sys
from uuid import uuid4

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

# 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}" }
)
id = str(uuid4())

# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )

def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))

def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))

def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))

def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))

def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)

def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)

def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)

def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the SDK type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])

def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))

async def app():
    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    creation_time = datetime.now(timezone.utc)
    try:
        while True:
            latest_timestamp = datetime.now(timezone.utc)
            advance_state(state, TICK_SECONDS)

            # Heading equals course because the simulation has no wind.
            if AUTOPILOT_REPORTS_ATTITUDE:
                body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
            else:
                body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
            position = Position(
                latitude_degrees=state["lat"],
                longitude_degrees=state["lon"],
                altitude_hae_meters=state["alt_hae"]
            )
            # The gimbal sweeps relative to the nose. FieldOfView orientation
            # is absolute ENU, so compose it with the body attitude.
            gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
            gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
            battery_percent = max(87 - 0.01 * state["elapsed"], 0)

            try:
                client.entities.publish_entity(
                    entity_id=id,
                    description="Friendly drone asset",
                    aliases=Aliases(
                        name="Drone 1"
                    ),
                    is_live=True,
                    created_time=creation_time,
                    expiry_time=latest_timestamp + timedelta(hours=1),
                    ontology=Ontology(
                        template="TEMPLATE_ASSET",
                        platform_type="UAV"
                    ),
                    mil_view=MilView(
                        disposition="DISPOSITION_FRIENDLY",
                        environment="ENVIRONMENT_AIR"
                    ),
                    location=Location(
                        position=position,
                        # Velocity in the ENU frame, in meters per second.
                        velocity_enu=Enu(
                            e=state["vel_east"],
                            n=state["vel_north"],
                            u=state["climb"]
                        ),
                        # Body-to-ENU attitude. Lattice uses it for heading.
                        attitude_enu=to_quaternion(body_quat)
                    ),
                    provenance=Provenance(
                        integration_name="your_integration_name",
                        data_type="your_data_type",
                        source_update_time=latest_timestamp
                    ),
                    health=Health(
                        connection_status="CONNECTION_STATUS_ONLINE",
                        health_status="HEALTH_STATUS_HEALTHY",
                        # Report the health of individual subsystems in
                        # components. Each component needs a stable id, a
                        # display name, and a health status.
                        components=[
                            ComponentHealth(
                                id="battery-0",
                                name="Battery",
                                health="HEALTH_STATUS_HEALTHY",
                                messages=[
                                    ComponentMessage(
                                        status="HEALTH_STATUS_HEALTHY",
                                        message=f"Battery at {battery_percent:.0f}% charge.",
                                    ),
                                ],
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="eoir-1",
                                name="EO/IR gimbal",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="rf-1",
                                name="RF direction finder",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                        ],
                        # Live list of active alerts for the asset. Remove
                        # entries when the underlying condition clears;
                        # Lattice does not filter stale entries
                        # automatically.
                        active_alerts=[],
                        update_time=latest_timestamp
                    ),
                    # Declare the sensors carried by the asset. Each entry
                    # requires a stable sensor_id, a sensor_type, and at
                    # least one field of view so Lattice can render the
                    # sensor cone.
                    sensors=Sensors(
                        sensors=[
                            Sensor(
                                sensor_id="eoir-1",
                                sensor_type="SENSOR_TYPE_CAMERA",
                                sensor_description="EO/IR gimbal",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(gimbal_quat),
                                        ),
                                        horizontal_fov=0.5,
                                        vertical_fov=0.3,
                                        range=3000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                            Sensor(
                                sensor_id="rf-1",
                                sensor_type="SENSOR_TYPE_RF",
                                sensor_description="RF direction finder",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    # Body-fixed, forward-facing mount.
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(body_quat),
                                        ),
                                        horizontal_fov=2 * math.pi,  # Omnidirectional.
                                        vertical_fov=1.0,
                                        range=10000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                        ],
                    ),
                    task_catalog=TaskCatalog(
                        task_definitions=[
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId" ),
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate" )
                        ]
                    )
                )
                print("Publishing asset.")
            except Exception as error:
                print(f"Error publishing entity: {error}")
            await asyncio.sleep(TICK_SECONDS)

    except asyncio.CancelledError:
        print(">>> Exiting...")

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

```

```ts title={"TypeScript (REST)"} startLine={68} maxLines={28}
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}`  }
    }
);

const entityId = uuidv4()
const expiryOffsetHours = 1;
const createdTime = new Date();

// Flight model constants.
const TICK_SECONDS = 1.0;          // Time between updates, in seconds.
const GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
const BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
const ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE = true;

function toRadians(degrees: number): number {
    return degrees * (Math.PI / 180);
}

function toDegrees(radians: number): number {
    return radians * (180 / Math.PI);
}

type Quat = { x: number; y: number; z: number; w: number };

// Hamilton product a * b.
function multiply(a: Quat, b: Quat): Quat {
    return {
        x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
        y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
        z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
        w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
    };
}

// Elementary rotations about the x, y, and z axes, in radians.
const qx = (a: number): Quat => ({ x: Math.sin(a / 2), y: 0, z: 0, w: Math.cos(a / 2) });
const qy = (a: number): Quat => ({ x: 0, y: Math.sin(a / 2), z: 0, w: Math.cos(a / 2) });
const qz = (a: number): Quat => ({ x: 0, y: 0, z: Math.sin(a / 2), w: Math.cos(a / 2) });

// Convert a compass heading (degrees clockwise from north), pitch (positive
// nose up), and roll (positive right wing down) into the attitude_enu
// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
// frame.
function attitudeToQuaternionEnu(headingDeg: number, pitchDeg: number, rollDeg: number): Quat {
    const yaw = Math.PI / 2 - toRadians(headingDeg);
    return multiply(multiply(qz(yaw), qy(-toRadians(pitchDeg))), qx(toRadians(rollDeg)));
}

// Compose the body attitude with a gimbal pointing relative to the nose. Pan
// is positive to the right and tilt is positive up. The result rotates the
// sensor frame (+X is the boresight) into ENU.
function gimbalToQuaternionEnu(body: Quat, panDeg: number, tiltDeg: number): Quat {
    const mount = multiply(qz(-toRadians(panDeg)), qy(-toRadians(tiltDeg)));
    return multiply(body, mount);
}

// Convert an ENU velocity vector into a yaw angle, in radians. Fallback when
// your autopilot reports only velocity.
function velocityToYawEnu(velocityEast: number, velocityNorth: number): number {
    return Math.atan2(velocityNorth, velocityEast);
}

// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
// roll. Fallback when your autopilot reports only velocity.
function yawToQuaternionEnu(yawRad: number): Quat {
    return qz(yawRad);
}

// Simulated state of the vehicle. Starts near the origin, heading north.
const state = {
    lat: 50.914,        // Degrees.
    lon: 0.792,         // Degrees.
    altHae: BASE_ALT_HAE,
    courseDeg: 0,       // Direction of travel, degrees clockwise from north.
    velEast: 0,         // Meters per second.
    velNorth: 0,
    climb: 0,
    pitchDeg: 0,        // Positive nose up.
    rollDeg: 0,         // Positive right wing down.
    elapsed: 0,         // Seconds since start.
};

// Move the simulation forward by dt seconds.
function advanceState(dt: number) {
    state.elapsed += dt;

    // Turn at a constant rate and oscillate the altitude.
    state.courseDeg = (state.courseDeg + TURN_RATE_DEG_SEC * dt) % 360;
    const w = 2 * Math.PI / ALT_PERIOD;
    state.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * state.elapsed);
    state.climb = ALT_AMPLITUDE * w * Math.cos(w * state.elapsed);

    // Velocity from ground speed, course, and climb rate.
    const course = toRadians(state.courseDeg);
    state.velEast = GROUND_SPEED * Math.sin(course);
    state.velNorth = GROUND_SPEED * Math.cos(course);

    // Integrate position: meters to degrees, scaling longitude by cos(lat).
    state.lat += state.velNorth * dt / METERS_PER_DEG;
    state.lon += state.velEast * dt / (METERS_PER_DEG * Math.cos(toRadians(state.lat)));

    // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    state.pitchDeg = toDegrees(Math.atan2(state.climb, GROUND_SPEED));
    state.rollDeg = toDegrees(Math.atan(GROUND_SPEED * toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
}

async function App() {
    try {
        const latestTimestamp = new Date();
        advanceState(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        const bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
            ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
            : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
        const position = {
            latitudeDegrees: state.lat,
            longitudeDegrees: state.lon,
            altitudeHaeMeters: state.altHae,
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        const gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
        const gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
        const batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);

        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Friendly drone asset",
                aliases: { name: "Drone 1" },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + expiryOffsetHours * 3600000).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "UAV"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_AIR",
                },
                location: {
                    position: position,
                    // Velocity in the ENU frame, in meters per second.
                    velocityEnu: { e: state.velEast, n: state.velNorth, u: state.climb },
                    // Body-to-ENU attitude. Lattice uses it for heading.
                    attitudeEnu: bodyQuat
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "your_data_type",
                    sourceUpdateTime: latestTimestamp.toISOString()
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    healthStatus: "HEALTH_STATUS_HEALTHY",
                    // Report the health of individual subsystems in
                    // components. Each component needs a stable id, a display
                    // name, and a health status.
                    components: [
                        {
                            id: "battery-0",
                            name: "Battery",
                            health: "HEALTH_STATUS_HEALTHY",
                            messages: [
                                {
                                    status: "HEALTH_STATUS_HEALTHY",
                                    message: `Battery at ${batteryPercent.toFixed(0)}% charge.`
                                }
                            ],
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "eoir-1",
                            name: "EO/IR gimbal",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "rf-1",
                            name: "RF direction finder",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        }
                    ],
                    // Live list of active alerts for the asset. Remove
                    // entries when the underlying condition clears; Lattice
                    // does not filter stale entries automatically.
                    activeAlerts: [],
                    updateTime: latestTimestamp.toISOString()
                },
                // Declare the sensors carried by the asset. Each entry
                // requires a stable sensor_id, a sensor_type, and at least
                // one field of view so Lattice can render the sensor cone.
                sensors: {
                    sensors: [
                        {
                            sensorId: "eoir-1",
                            sensorType: "SENSOR_TYPE_CAMERA",
                            sensorDescription: "EO/IR gimbal",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: gimbalQuat
                                    },
                                    horizontalFov: 0.5,
                                    verticalFov: 0.3,
                                    range: 3000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        },
                        {
                            sensorId: "rf-1",
                            sensorType: "SENSOR_TYPE_RF",
                            sensorDescription: "RF direction finder",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                // Body-fixed, forward-facing mount.
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: bodyQuat
                                    },
                                    horizontalFov: 2 * Math.PI, // Omnidirectional.
                                    verticalFov: 1.0,
                                    range: 10000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        }
                    ]
                },
                taskCatalog: {
                    taskDefinitions: [
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId" },
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate" }
                    ]
                }
            }
        );
        console.log(`Publishing asset.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Wait for 1 second before the next iteration
        await new Promise(resolve => setTimeout(resolve, TICK_SECONDS * 1000));
    }
})();

```

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

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

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the SDK type.
    fn to_sdk(self) -> Quaternion {
        Quaternion {
            x: Some(self.x),
            y: Some(self.y),
            z: Some(self.z),
            w: Some(self.w),
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = std::f64::consts::FRAC_PI_2 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * std::f64::consts::PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: Some(self.lat),
            longitude_degrees: Some(self.lon),
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

#[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 id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * std::f64::consts::PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        let entity = Entity {
            entity_id: Some(id.clone()),
            description: Some("Friendly drone asset".to_string()),
            aliases: Some(Aliases {
                name: Some("Drone 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::hours(1)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("UAV".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentAir),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: Some(state.vel_east),
                    n: Some(state.vel_north),
                    u: Some(state.climb),
                    ..Default::default()
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_sdk()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("your_data_type".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                health_status: Some(HealthHealthStatus::HealthStatusHealthy),
                // Report the health of individual subsystems in components. Each
                // component needs a stable id, a display name, and a health
                // status.
                components: Some(vec![
                    ComponentHealth {
                        id: Some("battery-0".to_string()),
                        name: Some("Battery".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        messages: Some(vec![ComponentMessage {
                            status: Some(ComponentMessageStatus::HealthStatusHealthy),
                            message: Some(format!("Battery at {:.0}% charge.", battery_percent)),
                            ..Default::default()
                        }]),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("eoir-1".to_string()),
                        name: Some("EO/IR gimbal".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("rf-1".to_string()),
                        name: Some("RF direction finder".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                ]),
                // Live list of active alerts for the asset. Remove entries when
                // the underlying condition clears; Lattice does not filter stale
                // entries automatically.
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            // Declare the sensors carried by the asset. Each entry requires a
            // stable sensor_id, a sensor_type, and at least one field of view so
            // Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: Some(vec![
                    Sensor {
                        sensor_id: Some("eoir-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeCamera),
                        sensor_description: Some("EO/IR gimbal".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(0.5),
                            vertical_fov: Some(0.3),
                            range: Some(3000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: Some("rf-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeRf),
                        sensor_description: Some("RF direction finder".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        // Body-fixed, forward-facing mount.
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(2.0 * std::f64::consts::PI), // Omnidirectional.
                            vertical_fov: Some(1.0),
                            range: Some(10000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: Some(vec![
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.VisualId".to_string(),
                        ),
                        ..Default::default()
                    },
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                        ),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={61} maxLines={28}
// 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"
	"math"
	"os"
	"time"

	"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"
	"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"
	tasksv2 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/tasks/v2"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the protobuf type.
func toQuaternion(q quat) *_type.Quaternion {
	return &_type.Quaternion{X: q.x, Y: q.y, Z: q.z, W: q.w}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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 (using NewClient instead of Dial which is deprecated)
	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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTimestamp := timestamppb.Now()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *entitymanagerv1.Position {
			return &entitymanagerv1.Position{
				LatitudeDegrees:   state.lat,
				LongitudeDegrees:  state.lon,
				AltitudeHaeMeters: wrapperspb.Double(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Friendly drone asset",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Drone 1",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "UAV",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_AIR,
			},
			Location: &entitymanagerv1.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &_type.ENU{
					E: state.velEast,
					N: state.velNorth,
					U: state.climb,
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "your_data_type",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*entitymanagerv1.ComponentHealth{
					{
						Id:     "battery-0",
						Name:   "Battery",
						Health: entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						Messages: []*entitymanagerv1.ComponentMessage{
							{
								Status:  entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
								Message: fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent),
							},
						},
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "eoir-1",
						Name:       "EO/IR gimbal",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "rf-1",
						Name:       "RF direction finder",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*entitymanagerv1.Alert{},
				UpdateTime:   timestamppb.New(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &entitymanagerv1.Sensors{
				Sensors: []*entitymanagerv1.Sensor{
					{
						SensorId:          "eoir-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
						SensorDescription: "EO/IR gimbal",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: 0.5,
								VerticalFov:   0.3,
								Range:         wrapperspb.Float(3000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
					{
						SensorId:          "rf-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_RF,
						SensorDescription: "RF direction finder",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: 2 * math.Pi, // Omnidirectional.
								VerticalFov:   1.0,
								Range:         wrapperspb.Float(10000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
				},
			},
			TaskCatalog: &tasksv2.TaskCatalog{
				TaskDefinitions: []*tasksv2.TaskDefinition{
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId",
					},
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate",
					},
				},
			},
		}

		// 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 asset with entity ID: %s\n", entityId)
		}

		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={88} maxLines={36}
# 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 math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, 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.health_status_pub_pb import (
    ComponentHealth,
    ComponentMessage,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.tasks.v2.catalog_pub_pb import TaskCatalog, TaskDefinition
from anduril.type.coords_pub_pb import ENU, Quaternion


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


# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )


def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))


def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))


def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))


def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))


def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)


def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)


def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)


def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the protobuf type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])


def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))


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)

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

    entity_id = str(uuid.uuid4())

    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    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(hours=1))

        advance_state(state, TICK_SECONDS)

        # Heading equals course because the simulation has no wind.
        if AUTOPILOT_REPORTS_ATTITUDE:
            body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
        else:
            body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
        position = Position(
            latitude_degrees=state["lat"],
            longitude_degrees=state["lon"],
            altitude_hae_meters=DoubleValue(value=state["alt_hae"]),
        )
        # The gimbal sweeps relative to the nose. FieldOfView orientation is
        # absolute ENU, so compose it with the body attitude.
        gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
        gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
        battery_percent = max(87 - 0.01 * state["elapsed"], 0)

        entity = Entity(
            entity_id=entity_id,
            description="Friendly drone asset",
            aliases=Aliases(name="Drone 1"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="UAV"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.AIR,
            ),
            location=Location(
                position=position,
                # Velocity in the ENU frame, in meters per second.
                velocity_enu=ENU(e=state["vel_east"], n=state["vel_north"], u=state["climb"]),
                # Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu=to_quaternion(body_quat),
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="your_data_type",
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                health_status=HealthStatus.HEALTHY,
                # Report the health of individual subsystems in components.
                # Each component needs a stable id, a display name, and a
                # health status.
                components=[
                    ComponentHealth(
                        id="battery-0",
                        name="Battery",
                        health=HealthStatus.HEALTHY,
                        messages=[
                            ComponentMessage(
                                status=HealthStatus.HEALTHY,
                                message=f"Battery at {battery_percent:.0f}% charge.",
                            ),
                        ],
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="eoir-1",
                        name="EO/IR gimbal",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="rf-1",
                        name="RF direction finder",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                ],
                # Live list of active alerts for the asset. Remove entries
                # when the underlying condition clears; Lattice does not
                # filter stale entries automatically.
                active_alerts=[],
                update_time=latest_ts,
            ),
            # Declare the sensors carried by the asset. Each entry requires a
            # stable sensor_id, a sensor_type, and at least one field of view
            # so Lattice can render the sensor cone.
            sensors=Sensors(
                sensors=[
                    Sensor(
                        sensor_id="eoir-1",
                        sensor_type=SensorType.CAMERA,
                        sensor_description="EO/IR gimbal",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(gimbal_quat),
                                ),
                                horizontal_fov=0.5,
                                vertical_fov=0.3,
                                range=FloatValue(value=3000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                    Sensor(
                        sensor_id="rf-1",
                        sensor_type=SensorType.RF,
                        sensor_description="RF direction finder",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            # Body-fixed, forward-facing mount.
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(body_quat),
                                ),
                                horizontal_fov=2 * math.pi,  # Omnidirectional.
                                vertical_fov=1.0,
                                range=FloatValue(value=10000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                ],
            ),
            task_catalog=TaskCatalog(
                task_definitions=[
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId"),
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate"),
                ],
            ),
        )

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

        time.sleep(TICK_SECONDS)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={88} maxLines={30}
// 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::{
    Aliases, ComponentHealth, ComponentMessage, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position, Provenance,
    PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::{Enu, Quaternion};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::tasks::v2::{
    TaskCatalog, TaskDefinition,
};
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::f64::consts::PI;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the protobuf type.
    fn to_proto(self) -> Quaternion {
        Quaternion {
            x: self.x,
            y: self.y,
            z: self.z,
            w: self.w,
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = PI / 2.0 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: self.lat,
            longitude_degrees: self.lon,
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

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");

    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)
        },
    );

    // Generate a unique ID for the entity
    let entity_id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_timestamp = now_timestamp();

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

        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        // Create entity to publish
        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Friendly drone asset".to_string(),
            aliases: Some(Aliases {
                name: "Drone 1".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp),
            expiry_time: Some(add_seconds(&latest_timestamp, 3600)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "UAV".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Air as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: state.vel_east,
                    n: state.vel_north,
                    u: state.climb,
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_proto()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "your_data_type".to_string(),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                health_status: HealthStatus::Healthy as i32,
                // Report the health of individual subsystems in components.
                // Each component needs a stable id, a display name, and a
                // health status.
                components: vec![
                    ComponentHealth {
                        id: "battery-0".to_string(),
                        name: "Battery".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![ComponentMessage {
                            status: HealthStatus::Healthy as i32,
                            message: format!("Battery at {:.0}% charge.", battery_percent),
                        }],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "eoir-1".to_string(),
                        name: "EO/IR gimbal".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "rf-1".to_string(),
                        name: "RF direction finder".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                ],
                // Live list of active alerts for the asset. Remove entries
                // when the underlying condition clears; Lattice does not
                // filter stale entries automatically.
                active_alerts: vec![],
                update_time: Some(latest_timestamp),
            }),
            // Declare the sensors carried by the asset. Each entry requires
            // a stable sensor_id, a sensor_type, and at least one field of
            // view so Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: vec![
                    Sensor {
                        sensor_id: "eoir-1".to_string(),
                        sensor_type: SensorType::Camera as i32,
                        sensor_description: "EO/IR gimbal".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_proto()),
                            }),
                            horizontal_fov: 0.5,
                            vertical_fov: 0.3,
                            range: Some(3000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: "rf-1".to_string(),
                        sensor_type: SensorType::Rf as i32,
                        sensor_description: "RF direction finder".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        // Body-fixed, forward-facing mount.
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_proto()),
                            }),
                            horizontal_fov: (2.0 * PI) as f32, // Omnidirectional.
                            vertical_fov: 1.0,
                            range: Some(10000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: vec![
                    TaskDefinition {
                        task_specification_url: "type.googleapis.com/anduril.tasks.v2.VisualId"
                            .to_string(),
                    },
                    TaskDefinition {
                        task_specification_url:
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                    },
                ],
            }),
            ..Default::default()
        };

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

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

> **Info**
>
> Prefer the autopilot's own heading over a heading derived from velocity. A velocity-derived
> heading points along the vehicle's path, which differs from where the nose points in a
> crosswind, and is undefined while the vehicle hovers.

#### Point onboard sensors

Compute each sensor's field of view from the vehicle's attitude on every update:

* **Body-fixed sensors**: A sensor fixed to the airframe and facing forward, such as the RF direction finder, uses the vehicle's attitude as its orientation.
* **Gimbaled sensors**: A sensor on a gimbal combines the attitude with the gimbal's angles as `q_body ⊗ qz(−pan) ⊗ qy(−tilt)`, where pan is positive to the right of the nose and tilt is positive up.

The following code advances the simulated flight, then converts the vehicle state into velocity,
attitude, and sensor orientations:

```go title={"Go (REST)"} startLine={162} maxLines={50}
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the SDK type.
func toQuaternion(q quat) *Lattice.Quaternion {
	return &Lattice.Quaternion{
		X: Lattice.Float64(q.x),
		Y: Lattice.Float64(q.y),
		Z: Lattice.Float64(q.z),
		W: Lattice.Float64(q.w),
	}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTime := time.Now().UTC()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *Lattice.Position {
			return &Lattice.Position{
				LatitudeDegrees:   Lattice.Float64(state.lat),
				LongitudeDegrees:  Lattice.Float64(state.lon),
				AltitudeHaeMeters: Lattice.Float64(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Friendly drone asset"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Drone 1"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("UAV"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
			},
			Location: &Lattice.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &Lattice.Enu{
					E: Lattice.Float64(state.velEast),
					N: Lattice.Float64(state.velNorth),
					U: Lattice.Float64(state.climb),
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("your_data_type"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*Lattice.ComponentHealth{
					{
						ID:     Lattice.String("battery-0"),
						Name:   Lattice.String("Battery"),
						Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						Messages: []*Lattice.ComponentMessage{
							{
								Status:  Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
								Message: Lattice.String(fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent)),
							},
						},
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("eoir-1"),
						Name:       Lattice.String("EO/IR gimbal"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("rf-1"),
						Name:       Lattice.String("RF direction finder"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*Lattice.Alert{},
				UpdateTime:   Lattice.Time(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &Lattice.Sensors{
				Sensors: []*Lattice.Sensor{
					{
						SensorID:          Lattice.String("eoir-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
						SensorDescription: Lattice.String("EO/IR gimbal"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: Lattice.Float64(0.5),
								VerticalFov:   Lattice.Float64(0.3),
								Range:         Lattice.Float64(3000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
					{
						SensorID:          Lattice.String("rf-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeRf.Ptr(),
						SensorDescription: Lattice.String("RF direction finder"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: Lattice.Float64(2 * math.Pi), // Omnidirectional.
								VerticalFov:   Lattice.Float64(1.0),
								Range:         Lattice.Float64(10000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
				},
			},
			TaskCatalog: &Lattice.TaskCatalog{
				TaskDefinitions: []*Lattice.TaskDefinition{
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.VisualId")},
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.Investigate")},
				},
			},
		}

		// 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 asset")
		}

		// Wait before next request
		time.Sleep(1 * time.Second)
	}
}

```

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

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.Aliases;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.ComponentMessage;
import com.anduril.types.ComponentMessageStatus;
import com.anduril.types.Enu;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
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.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TaskCatalog;
import com.anduril.types.TaskDefinition;



public class PublishAssetDrone {
    // Flight model constants.
    private static final double TICK_SECONDS = 1.0;          // Time between updates, in seconds.
    private static final double GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
    private static final double TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
    private static final double BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
    private static final double ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
    private static final double ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
    private static final double GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
    private static final double GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
    private static final double GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
    private static final double GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
    private static final double METERS_PER_DEG = 111320.0;

    // Set to false to derive the attitude from velocity alone.
    private static final boolean AUTOPILOT_REPORTS_ATTITUDE = true;

    // Simulated state of the vehicle.
    private static class FlightState {
        double lat = 50.914;      // Degrees.
        double lon = 0.792;       // Degrees.
        double altHae = BASE_ALT_HAE;
        double courseDeg = 0.0;   // Direction of travel, degrees clockwise from north.
        double velEast, velNorth, climb; // Meters per second.
        double pitchDeg;          // Positive nose up.
        double rollDeg;           // Positive right wing down.
        double elapsed = 0.0;     // Seconds since start.
    }

    // Move the simulation forward by dt seconds.
    private static void advanceState(FlightState s, double dt) {
        s.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        s.courseDeg = (s.courseDeg + TURN_RATE_DEG_SEC * dt) % 360.0;
        double w = 2 * Math.PI / ALT_PERIOD;
        s.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * s.elapsed);
        s.climb = ALT_AMPLITUDE * w * Math.cos(w * s.elapsed);

        // Velocity from ground speed, course, and climb rate.
        double course = Math.toRadians(s.courseDeg);
        s.velEast = GROUND_SPEED * Math.sin(course);
        s.velNorth = GROUND_SPEED * Math.cos(course);

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        s.lat += s.velNorth * dt / METERS_PER_DEG;
        s.lon += s.velEast * dt / (METERS_PER_DEG * Math.cos(Math.toRadians(s.lat)));

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        s.pitchDeg = Math.toDegrees(Math.atan2(s.climb, GROUND_SPEED));
        s.rollDeg = Math.toDegrees(Math.atan(GROUND_SPEED * Math.toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
    }

    // Hamilton product a * b of two quaternions in {x, y, z, w} order.
    private static double[] multiply(double[] a, double[] b) {
        return new double[] {
            a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
            a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
            a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
            a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
        };
    }

    // Elementary rotations about the x, y, and z axes, in radians.
    private static double[] qx(double a) { return new double[] {Math.sin(a / 2), 0, 0, Math.cos(a / 2)}; }
    private static double[] qy(double a) { return new double[] {0, Math.sin(a / 2), 0, Math.cos(a / 2)}; }
    private static double[] qz(double a) { return new double[] {0, 0, Math.sin(a / 2), Math.cos(a / 2)}; }

    // Convert a compass heading (degrees clockwise from north), pitch
    // (positive nose up), and roll (positive right wing down) into the
    // attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
    // the ENU world frame.
    private static double[] attitudeToQuaternionEnu(double headingDeg, double pitchDeg, double rollDeg) {
        double yaw = Math.PI / 2 - Math.toRadians(headingDeg);
        return multiply(multiply(qz(yaw), qy(-Math.toRadians(pitchDeg))), qx(Math.toRadians(rollDeg)));
    }

    // Compose the body attitude with a gimbal pointing relative to the nose.
    // Pan is positive to the right and tilt is positive up. The result
    // rotates the sensor frame (+X is the boresight) into ENU.
    private static double[] gimbalToQuaternionEnu(double[] body, double panDeg, double tiltDeg) {
        double[] mount = multiply(qz(-Math.toRadians(panDeg)), qy(-Math.toRadians(tiltDeg)));
        return multiply(body, mount);
    }

    // Convert an ENU velocity vector into a yaw angle, in radians. Fallback
    // when your autopilot reports only velocity.
    private static double velocityToYawEnu(double velocityEast, double velocityNorth) {
        return Math.atan2(velocityNorth, velocityEast);
    }

    // Convert a yaw angle into an attitude_enu quaternion with zero pitch and
    // roll. Fallback when your autopilot reports only velocity.
    private static double[] yawToQuaternionEnu(double yawRad) {
        return qz(yawRad);
    }

    // Convert an {x, y, z, w} array into the SDK type.
    private static Quaternion toQuaternion(double[] q) {
        return Quaternion.builder().x(q[0]).y(q[1]).z(q[2]).w(q[3]).build();
    }

    private static Position position(FlightState s) {
        return Position.builder()
            .latitudeDegrees(s.lat)
            .longitudeDegrees(s.lon)
            .altitudeHaeMeters(s.altHae)
            .build();
    }

    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;
        
        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 entityId = UUID.randomUUID().toString();
            
            // Start near the origin, heading north.
            FlightState state = new FlightState();
            Instant creationTime = Instant.now();

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

                    advanceState(state, TICK_SECONDS);

                    // Heading equals course because the simulation has no wind.
                    double[] bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
                        ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
                        : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
                    // The gimbal sweeps relative to the nose. FieldOfView
                    // orientation is absolute ENU, so compose it with the
                    // body attitude.
                    double gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
                    double[] gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
                    double batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);
                    
                    // Create the entity
                    TaskDefinition visualId = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.VisualId")
                        .build();

                    TaskDefinition investigate = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.Investigate")
                        .build();

                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Friendly drone asset")
                        .aliases(Aliases.builder()
                            .name("Drone 1")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(1, ChronoUnit.HOURS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("UAV")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_AIR)
                            .build())
                        .location(Location.builder()
                            .position(position(state))
                            // Velocity in the ENU frame, in meters per second.
                            .velocityEnu(Enu.builder()
                                .e(state.velEast)
                                .n(state.velNorth)
                                .u(state.climb)
                                .build())
                            // Body-to-ENU attitude. Lattice uses it for heading.
                            .attitudeEnu(toQuaternion(bodyQuat))
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("your_data_type")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(HealthHealthStatus.HEALTH_STATUS_HEALTHY)
                            // Report the health of individual subsystems in
                            // components. Each component needs a stable id, a
                            // display name, and a health status.
                            .components(List.of(
                                ComponentHealth.builder()
                                    .id("battery-0")
                                    .name("Battery")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .messages(List.of(
                                        ComponentMessage.builder()
                                            .status(ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                                            .message(String.format("Battery at %.0f%% charge.", batteryPercent))
                                            .build()
                                    ))
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("eoir-1")
                                    .name("EO/IR gimbal")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("rf-1")
                                    .name("RF direction finder")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build()
                            ))
                            // Live list of active alerts for the asset. Remove
                            // entries when the underlying condition clears;
                            // Lattice does not filter stale entries
                            // automatically.
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        // Declare the sensors carried by the asset. Each
                        // entry requires a stable sensor_id, a sensor_type,
                        // and at least one field of view so Lattice can
                        // render the sensor cone.
                        .sensors(Sensors.builder()
                            .sensors(List.of(
                                Sensor.builder()
                                    .sensorId("eoir-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                    .sensorDescription("EO/IR gimbal")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(gimbalQuat))
                                                .build())
                                            .horizontalFov(0.5f)
                                            .verticalFov(0.3f)
                                            .range(3000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build(),
                                Sensor.builder()
                                    .sensorId("rf-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_RF)
                                    .sensorDescription("RF direction finder")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        // Body-fixed, forward-facing mount.
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(bodyQuat))
                                                .build())
                                            .horizontalFov((float) (2 * Math.PI)) // Omnidirectional.
                                            .verticalFov(1.0f)
                                            .range(10000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build()
                            ))
                            .build())
                        .taskCatalog(TaskCatalog.builder()
                            .taskDefinitions(Arrays.asList(visualId, investigate))
                            .build())
                        .build();
                    
                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset.");
                    
                    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={141} maxLines={48}
from anduril import Lattice, Aliases, MilView, Location, Position,\
      Ontology, Provenance, Health, ComponentHealth, ComponentMessage,\
      TaskCatalog, TaskDefinition,\
      Sensors, Sensor, FieldOfView, EntityManagerPose, Quaternion, Enu
from datetime import datetime, timezone, timedelta
import asyncio
import math
import os
import sys
from uuid import uuid4

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

# 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}" }
)
id = str(uuid4())

# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )

def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))

def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))

def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))

def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))

def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)

def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)

def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)

def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the SDK type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])

def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))

async def app():
    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    creation_time = datetime.now(timezone.utc)
    try:
        while True:
            latest_timestamp = datetime.now(timezone.utc)
            advance_state(state, TICK_SECONDS)

            # Heading equals course because the simulation has no wind.
            if AUTOPILOT_REPORTS_ATTITUDE:
                body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
            else:
                body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
            position = Position(
                latitude_degrees=state["lat"],
                longitude_degrees=state["lon"],
                altitude_hae_meters=state["alt_hae"]
            )
            # The gimbal sweeps relative to the nose. FieldOfView orientation
            # is absolute ENU, so compose it with the body attitude.
            gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
            gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
            battery_percent = max(87 - 0.01 * state["elapsed"], 0)

            try:
                client.entities.publish_entity(
                    entity_id=id,
                    description="Friendly drone asset",
                    aliases=Aliases(
                        name="Drone 1"
                    ),
                    is_live=True,
                    created_time=creation_time,
                    expiry_time=latest_timestamp + timedelta(hours=1),
                    ontology=Ontology(
                        template="TEMPLATE_ASSET",
                        platform_type="UAV"
                    ),
                    mil_view=MilView(
                        disposition="DISPOSITION_FRIENDLY",
                        environment="ENVIRONMENT_AIR"
                    ),
                    location=Location(
                        position=position,
                        # Velocity in the ENU frame, in meters per second.
                        velocity_enu=Enu(
                            e=state["vel_east"],
                            n=state["vel_north"],
                            u=state["climb"]
                        ),
                        # Body-to-ENU attitude. Lattice uses it for heading.
                        attitude_enu=to_quaternion(body_quat)
                    ),
                    provenance=Provenance(
                        integration_name="your_integration_name",
                        data_type="your_data_type",
                        source_update_time=latest_timestamp
                    ),
                    health=Health(
                        connection_status="CONNECTION_STATUS_ONLINE",
                        health_status="HEALTH_STATUS_HEALTHY",
                        # Report the health of individual subsystems in
                        # components. Each component needs a stable id, a
                        # display name, and a health status.
                        components=[
                            ComponentHealth(
                                id="battery-0",
                                name="Battery",
                                health="HEALTH_STATUS_HEALTHY",
                                messages=[
                                    ComponentMessage(
                                        status="HEALTH_STATUS_HEALTHY",
                                        message=f"Battery at {battery_percent:.0f}% charge.",
                                    ),
                                ],
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="eoir-1",
                                name="EO/IR gimbal",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="rf-1",
                                name="RF direction finder",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                        ],
                        # Live list of active alerts for the asset. Remove
                        # entries when the underlying condition clears;
                        # Lattice does not filter stale entries
                        # automatically.
                        active_alerts=[],
                        update_time=latest_timestamp
                    ),
                    # Declare the sensors carried by the asset. Each entry
                    # requires a stable sensor_id, a sensor_type, and at
                    # least one field of view so Lattice can render the
                    # sensor cone.
                    sensors=Sensors(
                        sensors=[
                            Sensor(
                                sensor_id="eoir-1",
                                sensor_type="SENSOR_TYPE_CAMERA",
                                sensor_description="EO/IR gimbal",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(gimbal_quat),
                                        ),
                                        horizontal_fov=0.5,
                                        vertical_fov=0.3,
                                        range=3000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                            Sensor(
                                sensor_id="rf-1",
                                sensor_type="SENSOR_TYPE_RF",
                                sensor_description="RF direction finder",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    # Body-fixed, forward-facing mount.
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(body_quat),
                                        ),
                                        horizontal_fov=2 * math.pi,  # Omnidirectional.
                                        vertical_fov=1.0,
                                        range=10000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                        ],
                    ),
                    task_catalog=TaskCatalog(
                        task_definitions=[
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId" ),
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate" )
                        ]
                    )
                )
                print("Publishing asset.")
            except Exception as error:
                print(f"Error publishing entity: {error}")
            await asyncio.sleep(TICK_SECONDS)

    except asyncio.CancelledError:
        print(">>> Exiting...")

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

```

```ts title={"TypeScript (REST)"} startLine={138} maxLines={45}
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}`  }
    }
);

const entityId = uuidv4()
const expiryOffsetHours = 1;
const createdTime = new Date();

// Flight model constants.
const TICK_SECONDS = 1.0;          // Time between updates, in seconds.
const GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
const BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
const ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE = true;

function toRadians(degrees: number): number {
    return degrees * (Math.PI / 180);
}

function toDegrees(radians: number): number {
    return radians * (180 / Math.PI);
}

type Quat = { x: number; y: number; z: number; w: number };

// Hamilton product a * b.
function multiply(a: Quat, b: Quat): Quat {
    return {
        x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
        y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
        z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
        w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
    };
}

// Elementary rotations about the x, y, and z axes, in radians.
const qx = (a: number): Quat => ({ x: Math.sin(a / 2), y: 0, z: 0, w: Math.cos(a / 2) });
const qy = (a: number): Quat => ({ x: 0, y: Math.sin(a / 2), z: 0, w: Math.cos(a / 2) });
const qz = (a: number): Quat => ({ x: 0, y: 0, z: Math.sin(a / 2), w: Math.cos(a / 2) });

// Convert a compass heading (degrees clockwise from north), pitch (positive
// nose up), and roll (positive right wing down) into the attitude_enu
// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
// frame.
function attitudeToQuaternionEnu(headingDeg: number, pitchDeg: number, rollDeg: number): Quat {
    const yaw = Math.PI / 2 - toRadians(headingDeg);
    return multiply(multiply(qz(yaw), qy(-toRadians(pitchDeg))), qx(toRadians(rollDeg)));
}

// Compose the body attitude with a gimbal pointing relative to the nose. Pan
// is positive to the right and tilt is positive up. The result rotates the
// sensor frame (+X is the boresight) into ENU.
function gimbalToQuaternionEnu(body: Quat, panDeg: number, tiltDeg: number): Quat {
    const mount = multiply(qz(-toRadians(panDeg)), qy(-toRadians(tiltDeg)));
    return multiply(body, mount);
}

// Convert an ENU velocity vector into a yaw angle, in radians. Fallback when
// your autopilot reports only velocity.
function velocityToYawEnu(velocityEast: number, velocityNorth: number): number {
    return Math.atan2(velocityNorth, velocityEast);
}

// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
// roll. Fallback when your autopilot reports only velocity.
function yawToQuaternionEnu(yawRad: number): Quat {
    return qz(yawRad);
}

// Simulated state of the vehicle. Starts near the origin, heading north.
const state = {
    lat: 50.914,        // Degrees.
    lon: 0.792,         // Degrees.
    altHae: BASE_ALT_HAE,
    courseDeg: 0,       // Direction of travel, degrees clockwise from north.
    velEast: 0,         // Meters per second.
    velNorth: 0,
    climb: 0,
    pitchDeg: 0,        // Positive nose up.
    rollDeg: 0,         // Positive right wing down.
    elapsed: 0,         // Seconds since start.
};

// Move the simulation forward by dt seconds.
function advanceState(dt: number) {
    state.elapsed += dt;

    // Turn at a constant rate and oscillate the altitude.
    state.courseDeg = (state.courseDeg + TURN_RATE_DEG_SEC * dt) % 360;
    const w = 2 * Math.PI / ALT_PERIOD;
    state.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * state.elapsed);
    state.climb = ALT_AMPLITUDE * w * Math.cos(w * state.elapsed);

    // Velocity from ground speed, course, and climb rate.
    const course = toRadians(state.courseDeg);
    state.velEast = GROUND_SPEED * Math.sin(course);
    state.velNorth = GROUND_SPEED * Math.cos(course);

    // Integrate position: meters to degrees, scaling longitude by cos(lat).
    state.lat += state.velNorth * dt / METERS_PER_DEG;
    state.lon += state.velEast * dt / (METERS_PER_DEG * Math.cos(toRadians(state.lat)));

    // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    state.pitchDeg = toDegrees(Math.atan2(state.climb, GROUND_SPEED));
    state.rollDeg = toDegrees(Math.atan(GROUND_SPEED * toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
}

async function App() {
    try {
        const latestTimestamp = new Date();
        advanceState(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        const bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
            ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
            : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
        const position = {
            latitudeDegrees: state.lat,
            longitudeDegrees: state.lon,
            altitudeHaeMeters: state.altHae,
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        const gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
        const gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
        const batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);

        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Friendly drone asset",
                aliases: { name: "Drone 1" },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + expiryOffsetHours * 3600000).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "UAV"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_AIR",
                },
                location: {
                    position: position,
                    // Velocity in the ENU frame, in meters per second.
                    velocityEnu: { e: state.velEast, n: state.velNorth, u: state.climb },
                    // Body-to-ENU attitude. Lattice uses it for heading.
                    attitudeEnu: bodyQuat
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "your_data_type",
                    sourceUpdateTime: latestTimestamp.toISOString()
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    healthStatus: "HEALTH_STATUS_HEALTHY",
                    // Report the health of individual subsystems in
                    // components. Each component needs a stable id, a display
                    // name, and a health status.
                    components: [
                        {
                            id: "battery-0",
                            name: "Battery",
                            health: "HEALTH_STATUS_HEALTHY",
                            messages: [
                                {
                                    status: "HEALTH_STATUS_HEALTHY",
                                    message: `Battery at ${batteryPercent.toFixed(0)}% charge.`
                                }
                            ],
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "eoir-1",
                            name: "EO/IR gimbal",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "rf-1",
                            name: "RF direction finder",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        }
                    ],
                    // Live list of active alerts for the asset. Remove
                    // entries when the underlying condition clears; Lattice
                    // does not filter stale entries automatically.
                    activeAlerts: [],
                    updateTime: latestTimestamp.toISOString()
                },
                // Declare the sensors carried by the asset. Each entry
                // requires a stable sensor_id, a sensor_type, and at least
                // one field of view so Lattice can render the sensor cone.
                sensors: {
                    sensors: [
                        {
                            sensorId: "eoir-1",
                            sensorType: "SENSOR_TYPE_CAMERA",
                            sensorDescription: "EO/IR gimbal",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: gimbalQuat
                                    },
                                    horizontalFov: 0.5,
                                    verticalFov: 0.3,
                                    range: 3000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        },
                        {
                            sensorId: "rf-1",
                            sensorType: "SENSOR_TYPE_RF",
                            sensorDescription: "RF direction finder",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                // Body-fixed, forward-facing mount.
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: bodyQuat
                                    },
                                    horizontalFov: 2 * Math.PI, // Omnidirectional.
                                    verticalFov: 1.0,
                                    range: 10000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        }
                    ]
                },
                taskCatalog: {
                    taskDefinitions: [
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId" },
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate" }
                    ]
                }
            }
        );
        console.log(`Publishing asset.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Wait for 1 second before the next iteration
        await new Promise(resolve => setTimeout(resolve, TICK_SECONDS * 1000));
    }
})();

```

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

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

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the SDK type.
    fn to_sdk(self) -> Quaternion {
        Quaternion {
            x: Some(self.x),
            y: Some(self.y),
            z: Some(self.z),
            w: Some(self.w),
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = std::f64::consts::FRAC_PI_2 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * std::f64::consts::PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: Some(self.lat),
            longitude_degrees: Some(self.lon),
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

#[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 id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * std::f64::consts::PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        let entity = Entity {
            entity_id: Some(id.clone()),
            description: Some("Friendly drone asset".to_string()),
            aliases: Some(Aliases {
                name: Some("Drone 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::hours(1)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("UAV".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentAir),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: Some(state.vel_east),
                    n: Some(state.vel_north),
                    u: Some(state.climb),
                    ..Default::default()
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_sdk()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("your_data_type".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                health_status: Some(HealthHealthStatus::HealthStatusHealthy),
                // Report the health of individual subsystems in components. Each
                // component needs a stable id, a display name, and a health
                // status.
                components: Some(vec![
                    ComponentHealth {
                        id: Some("battery-0".to_string()),
                        name: Some("Battery".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        messages: Some(vec![ComponentMessage {
                            status: Some(ComponentMessageStatus::HealthStatusHealthy),
                            message: Some(format!("Battery at {:.0}% charge.", battery_percent)),
                            ..Default::default()
                        }]),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("eoir-1".to_string()),
                        name: Some("EO/IR gimbal".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("rf-1".to_string()),
                        name: Some("RF direction finder".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                ]),
                // Live list of active alerts for the asset. Remove entries when
                // the underlying condition clears; Lattice does not filter stale
                // entries automatically.
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            // Declare the sensors carried by the asset. Each entry requires a
            // stable sensor_id, a sensor_type, and at least one field of view so
            // Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: Some(vec![
                    Sensor {
                        sensor_id: Some("eoir-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeCamera),
                        sensor_description: Some("EO/IR gimbal".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(0.5),
                            vertical_fov: Some(0.3),
                            range: Some(3000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: Some("rf-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeRf),
                        sensor_description: Some("RF direction finder".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        // Body-fixed, forward-facing mount.
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(2.0 * std::f64::consts::PI), // Omnidirectional.
                            vertical_fov: Some(1.0),
                            range: Some(10000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: Some(vec![
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.VisualId".to_string(),
                        ),
                        ..Default::default()
                    },
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                        ),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={175} maxLines={50}
// 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"
	"math"
	"os"
	"time"

	"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"
	"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"
	tasksv2 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/tasks/v2"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the protobuf type.
func toQuaternion(q quat) *_type.Quaternion {
	return &_type.Quaternion{X: q.x, Y: q.y, Z: q.z, W: q.w}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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 (using NewClient instead of Dial which is deprecated)
	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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTimestamp := timestamppb.Now()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *entitymanagerv1.Position {
			return &entitymanagerv1.Position{
				LatitudeDegrees:   state.lat,
				LongitudeDegrees:  state.lon,
				AltitudeHaeMeters: wrapperspb.Double(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Friendly drone asset",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Drone 1",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "UAV",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_AIR,
			},
			Location: &entitymanagerv1.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &_type.ENU{
					E: state.velEast,
					N: state.velNorth,
					U: state.climb,
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "your_data_type",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*entitymanagerv1.ComponentHealth{
					{
						Id:     "battery-0",
						Name:   "Battery",
						Health: entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						Messages: []*entitymanagerv1.ComponentMessage{
							{
								Status:  entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
								Message: fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent),
							},
						},
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "eoir-1",
						Name:       "EO/IR gimbal",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "rf-1",
						Name:       "RF direction finder",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*entitymanagerv1.Alert{},
				UpdateTime:   timestamppb.New(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &entitymanagerv1.Sensors{
				Sensors: []*entitymanagerv1.Sensor{
					{
						SensorId:          "eoir-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
						SensorDescription: "EO/IR gimbal",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: 0.5,
								VerticalFov:   0.3,
								Range:         wrapperspb.Float(3000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
					{
						SensorId:          "rf-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_RF,
						SensorDescription: "RF direction finder",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: 2 * math.Pi, // Omnidirectional.
								VerticalFov:   1.0,
								Range:         wrapperspb.Float(10000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
				},
			},
			TaskCatalog: &tasksv2.TaskCatalog{
				TaskDefinitions: []*tasksv2.TaskDefinition{
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId",
					},
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate",
					},
				},
			},
		}

		// 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 asset with entity ID: %s\n", entityId)
		}

		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={182} maxLines={42}
# 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 math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, 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.health_status_pub_pb import (
    ComponentHealth,
    ComponentMessage,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.tasks.v2.catalog_pub_pb import TaskCatalog, TaskDefinition
from anduril.type.coords_pub_pb import ENU, Quaternion


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


# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )


def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))


def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))


def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))


def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))


def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)


def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)


def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)


def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the protobuf type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])


def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))


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)

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

    entity_id = str(uuid.uuid4())

    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    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(hours=1))

        advance_state(state, TICK_SECONDS)

        # Heading equals course because the simulation has no wind.
        if AUTOPILOT_REPORTS_ATTITUDE:
            body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
        else:
            body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
        position = Position(
            latitude_degrees=state["lat"],
            longitude_degrees=state["lon"],
            altitude_hae_meters=DoubleValue(value=state["alt_hae"]),
        )
        # The gimbal sweeps relative to the nose. FieldOfView orientation is
        # absolute ENU, so compose it with the body attitude.
        gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
        gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
        battery_percent = max(87 - 0.01 * state["elapsed"], 0)

        entity = Entity(
            entity_id=entity_id,
            description="Friendly drone asset",
            aliases=Aliases(name="Drone 1"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="UAV"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.AIR,
            ),
            location=Location(
                position=position,
                # Velocity in the ENU frame, in meters per second.
                velocity_enu=ENU(e=state["vel_east"], n=state["vel_north"], u=state["climb"]),
                # Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu=to_quaternion(body_quat),
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="your_data_type",
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                health_status=HealthStatus.HEALTHY,
                # Report the health of individual subsystems in components.
                # Each component needs a stable id, a display name, and a
                # health status.
                components=[
                    ComponentHealth(
                        id="battery-0",
                        name="Battery",
                        health=HealthStatus.HEALTHY,
                        messages=[
                            ComponentMessage(
                                status=HealthStatus.HEALTHY,
                                message=f"Battery at {battery_percent:.0f}% charge.",
                            ),
                        ],
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="eoir-1",
                        name="EO/IR gimbal",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="rf-1",
                        name="RF direction finder",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                ],
                # Live list of active alerts for the asset. Remove entries
                # when the underlying condition clears; Lattice does not
                # filter stale entries automatically.
                active_alerts=[],
                update_time=latest_ts,
            ),
            # Declare the sensors carried by the asset. Each entry requires a
            # stable sensor_id, a sensor_type, and at least one field of view
            # so Lattice can render the sensor cone.
            sensors=Sensors(
                sensors=[
                    Sensor(
                        sensor_id="eoir-1",
                        sensor_type=SensorType.CAMERA,
                        sensor_description="EO/IR gimbal",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(gimbal_quat),
                                ),
                                horizontal_fov=0.5,
                                vertical_fov=0.3,
                                range=FloatValue(value=3000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                    Sensor(
                        sensor_id="rf-1",
                        sensor_type=SensorType.RF,
                        sensor_description="RF direction finder",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            # Body-fixed, forward-facing mount.
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(body_quat),
                                ),
                                horizontal_fov=2 * math.pi,  # Omnidirectional.
                                vertical_fov=1.0,
                                range=FloatValue(value=10000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                ],
            ),
            task_catalog=TaskCatalog(
                task_definitions=[
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId"),
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate"),
                ],
            ),
        )

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

        time.sleep(TICK_SECONDS)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={243} maxLines={47}
// 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::{
    Aliases, ComponentHealth, ComponentMessage, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position, Provenance,
    PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::{Enu, Quaternion};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::tasks::v2::{
    TaskCatalog, TaskDefinition,
};
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::f64::consts::PI;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the protobuf type.
    fn to_proto(self) -> Quaternion {
        Quaternion {
            x: self.x,
            y: self.y,
            z: self.z,
            w: self.w,
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = PI / 2.0 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: self.lat,
            longitude_degrees: self.lon,
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

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");

    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)
        },
    );

    // Generate a unique ID for the entity
    let entity_id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_timestamp = now_timestamp();

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

        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        // Create entity to publish
        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Friendly drone asset".to_string(),
            aliases: Some(Aliases {
                name: "Drone 1".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp),
            expiry_time: Some(add_seconds(&latest_timestamp, 3600)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "UAV".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Air as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: state.vel_east,
                    n: state.vel_north,
                    u: state.climb,
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_proto()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "your_data_type".to_string(),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                health_status: HealthStatus::Healthy as i32,
                // Report the health of individual subsystems in components.
                // Each component needs a stable id, a display name, and a
                // health status.
                components: vec![
                    ComponentHealth {
                        id: "battery-0".to_string(),
                        name: "Battery".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![ComponentMessage {
                            status: HealthStatus::Healthy as i32,
                            message: format!("Battery at {:.0}% charge.", battery_percent),
                        }],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "eoir-1".to_string(),
                        name: "EO/IR gimbal".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "rf-1".to_string(),
                        name: "RF direction finder".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                ],
                // Live list of active alerts for the asset. Remove entries
                // when the underlying condition clears; Lattice does not
                // filter stale entries automatically.
                active_alerts: vec![],
                update_time: Some(latest_timestamp),
            }),
            // Declare the sensors carried by the asset. Each entry requires
            // a stable sensor_id, a sensor_type, and at least one field of
            // view so Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: vec![
                    Sensor {
                        sensor_id: "eoir-1".to_string(),
                        sensor_type: SensorType::Camera as i32,
                        sensor_description: "EO/IR gimbal".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_proto()),
                            }),
                            horizontal_fov: 0.5,
                            vertical_fov: 0.3,
                            range: Some(3000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: "rf-1".to_string(),
                        sensor_type: SensorType::Rf as i32,
                        sensor_description: "RF direction finder".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        // Body-fixed, forward-facing mount.
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_proto()),
                            }),
                            horizontal_fov: (2.0 * PI) as f32, // Omnidirectional.
                            vertical_fov: 1.0,
                            range: Some(10000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: vec![
                    TaskDefinition {
                        task_specification_url: "type.googleapis.com/anduril.tasks.v2.VisualId"
                            .to_string(),
                    },
                    TaskDefinition {
                        task_specification_url:
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                    },
                ],
            }),
            ..Default::default()
        };

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

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

#### Publish the entity

Declare both sensors with their fields of view, and publish the entity with the
[`PublishEntity`](/reference/rest/entities/publish-entity) API method. Publish at the rate your
autopilot reports, such as once per second, so the vehicle and its sensor coverage move smoothly
on the map:

```go title={"Go (REST)"} startLine={257} maxLines={61}
package main

import (
	"context"
	"fmt"
	"math"
	"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"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the SDK type.
func toQuaternion(q quat) *Lattice.Quaternion {
	return &Lattice.Quaternion{
		X: Lattice.Float64(q.x),
		Y: Lattice.Float64(q.y),
		Z: Lattice.Float64(q.z),
		W: Lattice.Float64(q.w),
	}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTime := time.Now().UTC()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *Lattice.Position {
			return &Lattice.Position{
				LatitudeDegrees:   Lattice.Float64(state.lat),
				LongitudeDegrees:  Lattice.Float64(state.lon),
				AltitudeHaeMeters: Lattice.Float64(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Friendly drone asset"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Drone 1"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			ExpiryTime:  Lattice.Time(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &Lattice.Ontology{
				Template:     Lattice.OntologyTemplateTemplateAsset.Ptr(),
				PlatformType: Lattice.String("UAV"),
			},
			MilView: &Lattice.MilView{
				Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
				Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
			},
			Location: &Lattice.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &Lattice.Enu{
					E: Lattice.Float64(state.velEast),
					N: Lattice.Float64(state.velNorth),
					U: Lattice.Float64(state.climb),
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("your_data_type"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
			Health: &Lattice.Health{
				ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
				HealthStatus:     Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*Lattice.ComponentHealth{
					{
						ID:     Lattice.String("battery-0"),
						Name:   Lattice.String("Battery"),
						Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						Messages: []*Lattice.ComponentMessage{
							{
								Status:  Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
								Message: Lattice.String(fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent)),
							},
						},
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("eoir-1"),
						Name:       Lattice.String("EO/IR gimbal"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
					{
						ID:         Lattice.String("rf-1"),
						Name:       Lattice.String("RF direction finder"),
						Health:     Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
						UpdateTime: Lattice.Time(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*Lattice.Alert{},
				UpdateTime:   Lattice.Time(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &Lattice.Sensors{
				Sensors: []*Lattice.Sensor{
					{
						SensorID:          Lattice.String("eoir-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
						SensorDescription: Lattice.String("EO/IR gimbal"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: Lattice.Float64(0.5),
								VerticalFov:   Lattice.Float64(0.3),
								Range:         Lattice.Float64(3000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
					{
						SensorID:          Lattice.String("rf-1"),
						SensorType:        Lattice.SensorSensorTypeSensorTypeRf.Ptr(),
						SensorDescription: Lattice.String("RF direction finder"),
						OperationalState:  Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
						FieldsOfView: []*Lattice.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &Lattice.EntityManagerPose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: Lattice.Float64(2 * math.Pi), // Omnidirectional.
								VerticalFov:   Lattice.Float64(1.0),
								Range:         Lattice.Float64(10000.0),
								Mode:          Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
							},
						},
					},
				},
			},
			TaskCatalog: &Lattice.TaskCatalog{
				TaskDefinitions: []*Lattice.TaskDefinition{
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.VisualId")},
					{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.Investigate")},
				},
			},
		}

		// 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 asset")
		}

		// Wait before next request
		time.Sleep(1 * time.Second)
	}
}

```

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

import com.anduril.Lattice;
import com.anduril.types.Alert;
import com.anduril.types.Aliases;
import com.anduril.types.ComponentHealth;
import com.anduril.types.ComponentHealthHealth;
import com.anduril.types.ComponentMessage;
import com.anduril.types.ComponentMessageStatus;
import com.anduril.types.Enu;
import com.anduril.types.Entity;
import com.anduril.types.EntityManagerPose;
import com.anduril.types.FieldOfView;
import com.anduril.types.FieldOfViewMode;
import com.anduril.types.Health;
import com.anduril.types.HealthConnectionStatus;
import com.anduril.types.HealthHealthStatus;
import com.anduril.types.Location;
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.Quaternion;
import com.anduril.types.Sensor;
import com.anduril.types.SensorOperationalState;
import com.anduril.types.SensorSensorType;
import com.anduril.types.Sensors;
import com.anduril.types.TaskCatalog;
import com.anduril.types.TaskDefinition;



public class PublishAssetDrone {
    // Flight model constants.
    private static final double TICK_SECONDS = 1.0;          // Time between updates, in seconds.
    private static final double GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
    private static final double TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
    private static final double BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
    private static final double ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
    private static final double ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
    private static final double GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
    private static final double GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
    private static final double GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
    private static final double GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
    private static final double METERS_PER_DEG = 111320.0;

    // Set to false to derive the attitude from velocity alone.
    private static final boolean AUTOPILOT_REPORTS_ATTITUDE = true;

    // Simulated state of the vehicle.
    private static class FlightState {
        double lat = 50.914;      // Degrees.
        double lon = 0.792;       // Degrees.
        double altHae = BASE_ALT_HAE;
        double courseDeg = 0.0;   // Direction of travel, degrees clockwise from north.
        double velEast, velNorth, climb; // Meters per second.
        double pitchDeg;          // Positive nose up.
        double rollDeg;           // Positive right wing down.
        double elapsed = 0.0;     // Seconds since start.
    }

    // Move the simulation forward by dt seconds.
    private static void advanceState(FlightState s, double dt) {
        s.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        s.courseDeg = (s.courseDeg + TURN_RATE_DEG_SEC * dt) % 360.0;
        double w = 2 * Math.PI / ALT_PERIOD;
        s.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * s.elapsed);
        s.climb = ALT_AMPLITUDE * w * Math.cos(w * s.elapsed);

        // Velocity from ground speed, course, and climb rate.
        double course = Math.toRadians(s.courseDeg);
        s.velEast = GROUND_SPEED * Math.sin(course);
        s.velNorth = GROUND_SPEED * Math.cos(course);

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        s.lat += s.velNorth * dt / METERS_PER_DEG;
        s.lon += s.velEast * dt / (METERS_PER_DEG * Math.cos(Math.toRadians(s.lat)));

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        s.pitchDeg = Math.toDegrees(Math.atan2(s.climb, GROUND_SPEED));
        s.rollDeg = Math.toDegrees(Math.atan(GROUND_SPEED * Math.toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
    }

    // Hamilton product a * b of two quaternions in {x, y, z, w} order.
    private static double[] multiply(double[] a, double[] b) {
        return new double[] {
            a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
            a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
            a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
            a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
        };
    }

    // Elementary rotations about the x, y, and z axes, in radians.
    private static double[] qx(double a) { return new double[] {Math.sin(a / 2), 0, 0, Math.cos(a / 2)}; }
    private static double[] qy(double a) { return new double[] {0, Math.sin(a / 2), 0, Math.cos(a / 2)}; }
    private static double[] qz(double a) { return new double[] {0, 0, Math.sin(a / 2), Math.cos(a / 2)}; }

    // Convert a compass heading (degrees clockwise from north), pitch
    // (positive nose up), and roll (positive right wing down) into the
    // attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
    // the ENU world frame.
    private static double[] attitudeToQuaternionEnu(double headingDeg, double pitchDeg, double rollDeg) {
        double yaw = Math.PI / 2 - Math.toRadians(headingDeg);
        return multiply(multiply(qz(yaw), qy(-Math.toRadians(pitchDeg))), qx(Math.toRadians(rollDeg)));
    }

    // Compose the body attitude with a gimbal pointing relative to the nose.
    // Pan is positive to the right and tilt is positive up. The result
    // rotates the sensor frame (+X is the boresight) into ENU.
    private static double[] gimbalToQuaternionEnu(double[] body, double panDeg, double tiltDeg) {
        double[] mount = multiply(qz(-Math.toRadians(panDeg)), qy(-Math.toRadians(tiltDeg)));
        return multiply(body, mount);
    }

    // Convert an ENU velocity vector into a yaw angle, in radians. Fallback
    // when your autopilot reports only velocity.
    private static double velocityToYawEnu(double velocityEast, double velocityNorth) {
        return Math.atan2(velocityNorth, velocityEast);
    }

    // Convert a yaw angle into an attitude_enu quaternion with zero pitch and
    // roll. Fallback when your autopilot reports only velocity.
    private static double[] yawToQuaternionEnu(double yawRad) {
        return qz(yawRad);
    }

    // Convert an {x, y, z, w} array into the SDK type.
    private static Quaternion toQuaternion(double[] q) {
        return Quaternion.builder().x(q[0]).y(q[1]).z(q[2]).w(q[3]).build();
    }

    private static Position position(FlightState s) {
        return Position.builder()
            .latitudeDegrees(s.lat)
            .longitudeDegrees(s.lon)
            .altitudeHaeMeters(s.altHae)
            .build();
    }

    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;
        
        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 entityId = UUID.randomUUID().toString();
            
            // Start near the origin, heading north.
            FlightState state = new FlightState();
            Instant creationTime = Instant.now();

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

                    advanceState(state, TICK_SECONDS);

                    // Heading equals course because the simulation has no wind.
                    double[] bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
                        ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
                        : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
                    // The gimbal sweeps relative to the nose. FieldOfView
                    // orientation is absolute ENU, so compose it with the
                    // body attitude.
                    double gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
                    double[] gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
                    double batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);
                    
                    // Create the entity
                    TaskDefinition visualId = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.VisualId")
                        .build();

                    TaskDefinition investigate = TaskDefinition.builder()
                        .taskSpecificationUrl("type.googleapis.com/anduril.tasks.v2.Investigate")
                        .build();

                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Friendly drone asset")
                        .aliases(Aliases.builder()
                            .name("Drone 1")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .expiryTime(OffsetDateTime.ofInstant(latestTimestamp.plus(1, ChronoUnit.HOURS), ZoneOffset.UTC))
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_ASSET)
                            .platformType("UAV")
                            .build())
                        .milView(MilView.builder()
                            .disposition(MilViewDisposition.DISPOSITION_FRIENDLY)
                            .environment(MilViewEnvironment.ENVIRONMENT_AIR)
                            .build())
                        .location(Location.builder()
                            .position(position(state))
                            // Velocity in the ENU frame, in meters per second.
                            .velocityEnu(Enu.builder()
                                .e(state.velEast)
                                .n(state.velNorth)
                                .u(state.climb)
                                .build())
                            // Body-to-ENU attitude. Lattice uses it for heading.
                            .attitudeEnu(toQuaternion(bodyQuat))
                            .build())
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("your_data_type")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .health(Health.builder()
                            .connectionStatus(HealthConnectionStatus.CONNECTION_STATUS_ONLINE)
                            .healthStatus(HealthHealthStatus.HEALTH_STATUS_HEALTHY)
                            // Report the health of individual subsystems in
                            // components. Each component needs a stable id, a
                            // display name, and a health status.
                            .components(List.of(
                                ComponentHealth.builder()
                                    .id("battery-0")
                                    .name("Battery")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .messages(List.of(
                                        ComponentMessage.builder()
                                            .status(ComponentMessageStatus.HEALTH_STATUS_HEALTHY)
                                            .message(String.format("Battery at %.0f%% charge.", batteryPercent))
                                            .build()
                                    ))
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("eoir-1")
                                    .name("EO/IR gimbal")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build(),
                                ComponentHealth.builder()
                                    .id("rf-1")
                                    .name("RF direction finder")
                                    .health(ComponentHealthHealth.HEALTH_STATUS_HEALTHY)
                                    .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                                    .build()
                            ))
                            // Live list of active alerts for the asset. Remove
                            // entries when the underlying condition clears;
                            // Lattice does not filter stale entries
                            // automatically.
                            .activeAlerts(Collections.<Alert>emptyList())
                            .updateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        // Declare the sensors carried by the asset. Each
                        // entry requires a stable sensor_id, a sensor_type,
                        // and at least one field of view so Lattice can
                        // render the sensor cone.
                        .sensors(Sensors.builder()
                            .sensors(List.of(
                                Sensor.builder()
                                    .sensorId("eoir-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_CAMERA)
                                    .sensorDescription("EO/IR gimbal")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(gimbalQuat))
                                                .build())
                                            .horizontalFov(0.5f)
                                            .verticalFov(0.3f)
                                            .range(3000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build(),
                                Sensor.builder()
                                    .sensorId("rf-1")
                                    .sensorType(SensorSensorType.SENSOR_TYPE_RF)
                                    .sensorDescription("RF direction finder")
                                    .operationalState(SensorOperationalState.OPERATIONAL_STATE_OPERATIONAL)
                                    .fieldsOfView(List.of(
                                        // Body-fixed, forward-facing mount.
                                        FieldOfView.builder()
                                            .centerRayPose(EntityManagerPose.builder()
                                                .pos(position(state))
                                                .orientation(toQuaternion(bodyQuat))
                                                .build())
                                            .horizontalFov((float) (2 * Math.PI)) // Omnidirectional.
                                            .verticalFov(1.0f)
                                            .range(10000.0f)
                                            .mode(FieldOfViewMode.SENSOR_MODE_SEARCH)
                                            .build()
                                    ))
                                    .build()
                            ))
                            .build())
                        .taskCatalog(TaskCatalog.builder()
                            .taskDefinitions(Arrays.asList(visualId, investigate))
                            .build())
                        .build();
                    
                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Publishing asset.");
                    
                    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={236} maxLines={52}
from anduril import Lattice, Aliases, MilView, Location, Position,\
      Ontology, Provenance, Health, ComponentHealth, ComponentMessage,\
      TaskCatalog, TaskDefinition,\
      Sensors, Sensor, FieldOfView, EntityManagerPose, Quaternion, Enu
from datetime import datetime, timezone, timedelta
import asyncio
import math
import os
import sys
from uuid import uuid4

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

# 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}" }
)
id = str(uuid4())

# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )

def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))

def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))

def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))

def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))

def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)

def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)

def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)

def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the SDK type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])

def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))

async def app():
    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    creation_time = datetime.now(timezone.utc)
    try:
        while True:
            latest_timestamp = datetime.now(timezone.utc)
            advance_state(state, TICK_SECONDS)

            # Heading equals course because the simulation has no wind.
            if AUTOPILOT_REPORTS_ATTITUDE:
                body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
            else:
                body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
            position = Position(
                latitude_degrees=state["lat"],
                longitude_degrees=state["lon"],
                altitude_hae_meters=state["alt_hae"]
            )
            # The gimbal sweeps relative to the nose. FieldOfView orientation
            # is absolute ENU, so compose it with the body attitude.
            gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
            gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
            battery_percent = max(87 - 0.01 * state["elapsed"], 0)

            try:
                client.entities.publish_entity(
                    entity_id=id,
                    description="Friendly drone asset",
                    aliases=Aliases(
                        name="Drone 1"
                    ),
                    is_live=True,
                    created_time=creation_time,
                    expiry_time=latest_timestamp + timedelta(hours=1),
                    ontology=Ontology(
                        template="TEMPLATE_ASSET",
                        platform_type="UAV"
                    ),
                    mil_view=MilView(
                        disposition="DISPOSITION_FRIENDLY",
                        environment="ENVIRONMENT_AIR"
                    ),
                    location=Location(
                        position=position,
                        # Velocity in the ENU frame, in meters per second.
                        velocity_enu=Enu(
                            e=state["vel_east"],
                            n=state["vel_north"],
                            u=state["climb"]
                        ),
                        # Body-to-ENU attitude. Lattice uses it for heading.
                        attitude_enu=to_quaternion(body_quat)
                    ),
                    provenance=Provenance(
                        integration_name="your_integration_name",
                        data_type="your_data_type",
                        source_update_time=latest_timestamp
                    ),
                    health=Health(
                        connection_status="CONNECTION_STATUS_ONLINE",
                        health_status="HEALTH_STATUS_HEALTHY",
                        # Report the health of individual subsystems in
                        # components. Each component needs a stable id, a
                        # display name, and a health status.
                        components=[
                            ComponentHealth(
                                id="battery-0",
                                name="Battery",
                                health="HEALTH_STATUS_HEALTHY",
                                messages=[
                                    ComponentMessage(
                                        status="HEALTH_STATUS_HEALTHY",
                                        message=f"Battery at {battery_percent:.0f}% charge.",
                                    ),
                                ],
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="eoir-1",
                                name="EO/IR gimbal",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                            ComponentHealth(
                                id="rf-1",
                                name="RF direction finder",
                                health="HEALTH_STATUS_HEALTHY",
                                update_time=latest_timestamp,
                            ),
                        ],
                        # Live list of active alerts for the asset. Remove
                        # entries when the underlying condition clears;
                        # Lattice does not filter stale entries
                        # automatically.
                        active_alerts=[],
                        update_time=latest_timestamp
                    ),
                    # Declare the sensors carried by the asset. Each entry
                    # requires a stable sensor_id, a sensor_type, and at
                    # least one field of view so Lattice can render the
                    # sensor cone.
                    sensors=Sensors(
                        sensors=[
                            Sensor(
                                sensor_id="eoir-1",
                                sensor_type="SENSOR_TYPE_CAMERA",
                                sensor_description="EO/IR gimbal",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(gimbal_quat),
                                        ),
                                        horizontal_fov=0.5,
                                        vertical_fov=0.3,
                                        range=3000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                            Sensor(
                                sensor_id="rf-1",
                                sensor_type="SENSOR_TYPE_RF",
                                sensor_description="RF direction finder",
                                operational_state="OPERATIONAL_STATE_OPERATIONAL",
                                fields_of_view=[
                                    # Body-fixed, forward-facing mount.
                                    FieldOfView(
                                        center_ray_pose=EntityManagerPose(
                                            pos=position,
                                            orientation=to_quaternion(body_quat),
                                        ),
                                        horizontal_fov=2 * math.pi,  # Omnidirectional.
                                        vertical_fov=1.0,
                                        range=10000.0,
                                        mode="SENSOR_MODE_SEARCH",
                                    ),
                                ],
                            ),
                        ],
                    ),
                    task_catalog=TaskCatalog(
                        task_definitions=[
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId" ),
                            TaskDefinition( task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate" )
                        ]
                    )
                )
                print("Publishing asset.")
            except Exception as error:
                print(f"Error publishing entity: {error}")
            await asyncio.sleep(TICK_SECONDS)

    except asyncio.CancelledError:
        print(">>> Exiting...")

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

```

```ts title={"TypeScript (REST)"} startLine={224} maxLines={59}
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}`  }
    }
);

const entityId = uuidv4()
const expiryOffsetHours = 1;
const createdTime = new Date();

// Flight model constants.
const TICK_SECONDS = 1.0;          // Time between updates, in seconds.
const GROUND_SPEED = 20.0;         // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC = 3.0;     // Constant right turn, in degrees per second.
const BASE_ALT_HAE = 300.0;        // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE = 20.0;        // Altitude oscillation amplitude, in meters.
const ALT_PERIOD = 60.0;           // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP = 45.0;       // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD = 40.0;        // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG = -20.0;     // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY = 9.81;              // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE = true;

function toRadians(degrees: number): number {
    return degrees * (Math.PI / 180);
}

function toDegrees(radians: number): number {
    return radians * (180 / Math.PI);
}

type Quat = { x: number; y: number; z: number; w: number };

// Hamilton product a * b.
function multiply(a: Quat, b: Quat): Quat {
    return {
        x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
        y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
        z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
        w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
    };
}

// Elementary rotations about the x, y, and z axes, in radians.
const qx = (a: number): Quat => ({ x: Math.sin(a / 2), y: 0, z: 0, w: Math.cos(a / 2) });
const qy = (a: number): Quat => ({ x: 0, y: Math.sin(a / 2), z: 0, w: Math.cos(a / 2) });
const qz = (a: number): Quat => ({ x: 0, y: 0, z: Math.sin(a / 2), w: Math.cos(a / 2) });

// Convert a compass heading (degrees clockwise from north), pitch (positive
// nose up), and roll (positive right wing down) into the attitude_enu
// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
// frame.
function attitudeToQuaternionEnu(headingDeg: number, pitchDeg: number, rollDeg: number): Quat {
    const yaw = Math.PI / 2 - toRadians(headingDeg);
    return multiply(multiply(qz(yaw), qy(-toRadians(pitchDeg))), qx(toRadians(rollDeg)));
}

// Compose the body attitude with a gimbal pointing relative to the nose. Pan
// is positive to the right and tilt is positive up. The result rotates the
// sensor frame (+X is the boresight) into ENU.
function gimbalToQuaternionEnu(body: Quat, panDeg: number, tiltDeg: number): Quat {
    const mount = multiply(qz(-toRadians(panDeg)), qy(-toRadians(tiltDeg)));
    return multiply(body, mount);
}

// Convert an ENU velocity vector into a yaw angle, in radians. Fallback when
// your autopilot reports only velocity.
function velocityToYawEnu(velocityEast: number, velocityNorth: number): number {
    return Math.atan2(velocityNorth, velocityEast);
}

// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
// roll. Fallback when your autopilot reports only velocity.
function yawToQuaternionEnu(yawRad: number): Quat {
    return qz(yawRad);
}

// Simulated state of the vehicle. Starts near the origin, heading north.
const state = {
    lat: 50.914,        // Degrees.
    lon: 0.792,         // Degrees.
    altHae: BASE_ALT_HAE,
    courseDeg: 0,       // Direction of travel, degrees clockwise from north.
    velEast: 0,         // Meters per second.
    velNorth: 0,
    climb: 0,
    pitchDeg: 0,        // Positive nose up.
    rollDeg: 0,         // Positive right wing down.
    elapsed: 0,         // Seconds since start.
};

// Move the simulation forward by dt seconds.
function advanceState(dt: number) {
    state.elapsed += dt;

    // Turn at a constant rate and oscillate the altitude.
    state.courseDeg = (state.courseDeg + TURN_RATE_DEG_SEC * dt) % 360;
    const w = 2 * Math.PI / ALT_PERIOD;
    state.altHae = BASE_ALT_HAE + ALT_AMPLITUDE * Math.sin(w * state.elapsed);
    state.climb = ALT_AMPLITUDE * w * Math.cos(w * state.elapsed);

    // Velocity from ground speed, course, and climb rate.
    const course = toRadians(state.courseDeg);
    state.velEast = GROUND_SPEED * Math.sin(course);
    state.velNorth = GROUND_SPEED * Math.cos(course);

    // Integrate position: meters to degrees, scaling longitude by cos(lat).
    state.lat += state.velNorth * dt / METERS_PER_DEG;
    state.lon += state.velEast * dt / (METERS_PER_DEG * Math.cos(toRadians(state.lat)));

    // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    state.pitchDeg = toDegrees(Math.atan2(state.climb, GROUND_SPEED));
    state.rollDeg = toDegrees(Math.atan(GROUND_SPEED * toRadians(TURN_RATE_DEG_SEC) / GRAVITY));
}

async function App() {
    try {
        const latestTimestamp = new Date();
        advanceState(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        const bodyQuat = AUTOPILOT_REPORTS_ATTITUDE
            ? attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
            : yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth));
        const position = {
            latitudeDegrees: state.lat,
            longitudeDegrees: state.lon,
            altitudeHaeMeters: state.altHae,
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        const gimbalPan = GIMBAL_PAN_AMP * Math.sin(2 * Math.PI * state.elapsed / GIMBAL_PERIOD);
        const gimbalQuat = gimbalToQuaternionEnu(bodyQuat, gimbalPan, GIMBAL_TILT_DEG);
        const batteryPercent = Math.max(87 - 0.01 * state.elapsed, 0);

        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Friendly drone asset",
                aliases: { name: "Drone 1" },
                isLive: true,
                createdTime: createdTime.toISOString(),
                expiryTime: new Date(latestTimestamp.getTime() + expiryOffsetHours * 3600000).toISOString(),
                ontology: {
                    template: "TEMPLATE_ASSET",
                    platformType: "UAV"
                },
                milView: {
                    disposition: "DISPOSITION_FRIENDLY",
                    environment: "ENVIRONMENT_AIR",
                },
                location: {
                    position: position,
                    // Velocity in the ENU frame, in meters per second.
                    velocityEnu: { e: state.velEast, n: state.velNorth, u: state.climb },
                    // Body-to-ENU attitude. Lattice uses it for heading.
                    attitudeEnu: bodyQuat
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "your_data_type",
                    sourceUpdateTime: latestTimestamp.toISOString()
                },
                health: {
                    connectionStatus: "CONNECTION_STATUS_ONLINE",
                    healthStatus: "HEALTH_STATUS_HEALTHY",
                    // Report the health of individual subsystems in
                    // components. Each component needs a stable id, a display
                    // name, and a health status.
                    components: [
                        {
                            id: "battery-0",
                            name: "Battery",
                            health: "HEALTH_STATUS_HEALTHY",
                            messages: [
                                {
                                    status: "HEALTH_STATUS_HEALTHY",
                                    message: `Battery at ${batteryPercent.toFixed(0)}% charge.`
                                }
                            ],
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "eoir-1",
                            name: "EO/IR gimbal",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        },
                        {
                            id: "rf-1",
                            name: "RF direction finder",
                            health: "HEALTH_STATUS_HEALTHY",
                            updateTime: latestTimestamp.toISOString()
                        }
                    ],
                    // Live list of active alerts for the asset. Remove
                    // entries when the underlying condition clears; Lattice
                    // does not filter stale entries automatically.
                    activeAlerts: [],
                    updateTime: latestTimestamp.toISOString()
                },
                // Declare the sensors carried by the asset. Each entry
                // requires a stable sensor_id, a sensor_type, and at least
                // one field of view so Lattice can render the sensor cone.
                sensors: {
                    sensors: [
                        {
                            sensorId: "eoir-1",
                            sensorType: "SENSOR_TYPE_CAMERA",
                            sensorDescription: "EO/IR gimbal",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: gimbalQuat
                                    },
                                    horizontalFov: 0.5,
                                    verticalFov: 0.3,
                                    range: 3000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        },
                        {
                            sensorId: "rf-1",
                            sensorType: "SENSOR_TYPE_RF",
                            sensorDescription: "RF direction finder",
                            operationalState: "OPERATIONAL_STATE_OPERATIONAL",
                            fieldsOfView: [
                                // Body-fixed, forward-facing mount.
                                {
                                    centerRayPose: {
                                        pos: position,
                                        orientation: bodyQuat
                                    },
                                    horizontalFov: 2 * Math.PI, // Omnidirectional.
                                    verticalFov: 1.0,
                                    range: 10000.0,
                                    mode: "SENSOR_MODE_SEARCH"
                                }
                            ]
                        }
                    ]
                },
                taskCatalog: {
                    taskDefinitions: [
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId" },
                        { taskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate" }
                    ]
                }
            }
        );
        console.log(`Publishing asset.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Wait for 1 second before the next iteration
        await new Promise(resolve => setTimeout(resolve, TICK_SECONDS * 1000));
    }
})();

```

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

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

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the SDK type.
    fn to_sdk(self) -> Quaternion {
        Quaternion {
            x: Some(self.x),
            y: Some(self.y),
            z: Some(self.z),
            w: Some(self.w),
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = std::f64::consts::FRAC_PI_2 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * std::f64::consts::PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: Some(self.lat),
            longitude_degrees: Some(self.lon),
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

#[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 id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_time = Utc::now().fixed_offset();
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * std::f64::consts::PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        let entity = Entity {
            entity_id: Some(id.clone()),
            description: Some("Friendly drone asset".to_string()),
            aliases: Some(Aliases {
                name: Some("Drone 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            expiry_time: Some((Utc::now() + chrono::Duration::hours(1)).fixed_offset()),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateAsset),
                platform_type: Some("UAV".to_string()),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Some(MilViewDisposition::DispositionFriendly),
                environment: Some(MilViewEnvironment::EnvironmentAir),
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: Some(state.vel_east),
                    n: Some(state.vel_north),
                    u: Some(state.climb),
                    ..Default::default()
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_sdk()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("your_data_type".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: Some(HealthConnectionStatus::ConnectionStatusOnline),
                health_status: Some(HealthHealthStatus::HealthStatusHealthy),
                // Report the health of individual subsystems in components. Each
                // component needs a stable id, a display name, and a health
                // status.
                components: Some(vec![
                    ComponentHealth {
                        id: Some("battery-0".to_string()),
                        name: Some("Battery".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        messages: Some(vec![ComponentMessage {
                            status: Some(ComponentMessageStatus::HealthStatusHealthy),
                            message: Some(format!("Battery at {:.0}% charge.", battery_percent)),
                            ..Default::default()
                        }]),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("eoir-1".to_string()),
                        name: Some("EO/IR gimbal".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                    ComponentHealth {
                        id: Some("rf-1".to_string()),
                        name: Some("RF direction finder".to_string()),
                        health: Some(ComponentHealthHealth::HealthStatusHealthy),
                        update_time: Some(latest_timestamp),
                        ..Default::default()
                    },
                ]),
                // Live list of active alerts for the asset. Remove entries when
                // the underlying condition clears; Lattice does not filter stale
                // entries automatically.
                active_alerts: Some(vec![]),
                update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            // Declare the sensors carried by the asset. Each entry requires a
            // stable sensor_id, a sensor_type, and at least one field of view so
            // Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: Some(vec![
                    Sensor {
                        sensor_id: Some("eoir-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeCamera),
                        sensor_description: Some("EO/IR gimbal".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(0.5),
                            vertical_fov: Some(0.3),
                            range: Some(3000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: Some("rf-1".to_string()),
                        sensor_type: Some(SensorSensorType::SensorTypeRf),
                        sensor_description: Some("RF direction finder".to_string()),
                        operational_state: Some(SensorOperationalState::OperationalStateOperational),
                        // Body-fixed, forward-facing mount.
                        fields_of_view: Some(vec![FieldOfView {
                            center_ray_pose: Some(EntityManagerPose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_sdk()),
                                ..Default::default()
                            }),
                            horizontal_fov: Some(2.0 * std::f64::consts::PI), // Omnidirectional.
                            vertical_fov: Some(1.0),
                            range: Some(10000.0),
                            mode: Some(FieldOfViewMode::SensorModeSearch),
                            ..Default::default()
                        }]),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: Some(vec![
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.VisualId".to_string(),
                        ),
                        ..Default::default()
                    },
                    TaskDefinition {
                        task_specification_url: Some(
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                        ),
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            }),
            ..Default::default()
        };

        match client.entities.publish_entity(&entity, None).await {
            Ok(_) => println!("Publishing asset with entity ID: {}", id),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={270} maxLines={69}
// 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"
	"math"
	"os"
	"time"

	"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"
	"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"
	tasksv2 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/tasks/v2"
	_type "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/type"
)

// Flight model constants.
const (
	tickSeconds    = 1.0   // Time between updates, in seconds.
	groundSpeed    = 20.0  // Ground speed, in meters per second.
	turnRateDegSec = 3.0   // Constant right turn, in degrees per second.
	baseAltHae     = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
	altAmplitude   = 20.0  // Altitude oscillation amplitude, in meters.
	altPeriod      = 60.0  // Altitude oscillation period, in seconds.
	gimbalPanAmp   = 45.0  // Gimbal pan sweep, in degrees either side of the nose.
	gimbalPeriod   = 40.0  // Gimbal pan sweep period, in seconds.
	gimbalTiltDeg  = -20.0 // Gimbal tilt, in degrees. Negative looks down.
	gravity        = 9.81  // Gravitational acceleration, in meters per second squared.
	metersPerDeg   = 111320.0

	// Set to false to derive the attitude from velocity alone.
	autopilotReportsAttitude = true
)

// quat is a quaternion in (x, y, z, w) order.
type quat struct{ x, y, z, w float64 }

// multiply returns the Hamilton product a ⊗ b.
func (a quat) multiply(b quat) quat {
	return quat{
		x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y,
		y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x,
		z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w,
		w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z,
	}
}

// Elementary rotations about the x, y, and z axes, in radians.
func qx(a float64) quat { return quat{x: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qy(a float64) quat { return quat{y: math.Sin(a / 2), w: math.Cos(a / 2)} }
func qz(a float64) quat { return quat{z: math.Sin(a / 2), w: math.Cos(a / 2)} }

// attitudeToQuaternionEnu converts a compass heading (degrees clockwise from
// north), pitch (positive nose up), and roll (positive right wing down) into
// the attitude_enu quaternion. attitude_enu rotates the body frame (FLU) into
// the ENU world frame.
func attitudeToQuaternionEnu(headingDeg, pitchDeg, rollDeg float64) quat {
	yaw := math.Pi/2 - headingDeg*math.Pi/180
	return qz(yaw).multiply(qy(-pitchDeg * math.Pi / 180)).multiply(qx(rollDeg * math.Pi / 180))
}

// gimbalToQuaternionEnu composes the body attitude with a gimbal pointing
// relative to the nose. Pan is positive to the right and tilt is positive up.
// The result rotates the sensor frame (+X is the boresight) into ENU.
func gimbalToQuaternionEnu(body quat, panDeg, tiltDeg float64) quat {
	mount := qz(-panDeg * math.Pi / 180).multiply(qy(-tiltDeg * math.Pi / 180))
	return body.multiply(mount)
}

// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. Fallback when your autopilot reports only velocity.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
	return math.Atan2(velocityNorth, velocityEast)
}

// yawToQuaternionEnu converts a yaw angle into an attitude_enu quaternion with
// zero pitch and roll. Fallback when your autopilot reports only velocity.
func yawToQuaternionEnu(yawRad float64) quat {
	return qz(yawRad)
}

// toQuaternion converts a quat into the protobuf type.
func toQuaternion(q quat) *_type.Quaternion {
	return &_type.Quaternion{X: q.x, Y: q.y, Z: q.z, W: q.w}
}

// flightState is the simulated state of the vehicle.
type flightState struct {
	lat, lon, altHae         float64 // Position, in degrees and meters.
	courseDeg                float64 // Direction of travel, degrees clockwise from north.
	velEast, velNorth, climb float64 // Velocity, in meters per second.
	pitchDeg, rollDeg        float64 // Pitch is positive nose up. Roll is positive right wing down.
	elapsed                  float64 // Seconds since start.
}

// advanceState moves the simulation forward by dt seconds.
func advanceState(s *flightState, dt float64) {
	s.elapsed += dt

	// Turn at a constant rate and oscillate the altitude.
	s.courseDeg = math.Mod(s.courseDeg+turnRateDegSec*dt, 360)
	w := 2 * math.Pi / altPeriod
	s.altHae = baseAltHae + altAmplitude*math.Sin(w*s.elapsed)
	s.climb = altAmplitude * w * math.Cos(w*s.elapsed)

	// Velocity from ground speed, course, and climb rate.
	course := s.courseDeg * math.Pi / 180
	s.velEast = groundSpeed * math.Sin(course)
	s.velNorth = groundSpeed * math.Cos(course)

	// Integrate position: meters to degrees, scaling longitude by cos(lat).
	s.lat += s.velNorth * dt / metersPerDeg
	s.lon += s.velEast * dt / (metersPerDeg * math.Cos(s.lat*math.Pi/180))

	// Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
	s.pitchDeg = math.Atan2(s.climb, groundSpeed) * 180 / math.Pi
	s.rollDeg = math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
}

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)
	}

	// 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 (using NewClient instead of Dial which is deprecated)
	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
	entityId := uuid.New().String()

	// Start near the origin, heading north.
	state := &flightState{lat: 50.914, lon: 0.792, altHae: baseAltHae}
	creationTimestamp := timestamppb.Now()

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

		advanceState(state, tickSeconds)

		// Heading equals course because the simulation has no wind.
		bodyQuat := attitudeToQuaternionEnu(state.courseDeg, state.pitchDeg, state.rollDeg)
		if !autopilotReportsAttitude {
			bodyQuat = yawToQuaternionEnu(velocityToYawEnu(state.velEast, state.velNorth))
		}
		position := func() *entitymanagerv1.Position {
			return &entitymanagerv1.Position{
				LatitudeDegrees:   state.lat,
				LongitudeDegrees:  state.lon,
				AltitudeHaeMeters: wrapperspb.Double(state.altHae),
			}
		}
		// The gimbal sweeps relative to the nose. FieldOfView orientation is
		// absolute ENU, so compose it with the body attitude.
		gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*state.elapsed/gimbalPeriod)
		gimbalQuat := gimbalToQuaternionEnu(bodyQuat, gimbalPan, gimbalTiltDeg)
		batteryPercent := math.Max(87-0.01*state.elapsed, 0)

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Friendly drone asset",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Drone 1",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			ExpiryTime:  timestamppb.New(latestTimestamp.Add(1 * time.Hour)),
			Ontology: &entitymanagerv1.Ontology{
				Template:     entitymanagerv1.Template_TEMPLATE_ASSET,
				PlatformType: "UAV",
			},
			MilView: &entitymanagerv1.MilView{
				Disposition: ontologyv1.Disposition_DISPOSITION_FRIENDLY,
				Environment: ontologyv1.Environment_ENVIRONMENT_AIR,
			},
			Location: &entitymanagerv1.Location{
				Position: position(),
				// Velocity in the ENU frame, in meters per second.
				VelocityEnu: &_type.ENU{
					E: state.velEast,
					N: state.velNorth,
					U: state.climb,
				},
				// Body-to-ENU attitude. Lattice uses it for heading.
				AttitudeEnu: toQuaternion(bodyQuat),
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "your_data_type",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
			Health: &entitymanagerv1.Health{
				ConnectionStatus: entitymanagerv1.ConnectionStatus_CONNECTION_STATUS_ONLINE,
				HealthStatus:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
				// Report the health of individual subsystems in components.
				// Each component needs a stable ID, a display name, and a
				// health status.
				Components: []*entitymanagerv1.ComponentHealth{
					{
						Id:     "battery-0",
						Name:   "Battery",
						Health: entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						Messages: []*entitymanagerv1.ComponentMessage{
							{
								Status:  entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
								Message: fmt.Sprintf("Battery at %.0f%% charge.", batteryPercent),
							},
						},
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "eoir-1",
						Name:       "EO/IR gimbal",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
					{
						Id:         "rf-1",
						Name:       "RF direction finder",
						Health:     entitymanagerv1.HealthStatus_HEALTH_STATUS_HEALTHY,
						UpdateTime: timestamppb.New(latestTimestamp),
					},
				},
				// Live list of active alerts for the asset. Remove entries
				// when the underlying condition clears; Lattice does not
				// filter stale entries automatically.
				ActiveAlerts: []*entitymanagerv1.Alert{},
				UpdateTime:   timestamppb.New(latestTimestamp),
			},
			// Declare the sensors carried by the asset. Each entry requires a
			// stable sensor_id, a sensor_type, and at least one field of view
			// so Lattice can render the sensor cone.
			Sensors: &entitymanagerv1.Sensors{
				Sensors: []*entitymanagerv1.Sensor{
					{
						SensorId:          "eoir-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_CAMERA,
						SensorDescription: "EO/IR gimbal",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(gimbalQuat),
								},
								HorizontalFov: 0.5,
								VerticalFov:   0.3,
								Range:         wrapperspb.Float(3000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
					{
						SensorId:          "rf-1",
						SensorType:        entitymanagerv1.SensorType_SENSOR_TYPE_RF,
						SensorDescription: "RF direction finder",
						OperationalState:  entitymanagerv1.OperationalState_OPERATIONAL_STATE_OPERATIONAL,
						FieldsOfView: []*entitymanagerv1.FieldOfView{
							{
								// Body-fixed, forward-facing mount.
								CenterRayPose: &entitymanagerv1.Pose{
									Pos:         position(),
									Orientation: toQuaternion(bodyQuat),
								},
								HorizontalFov: 2 * math.Pi, // Omnidirectional.
								VerticalFov:   1.0,
								Range:         wrapperspb.Float(10000.0),
								Mode:          entitymanagerv1.SensorMode_SENSOR_MODE_SEARCH,
							},
						},
					},
				},
			},
			TaskCatalog: &tasksv2.TaskCatalog{
				TaskDefinitions: []*tasksv2.TaskDefinition{
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.VisualId",
					},
					{
						TaskSpecificationUrl: "type.googleapis.com/anduril.tasks.v2.Investigate",
					},
				},
			},
		}

		// 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 asset with entity ID: %s\n", entityId)
		}

		time.Sleep(1 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={265} maxLines={56}
# 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 math
import os
import sys
import time
import uuid
from datetime import datetime, timedelta, timezone
from bearer_auth import create_client
from protobuf.wkt import DoubleValue, FloatValue, 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.health_status_pub_pb import (
    ComponentHealth,
    ComponentMessage,
    ConnectionStatus,
    Health,
    HealthStatus,
)
from anduril.entitymanager.v1.location_pub_pb import Location, Pose, Position
from anduril.entitymanager.v1.ontology_pub_pb import MilView, Ontology
from anduril.entitymanager.v1.sensors_pub_pb import (
    FieldOfView,
    OperationalState,
    Sensor,
    SensorMode,
    Sensors,
    SensorType,
)
from anduril.entitymanager.v1.types_pub_pb import Template
from anduril.ontology.v1.type_pub_pb import Disposition, Environment
from anduril.tasks.v2.catalog_pub_pb import TaskCatalog, TaskDefinition
from anduril.type.coords_pub_pb import ENU, Quaternion


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


# Flight model constants.
TICK_SECONDS = 1.0           # Time between updates, in seconds.
GROUND_SPEED = 20.0          # Ground speed, in meters per second.
TURN_RATE_DEG_SEC = 3.0      # Constant right turn, in degrees per second.
BASE_ALT_HAE = 300.0         # Mean altitude above the WGS84 ellipsoid, in meters.
ALT_AMPLITUDE = 20.0         # Altitude oscillation amplitude, in meters.
ALT_PERIOD = 60.0            # Altitude oscillation period, in seconds.
GIMBAL_PAN_AMP = 45.0        # Gimbal pan sweep, in degrees either side of the nose.
GIMBAL_PERIOD = 40.0         # Gimbal pan sweep period, in seconds.
GIMBAL_TILT_DEG = -20.0      # Gimbal tilt, in degrees. Negative looks down.
GRAVITY = 9.81               # Gravitational acceleration, in meters per second squared.
METERS_PER_DEG = 111320.0

# Set to False to derive the attitude from velocity alone.
AUTOPILOT_REPORTS_ATTITUDE = True


def multiply(a, b):
    """Hamilton product a * b of two (x, y, z, w) quaternions."""
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return (
        aw * bx + ax * bw + ay * bz - az * by,
        aw * by - ax * bz + ay * bw + az * bx,
        aw * bz + ax * by - ay * bx + az * bw,
        aw * bw - ax * bx - ay * by - az * bz,
    )


def qx(a):
    """Rotation of a radians about the x axis."""
    return (math.sin(a / 2), 0.0, 0.0, math.cos(a / 2))


def qy(a):
    """Rotation of a radians about the y axis."""
    return (0.0, math.sin(a / 2), 0.0, math.cos(a / 2))


def qz(a):
    """Rotation of a radians about the z axis."""
    return (0.0, 0.0, math.sin(a / 2), math.cos(a / 2))


def attitude_to_quaternion_enu(heading_deg, pitch_deg, roll_deg):
    """Convert a compass heading (degrees clockwise from north), pitch
    (positive nose up), and roll (positive right wing down) into the
    attitude_enu quaternion.

    attitude_enu rotates the body frame (FLU) into the ENU world frame.
    """
    yaw = math.pi / 2 - math.radians(heading_deg)
    return multiply(multiply(qz(yaw), qy(-math.radians(pitch_deg))), qx(math.radians(roll_deg)))


def gimbal_to_quaternion_enu(body, pan_deg, tilt_deg):
    """Compose the body attitude with a gimbal pointing relative to the nose.

    Pan is positive to the right and tilt is positive up. The result rotates
    the sensor frame (+X is the boresight) into ENU.
    """
    mount = multiply(qz(-math.radians(pan_deg)), qy(-math.radians(tilt_deg)))
    return multiply(body, mount)


def velocity_to_yaw_enu(velocity_east, velocity_north):
    """Convert an ENU velocity vector into a yaw angle, in radians.

    Fallback when your autopilot reports only velocity.
    """
    return math.atan2(velocity_north, velocity_east)


def yaw_to_quaternion_enu(yaw_rad):
    """Convert a yaw angle into an attitude_enu quaternion with zero pitch
    and roll.

    Fallback when your autopilot reports only velocity.
    """
    return qz(yaw_rad)


def to_quaternion(q):
    """Convert an (x, y, z, w) tuple into the protobuf type."""
    return Quaternion(x=q[0], y=q[1], z=q[2], w=q[3])


def advance_state(s, dt):
    """Move the simulation forward by dt seconds."""
    s["elapsed"] += dt

    # Turn at a constant rate and oscillate the altitude.
    s["course_deg"] = (s["course_deg"] + TURN_RATE_DEG_SEC * dt) % 360
    w = 2 * math.pi / ALT_PERIOD
    s["alt_hae"] = BASE_ALT_HAE + ALT_AMPLITUDE * math.sin(w * s["elapsed"])
    s["climb"] = ALT_AMPLITUDE * w * math.cos(w * s["elapsed"])

    # Velocity from ground speed, course, and climb rate.
    course = math.radians(s["course_deg"])
    s["vel_east"] = GROUND_SPEED * math.sin(course)
    s["vel_north"] = GROUND_SPEED * math.cos(course)

    # Integrate position: meters to degrees, scaling longitude by cos(lat).
    s["lat"] += s["vel_north"] * dt / METERS_PER_DEG
    s["lon"] += s["vel_east"] * dt / (METERS_PER_DEG * math.cos(math.radians(s["lat"])))

    # Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
    s["pitch_deg"] = math.degrees(math.atan2(s["climb"], GROUND_SPEED))
    s["roll_deg"] = math.degrees(math.atan(GROUND_SPEED * math.radians(TURN_RATE_DEG_SEC) / GRAVITY))


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)

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

    entity_id = str(uuid.uuid4())

    # Start near the origin, heading north.
    state = {
        "lat": 50.914, "lon": 0.792, "alt_hae": BASE_ALT_HAE,
        "course_deg": 0.0, "vel_east": 0.0, "vel_north": 0.0, "climb": 0.0,
        "pitch_deg": 0.0, "roll_deg": 0.0, "elapsed": 0.0,
    }
    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(hours=1))

        advance_state(state, TICK_SECONDS)

        # Heading equals course because the simulation has no wind.
        if AUTOPILOT_REPORTS_ATTITUDE:
            body_quat = attitude_to_quaternion_enu(state["course_deg"], state["pitch_deg"], state["roll_deg"])
        else:
            body_quat = yaw_to_quaternion_enu(velocity_to_yaw_enu(state["vel_east"], state["vel_north"]))
        position = Position(
            latitude_degrees=state["lat"],
            longitude_degrees=state["lon"],
            altitude_hae_meters=DoubleValue(value=state["alt_hae"]),
        )
        # The gimbal sweeps relative to the nose. FieldOfView orientation is
        # absolute ENU, so compose it with the body attitude.
        gimbal_pan = GIMBAL_PAN_AMP * math.sin(2 * math.pi * state["elapsed"] / GIMBAL_PERIOD)
        gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG)
        battery_percent = max(87 - 0.01 * state["elapsed"], 0)

        entity = Entity(
            entity_id=entity_id,
            description="Friendly drone asset",
            aliases=Aliases(name="Drone 1"),
            is_live=True,
            created_time=creation_timestamp,
            expiry_time=expiry_ts,
            ontology=Ontology(template=Template.ASSET, platform_type="UAV"),
            mil_view=MilView(
                disposition=Disposition.FRIENDLY,
                environment=Environment.AIR,
            ),
            location=Location(
                position=position,
                # Velocity in the ENU frame, in meters per second.
                velocity_enu=ENU(e=state["vel_east"], n=state["vel_north"], u=state["climb"]),
                # Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu=to_quaternion(body_quat),
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="your_data_type",
                source_update_time=latest_ts,
            ),
            health=Health(
                connection_status=ConnectionStatus.ONLINE,
                health_status=HealthStatus.HEALTHY,
                # Report the health of individual subsystems in components.
                # Each component needs a stable id, a display name, and a
                # health status.
                components=[
                    ComponentHealth(
                        id="battery-0",
                        name="Battery",
                        health=HealthStatus.HEALTHY,
                        messages=[
                            ComponentMessage(
                                status=HealthStatus.HEALTHY,
                                message=f"Battery at {battery_percent:.0f}% charge.",
                            ),
                        ],
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="eoir-1",
                        name="EO/IR gimbal",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                    ComponentHealth(
                        id="rf-1",
                        name="RF direction finder",
                        health=HealthStatus.HEALTHY,
                        update_time=latest_ts,
                    ),
                ],
                # Live list of active alerts for the asset. Remove entries
                # when the underlying condition clears; Lattice does not
                # filter stale entries automatically.
                active_alerts=[],
                update_time=latest_ts,
            ),
            # Declare the sensors carried by the asset. Each entry requires a
            # stable sensor_id, a sensor_type, and at least one field of view
            # so Lattice can render the sensor cone.
            sensors=Sensors(
                sensors=[
                    Sensor(
                        sensor_id="eoir-1",
                        sensor_type=SensorType.CAMERA,
                        sensor_description="EO/IR gimbal",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(gimbal_quat),
                                ),
                                horizontal_fov=0.5,
                                vertical_fov=0.3,
                                range=FloatValue(value=3000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                    Sensor(
                        sensor_id="rf-1",
                        sensor_type=SensorType.RF,
                        sensor_description="RF direction finder",
                        operational_state=OperationalState.OPERATIONAL,
                        fields_of_view=[
                            # Body-fixed, forward-facing mount.
                            FieldOfView(
                                center_ray_pose=Pose(
                                    pos=position,
                                    orientation=to_quaternion(body_quat),
                                ),
                                horizontal_fov=2 * math.pi,  # Omnidirectional.
                                vertical_fov=1.0,
                                range=FloatValue(value=10000.0),
                                mode=SensorMode.SEARCH,
                            ),
                        ],
                    ),
                ],
            ),
            task_catalog=TaskCatalog(
                task_definitions=[
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.VisualId"),
                    TaskDefinition(task_specification_url="type.googleapis.com/anduril.tasks.v2.Investigate"),
                ],
            ),
        )

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

        time.sleep(TICK_SECONDS)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={337} maxLines={65}
// 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::{
    Aliases, ComponentHealth, ComponentMessage, ConnectionStatus, Entity, FieldOfView, Health,
    HealthStatus, Location, MilView, Ontology, OperationalState, Pose, Position, Provenance,
    PublishEntityRequest, Sensor, SensorMode, SensorType, Sensors, Template,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::ontology::v1::{
    Disposition, Environment,
};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::r#type::{Enu, Quaternion};
use anduril_lattice_sdk_community_neoeinstein_prost::anduril::tasks::v2::{
    TaskCatalog, TaskDefinition,
};
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::f64::consts::PI;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// Flight model constants.
const TICK_SECONDS: f64 = 1.0; // Time between updates, in seconds.
const GROUND_SPEED: f64 = 20.0; // Ground speed, in meters per second.
const TURN_RATE_DEG_SEC: f64 = 3.0; // Constant right turn, in degrees per second.
const BASE_ALT_HAE: f64 = 300.0; // Mean altitude above the WGS84 ellipsoid, in meters.
const ALT_AMPLITUDE: f64 = 20.0; // Altitude oscillation amplitude, in meters.
const ALT_PERIOD: f64 = 60.0; // Altitude oscillation period, in seconds.
const GIMBAL_PAN_AMP: f64 = 45.0; // Gimbal pan sweep, in degrees either side of the nose.
const GIMBAL_PERIOD: f64 = 40.0; // Gimbal pan sweep period, in seconds.
const GIMBAL_TILT_DEG: f64 = -20.0; // Gimbal tilt, in degrees. Negative looks down.
const GRAVITY: f64 = 9.81; // Gravitational acceleration, in meters per second squared.
const METERS_PER_DEG: f64 = 111320.0;

// Set to false to derive the attitude from velocity alone.
const AUTOPILOT_REPORTS_ATTITUDE: bool = true;

/// A quaternion in (x, y, z, w) order.
#[derive(Clone, Copy)]
struct Quat {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl Quat {
    /// Hamilton product `self ⊗ b`.
    fn multiply(self, b: Quat) -> Quat {
        let a = self;
        Quat {
            x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
            w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
        }
    }

    /// Convert into the protobuf type.
    fn to_proto(self) -> Quaternion {
        Quaternion {
            x: self.x,
            y: self.y,
            z: self.z,
            w: self.w,
        }
    }
}

// Elementary rotations about the x, y, and z axes, in radians.
fn qx(a: f64) -> Quat {
    Quat { x: (a / 2.0).sin(), y: 0.0, z: 0.0, w: (a / 2.0).cos() }
}
fn qy(a: f64) -> Quat {
    Quat { x: 0.0, y: (a / 2.0).sin(), z: 0.0, w: (a / 2.0).cos() }
}
fn qz(a: f64) -> Quat {
    Quat { x: 0.0, y: 0.0, z: (a / 2.0).sin(), w: (a / 2.0).cos() }
}

/// Convert a compass heading (degrees clockwise from north), pitch (positive
/// nose up), and roll (positive right wing down) into the attitude_enu
/// quaternion. attitude_enu rotates the body frame (FLU) into the ENU world
/// frame.
fn attitude_to_quaternion_enu(heading_deg: f64, pitch_deg: f64, roll_deg: f64) -> Quat {
    let yaw = PI / 2.0 - heading_deg.to_radians();
    qz(yaw)
        .multiply(qy(-pitch_deg.to_radians()))
        .multiply(qx(roll_deg.to_radians()))
}

/// Compose the body attitude with a gimbal pointing relative to the nose. Pan
/// is positive to the right and tilt is positive up. The result rotates the
/// sensor frame (+X is the boresight) into ENU.
fn gimbal_to_quaternion_enu(body: Quat, pan_deg: f64, tilt_deg: f64) -> Quat {
    let mount = qz(-pan_deg.to_radians()).multiply(qy(-tilt_deg.to_radians()));
    body.multiply(mount)
}

/// Convert an ENU velocity vector into a yaw angle, in radians.
/// Fallback when your autopilot reports only velocity.
fn velocity_to_yaw_enu(velocity_east: f64, velocity_north: f64) -> f64 {
    velocity_north.atan2(velocity_east)
}

/// Convert a yaw angle into an attitude_enu quaternion with zero pitch and
/// roll. Fallback when your autopilot reports only velocity.
fn yaw_to_quaternion_enu(yaw_rad: f64) -> Quat {
    qz(yaw_rad)
}

/// Simulated state of the vehicle.
struct FlightState {
    lat: f64,        // Degrees.
    lon: f64,        // Degrees.
    alt_hae: f64,    // Meters.
    course_deg: f64, // Direction of travel, degrees clockwise from north.
    vel_east: f64,   // Meters per second.
    vel_north: f64,
    climb: f64,
    pitch_deg: f64, // Positive nose up.
    roll_deg: f64,  // Positive right wing down.
    elapsed: f64,   // Seconds since start.
}

impl FlightState {
    /// Move the simulation forward by dt seconds.
    fn advance(&mut self, dt: f64) {
        self.elapsed += dt;

        // Turn at a constant rate and oscillate the altitude.
        self.course_deg = (self.course_deg + TURN_RATE_DEG_SEC * dt) % 360.0;
        let w = 2.0 * PI / ALT_PERIOD;
        self.alt_hae = BASE_ALT_HAE + ALT_AMPLITUDE * (w * self.elapsed).sin();
        self.climb = ALT_AMPLITUDE * w * (w * self.elapsed).cos();

        // Velocity from ground speed, course, and climb rate.
        let course = self.course_deg.to_radians();
        self.vel_east = GROUND_SPEED * course.sin();
        self.vel_north = GROUND_SPEED * course.cos();

        // Integrate position: meters to degrees, scaling longitude by cos(lat).
        self.lat += self.vel_north * dt / METERS_PER_DEG;
        self.lon += self.vel_east * dt / (METERS_PER_DEG * self.lat.to_radians().cos());

        // Pitch follows the climb angle. Bank balances the turn: atan(v*omega/g).
        self.pitch_deg = self.climb.atan2(GROUND_SPEED).to_degrees();
        self.roll_deg = (GROUND_SPEED * TURN_RATE_DEG_SEC.to_radians() / GRAVITY)
            .atan()
            .to_degrees();
    }

    fn position(&self) -> Position {
        Position {
            latitude_degrees: self.lat,
            longitude_degrees: self.lon,
            altitude_hae_meters: Some(self.alt_hae),
            ..Default::default()
        }
    }
}

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");

    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)
        },
    );

    // Generate a unique ID for the entity
    let entity_id = Uuid::new_v4().to_string();

    // Start near the origin, heading north.
    let mut state = FlightState {
        lat: 50.914,
        lon: 0.792,
        alt_hae: BASE_ALT_HAE,
        course_deg: 0.0,
        vel_east: 0.0,
        vel_north: 0.0,
        climb: 0.0,
        pitch_deg: 0.0,
        roll_deg: 0.0,
        elapsed: 0.0,
    };
    let creation_timestamp = now_timestamp();

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

        state.advance(TICK_SECONDS);

        // Heading equals course because the simulation has no wind.
        let body_quat = if AUTOPILOT_REPORTS_ATTITUDE {
            attitude_to_quaternion_enu(state.course_deg, state.pitch_deg, state.roll_deg)
        } else {
            yaw_to_quaternion_enu(velocity_to_yaw_enu(state.vel_east, state.vel_north))
        };
        // The gimbal sweeps relative to the nose. FieldOfView orientation is
        // absolute ENU, so compose it with the body attitude.
        let gimbal_pan = GIMBAL_PAN_AMP * (2.0 * PI * state.elapsed / GIMBAL_PERIOD).sin();
        let gimbal_quat = gimbal_to_quaternion_enu(body_quat, gimbal_pan, GIMBAL_TILT_DEG);
        let battery_percent = (87.0 - 0.01 * state.elapsed).max(0.0);

        // Create entity to publish
        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Friendly drone asset".to_string(),
            aliases: Some(Aliases {
                name: "Drone 1".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp),
            expiry_time: Some(add_seconds(&latest_timestamp, 3600)),
            ontology: Some(Ontology {
                template: Template::Asset as i32,
                platform_type: "UAV".to_string(),
                ..Default::default()
            }),
            mil_view: Some(MilView {
                disposition: Disposition::Friendly as i32,
                environment: Environment::Air as i32,
                ..Default::default()
            }),
            location: Some(Location {
                position: Some(state.position()),
                // Velocity in the ENU frame, in meters per second.
                velocity_enu: Some(Enu {
                    e: state.vel_east,
                    n: state.vel_north,
                    u: state.climb,
                }),
                // Body-to-ENU attitude. Lattice uses it for heading.
                attitude_enu: Some(body_quat.to_proto()),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "your_data_type".to_string(),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            health: Some(Health {
                connection_status: ConnectionStatus::Online as i32,
                health_status: HealthStatus::Healthy as i32,
                // Report the health of individual subsystems in components.
                // Each component needs a stable id, a display name, and a
                // health status.
                components: vec![
                    ComponentHealth {
                        id: "battery-0".to_string(),
                        name: "Battery".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![ComponentMessage {
                            status: HealthStatus::Healthy as i32,
                            message: format!("Battery at {:.0}% charge.", battery_percent),
                        }],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "eoir-1".to_string(),
                        name: "EO/IR gimbal".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                    ComponentHealth {
                        id: "rf-1".to_string(),
                        name: "RF direction finder".to_string(),
                        health: HealthStatus::Healthy as i32,
                        messages: vec![],
                        update_time: Some(latest_timestamp),
                    },
                ],
                // Live list of active alerts for the asset. Remove entries
                // when the underlying condition clears; Lattice does not
                // filter stale entries automatically.
                active_alerts: vec![],
                update_time: Some(latest_timestamp),
            }),
            // Declare the sensors carried by the asset. Each entry requires
            // a stable sensor_id, a sensor_type, and at least one field of
            // view so Lattice can render the sensor cone.
            sensors: Some(Sensors {
                sensors: vec![
                    Sensor {
                        sensor_id: "eoir-1".to_string(),
                        sensor_type: SensorType::Camera as i32,
                        sensor_description: "EO/IR gimbal".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(gimbal_quat.to_proto()),
                            }),
                            horizontal_fov: 0.5,
                            vertical_fov: 0.3,
                            range: Some(3000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                    Sensor {
                        sensor_id: "rf-1".to_string(),
                        sensor_type: SensorType::Rf as i32,
                        sensor_description: "RF direction finder".to_string(),
                        operational_state: OperationalState::Operational as i32,
                        // Body-fixed, forward-facing mount.
                        fields_of_view: vec![FieldOfView {
                            center_ray_pose: Some(Pose {
                                pos: Some(state.position()),
                                orientation: Some(body_quat.to_proto()),
                            }),
                            horizontal_fov: (2.0 * PI) as f32, // Omnidirectional.
                            vertical_fov: 1.0,
                            range: Some(10000.0),
                            mode: SensorMode::Search as i32,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
            }),
            task_catalog: Some(TaskCatalog {
                task_definitions: vec![
                    TaskDefinition {
                        task_specification_url: "type.googleapis.com/anduril.tasks.v2.VisualId"
                            .to_string(),
                    },
                    TaskDefinition {
                        task_specification_url:
                            "type.googleapis.com/anduril.tasks.v2.Investigate".to_string(),
                    },
                ],
            }),
            ..Default::default()
        };

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

        tokio::time::sleep(Duration::from_secs_f64(TICK_SECONDS)).await;
    }
}

```

The RF direction finder uses `sensorId` `rf-1`. A line-of-bearing track from this sensor refers
to it in its `trackedBy` relationship. For more information, see
[Create a track](/guides/entities/create-a-track#publish-a-3d-track).

## What's next?

* Publish the detections from these sensors as [fusion-ready tracks](/guides/entities/create-a-track).
* Stream a camera's video with [Create streams](/guides/video/create-streams).
* Make your asset taskable by [integrating an agent](/guides/tasks/integrate-an-agent).