Skip to navigation

Cue and monitor

Fetch, stream, and filter entities to follow a target track from an effector

Effectors, such as interceptors, jammers, and other weapons systems, act on tracks that other sensors publish to Lattice. A typical engagement has two phases:

  • Cue: The effector receives the entity ID of a target track, for example from a task or an operator’s selection.
  • Monitor: Until the engagement ends, the effector follows that track’s newest position and velocity, and reacts when the track disappears.

This page shows how to get a single entity, how to stream entity events, and how to filter a stream down to exactly the tracks an effector cares about. The examples use the following APIs:

  • GetEntity: Retrieves the current state of one entity.
  • StreamEntities: Opens a persistent stream of entity events over REST, which you can filter on the server.
  • StreamEntityComponents: Opens the same filtered stream over gRPC, with optional per-entity rate limits.

Before you begin

  • To get and stream entities, set up the Lattice SDK and set up a Lattice environment.
  • Publish your effector as an asset, so operators can see and task it. For more information, see Create an asset.
  • Learn how tracks carry position and velocity in Create a track.
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 before running the examples on this page.

Get an entity

When an effector is cued, it first needs the target’s current state. Use the GetEntity API method with the target’s entity_id to retrieve a snapshot of the entity:

1

Get the entity ID

The entity ID usually arrives with the cue, such as in a task’s specification. To find an entity ID manually, open the Lattice UI, find the entity in the Entity Explorer, and copy its ID from the Entity ID column:

Shows the Entity Explorer in the Lattice Developer Console.
2

Get the entity object

Replace <ENTITY_ID> in the following example with the entity ID, then run the example to retrieve the entity from Lattice:

package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
func main() {
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")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
for {
ctx := context.Background()
entity, err := LatticeClient.Entities.GetEntity(ctx, &Lattice.GetEntityRequest{EntityID: "<ENTITY_ID>"})
if err != nil {
fmt.Printf("Error fetching entity: %v\n", err)
} else {
name := "<none>"
if n := entity.GetAliases().GetName(); n != nil {
name = *n
}
location := "<none>"
pos := entity.GetLocation().GetPosition()
if pos != nil && pos.GetLatitudeDegrees() != nil && pos.GetLongitudeDegrees() != nil {
location = fmt.Sprintf("%f, %f", *pos.GetLatitudeDegrees(), *pos.GetLongitudeDegrees())
}
fmt.Printf("Asset name | %s\n", name)
fmt.Printf("Asset location | %s\n", location)
}
time.Sleep(5 * time.Second)
}
}
3

Verify the response

If successful, you see the entity’s aliases.name and its location logged in the console:

Asset name | Demo-Sim-Asset1
Asset location | 37.7749, -122.4194

A single GetEntity call is useful to confirm that a cued target exists before you commit to an engagement. To follow the target over time, open a stream instead of calling GetEntity in a loop. A stream delivers each update as soon as Lattice receives it, without polling delays or extra load.

Stream entities

The StreamEntities API method opens a persistent connection and sends two kinds of messages: entity events and heartbeat messages. Each entity event carries an eventType that tells you what happened to the entity:

  • EVENT_TYPE_PREEXISTING: The entity already existed when the stream opened, so treat it as the initial state.
  • EVENT_TYPE_CREATED: The entity was published for the first time, or it started matching your filter, so start tracking it.
  • EVENT_TYPE_UPDATE: The entity changed, so replace your copy with the new state.
  • EVENT_TYPE_DELETED: The entity expired, was deleted, or stopped matching your filter, so remove every reference to it.
  • EVENT_TYPE_POST_EXPIRY_OVERRIDE: An override was set on the entity after it expired, so apply it only if you still keep the expired entity.

Use the following request options to control what the stream sends:

heartbeatIntervalMS
integer

How often Lattice sends a heartbeat. Heartbeats let you detect a silent connection even when no entity changes. Over gRPC, set heartbeat_period_millis.

preExistingOnly
boolean

When true, Lattice sends the entities that already exist and then closes the stream. Defaults to false, which keeps the stream open for new events.

componentsToInclude
string[]

The components to populate in each event, in snake_case, such as location_uncertainty. Lattice omits every other component. Leave empty to receive all components.

filter
Statement

A filter expression that limits the stream to matching entities. For more information, see Monitor a target track.

To stream entities from Lattice, do the following:

1

Stream all components

To stream every entity in your environment with all of its components, use the default options:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Create the entity stream.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
PreExistingOnly: Lattice.Bool(false),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
for {
select {
case <-ctx.Done():
log.Printf("Context canceled: %v", ctx.Err())
return
default:
// Continue processing
}
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Printf("Error receiving message: %v", err)
continue
}
// Process the message based on its type
switch message.Event {
case "heartbeat":
timestamp := *message.Heartbeat.Timestamp
log.Printf("Heartbeat: %s", timestamp)
case "entity":
log.Printf("Entity: %s", *message.Entity.Entity.EntityID)
default:
log.Printf("Unknown event type: %s", message.Event)
}
}
}

If successful, you get a stream of entities as they change in Lattice:

Entity: Demo-Sim-Asset2
Entity: adsbEntity
Entity: esim.adsb.aus-4005
2

Stream specific components

To reduce bandwidth, list the components you need in componentsToInclude, such as aliases and location:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Create the entity stream.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
PreExistingOnly: Lattice.Bool(false),
// Define a list of components to control which entities are fetched.
// If set, Lattice streams only entities with the components you provide.
ComponentsToInclude: []string{"aliases", "location_uncertainty"},
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
for {
select {
case <-ctx.Done():
log.Printf("Context canceled: %v", ctx.Err())
return
default:
// Continue processing
}
message, err := stream.Recv()
// Handle stream completion
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Printf("Error receiving message: %v", err)
continue
}
// Process the event based whether it is a heartbeat or entity event.
switch message.Event {
case "heartbeat":
timestamp := *message.Heartbeat.Timestamp
log.Printf("Heartbeat: %s", timestamp)
case "entity":
log.Printf("Entity: %s", *message.Entity.Entity.Aliases.Name)
default:
log.Printf("Unknown event type: %s", message.Event)
}
}
}

List component names in snake_case, such as location_uncertainty, even when you call the StreamEntities REST API directly with curl or a similar tool. Lattice ignores camelCase names, such as locationUncertainty, without returning an error.

componentsToInclude doesn’t filter entities. Lattice still streams every matching entity, with only the listed components populated. Tracks can report their position in either location or kinematics, so requesting only location streams tracks that use kinematics with no position.

Monitor a target track

An interceptor that’s engaging a target needs every update for that one track, and nothing else. Instead of streaming every entity and discarding most of them, send a filter with the stream request so Lattice sends only the target. Lattice evaluates the filter continuously: when the target stops matching, such as when it expires, you receive an EVENT_TYPE_DELETED event.

A filter is a tree of statements. The simplest statement is a single predicate that compares a field to a value. Field paths use snake_case and start at the entity, without an entity. prefix:

{
"predicate": {
"fieldPath": "entity_id",
"value": { "stringType": { "value": "<ENTITY_ID>" } },
"comparator": "COMPARATOR_EQUALITY"
}
}

To monitor a target track, do the following:

1

Build the filter

Build a predicate that matches the target’s entity ID:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"sync/atomic"
"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"
)
const (
// Replace with the entity ID of the track you want to monitor.
targetEntityID = "<ENTITY_ID>"
// Request a heartbeat every 5 seconds so silence is detectable.
heartbeatInterval = 5 * time.Second
// Warn if nothing arrives within three heartbeat intervals.
staleAfter = 3 * heartbeatInterval
)
// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
return &Lattice.Statement{
Predicate: &Lattice.Predicate{
FieldPath: Lattice.String("entity_id"),
Value: &Lattice.Value{
StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
},
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
}
}
// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
lat, lon, hae float64
velocityENU *[3]float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
if v := geodetic.VelocityEnuMPerS; v != nil {
pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
if v := loc.VelocityEnu; v != nil {
pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Stream only the target. Omit ComponentsToInclude to receive all components,
// because listing components drops the others, which can include the position.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: targetFilter(targetEntityID),
HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Watchdog: warn when neither entity updates nor heartbeats arrive.
var lastMessage atomic.Int64
lastMessage.Store(time.Now().UnixNano())
go func() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
silence := time.Since(time.Unix(0, lastMessage.Load()))
if silence > staleAfter {
log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
silence.Seconds(), heartbeatInterval.Seconds())
}
}
}
}()
log.Printf("Monitoring target %s", targetEntityID)
var lastSourceTime time.Time
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
lastMessage.Store(time.Now().UnixNano())
switch message.Event {
case "heartbeat":
log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
case "entity":
event := message.Entity
eventType := deref(event.EventType)
switch eventType {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
entity := event.Entity
pos := extractPosition(entity)
if pos == nil {
continue
}
// Ignore updates that are not newer than the last one seen.
sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
if sourceTime.IsZero() {
sourceTime = deref(event.Time)
}
if !sourceTime.After(lastSourceTime) {
continue
}
lastSourceTime = sourceTime
line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
if v := pos.velocityENU; v != nil {
line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
}
log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The target expired, was deleted, or stopped matching the filter.
// A real interceptor would abort the engagement or request a new cue.
log.Printf("Target lost: %s", targetEntityID)
return
}
}
}
}

To monitor several targets on one stream, match a set of IDs with the COMPARATOR_IN comparator and a listType value:

filter.json
{
"predicate": {
"fieldPath": "entity_id",
"value": {
"listType": {
"values": [
{ "stringType": { "value": "<TARGET_1_ID>" } },
{ "stringType": { "value": "<TARGET_2_ID>" } }
]
}
},
"comparator": "COMPARATOR_IN"
}
}
2

Read the target's position

Tracks report their position in one of two components. kinematics is the preferred component for tracks, and location is the general-purpose alternative. Read kinematics when it’s present, and fall back to location:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"sync/atomic"
"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"
)
const (
// Replace with the entity ID of the track you want to monitor.
targetEntityID = "<ENTITY_ID>"
// Request a heartbeat every 5 seconds so silence is detectable.
heartbeatInterval = 5 * time.Second
// Warn if nothing arrives within three heartbeat intervals.
staleAfter = 3 * heartbeatInterval
)
// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
return &Lattice.Statement{
Predicate: &Lattice.Predicate{
FieldPath: Lattice.String("entity_id"),
Value: &Lattice.Value{
StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
},
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
}
}
// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
lat, lon, hae float64
velocityENU *[3]float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
if v := geodetic.VelocityEnuMPerS; v != nil {
pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
if v := loc.VelocityEnu; v != nil {
pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Stream only the target. Omit ComponentsToInclude to receive all components,
// because listing components drops the others, which can include the position.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: targetFilter(targetEntityID),
HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Watchdog: warn when neither entity updates nor heartbeats arrive.
var lastMessage atomic.Int64
lastMessage.Store(time.Now().UnixNano())
go func() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
silence := time.Since(time.Unix(0, lastMessage.Load()))
if silence > staleAfter {
log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
silence.Seconds(), heartbeatInterval.Seconds())
}
}
}
}()
log.Printf("Monitoring target %s", targetEntityID)
var lastSourceTime time.Time
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
lastMessage.Store(time.Now().UnixNano())
switch message.Event {
case "heartbeat":
log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
case "entity":
event := message.Entity
eventType := deref(event.EventType)
switch eventType {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
entity := event.Entity
pos := extractPosition(entity)
if pos == nil {
continue
}
// Ignore updates that are not newer than the last one seen.
sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
if sourceTime.IsZero() {
sourceTime = deref(event.Time)
}
if !sourceTime.After(lastSourceTime) {
continue
}
lastSourceTime = sourceTime
line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
if v := pos.velocityENU; v != nil {
line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
}
log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The target expired, was deleted, or stopped matching the filter.
// A real interceptor would abort the engagement or request a new cue.
log.Printf("Target lost: %s", targetEntityID)
return
}
}
}
}
3

Stream and handle events

Open the stream with the filter and a heartbeat interval, then handle each event type:

  • On EVENT_TYPE_PREEXISTING, EVENT_TYPE_CREATED, or EVENT_TYPE_UPDATE, read the newest position. Skip any update whose provenance.source_update_time isn’t newer than the last one you used, so the effector never steers toward stale data.
  • On EVENT_TYPE_DELETED, treat the target as lost. A real interceptor aborts the engagement or requests a new cue.
  • On every message, including heartbeats, record the time. If nothing arrives for several heartbeat intervals, warn that the connection might be stale.

Request all components, rather than listing them in componentsToInclude, so the target’s position arrives whichever component carries it, location or kinematics:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"sync/atomic"
"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"
)
const (
// Replace with the entity ID of the track you want to monitor.
targetEntityID = "<ENTITY_ID>"
// Request a heartbeat every 5 seconds so silence is detectable.
heartbeatInterval = 5 * time.Second
// Warn if nothing arrives within three heartbeat intervals.
staleAfter = 3 * heartbeatInterval
)
// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
return &Lattice.Statement{
Predicate: &Lattice.Predicate{
FieldPath: Lattice.String("entity_id"),
Value: &Lattice.Value{
StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
},
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
}
}
// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
lat, lon, hae float64
velocityENU *[3]float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
if v := geodetic.VelocityEnuMPerS; v != nil {
pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
if v := loc.VelocityEnu; v != nil {
pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Stream only the target. Omit ComponentsToInclude to receive all components,
// because listing components drops the others, which can include the position.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: targetFilter(targetEntityID),
HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Watchdog: warn when neither entity updates nor heartbeats arrive.
var lastMessage atomic.Int64
lastMessage.Store(time.Now().UnixNano())
go func() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
silence := time.Since(time.Unix(0, lastMessage.Load()))
if silence > staleAfter {
log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
silence.Seconds(), heartbeatInterval.Seconds())
}
}
}
}()
log.Printf("Monitoring target %s", targetEntityID)
var lastSourceTime time.Time
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
lastMessage.Store(time.Now().UnixNano())
switch message.Event {
case "heartbeat":
log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
case "entity":
event := message.Entity
eventType := deref(event.EventType)
switch eventType {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
entity := event.Entity
pos := extractPosition(entity)
if pos == nil {
continue
}
// Ignore updates that are not newer than the last one seen.
sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
if sourceTime.IsZero() {
sourceTime = deref(event.Time)
}
if !sourceTime.After(lastSourceTime) {
continue
}
lastSourceTime = sourceTime
line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
if v := pos.velocityENU; v != nil {
line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
}
log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The target expired, was deleted, or stopped matching the filter.
// A real interceptor would abort the engagement or request a new cue.
log.Printf("Target lost: %s", targetEntityID)
return
}
}
}
}

If successful, you see each new position and how old the measurement is:

Monitoring target 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21
EVENT_TYPE_PREEXISTING lat=34.045000 lon=-117.990000 hae=512.1m vel_enu=(4.8,-31.6,-11.7)m/s age=0.4s
EVENT_TYPE_UPDATE lat=34.044715 lon=-117.989957 hae=500.4m vel_enu=(4.8,-31.6,-11.7)m/s age=0.3s
Target lost: 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21

Over gRPC, StreamEntityComponents also accepts a rate_limit that sets the minimum time between updates for each entity, with a floor of 500 milliseconds. A rate limit only reduces the update rate, so leave it unset when an effector needs every update for its target.

Watch for threat tracks

Before it’s cued, an effector can watch for the tracks it might be asked to engage. Combine predicates with an and statement to stream only hostile or suspicious air tracks:

ontology.template
EnumType

Equal to TEMPLATE_TRACK, so the stream excludes assets and geo-entities.

mil_view.environment
EnumType

Equal to ENVIRONMENT_AIR, so the stream excludes surface and subsurface tracks.

mil_view.disposition
EnumType

In the set DISPOSITION_HOSTILE and DISPOSITION_SUSPICIOUS, using the COMPARATOR_IN comparator.

Filters compare enum fields by their integer values, as defined in the Lattice protobuf definitions. This filter uses 1 for TEMPLATE_TRACK and ENVIRONMENT_AIR, 2 for DISPOSITION_HOSTILE, and 3 for DISPOSITION_SUSPICIOUS:

{
"and": {
"predicateSet": {
"predicates": [
{
"fieldPath": "ontology.template",
"value": { "enumType": { "value": 1 } },
"comparator": "COMPARATOR_EQUALITY"
},
{
"fieldPath": "mil_view.environment",
"value": { "enumType": { "value": 1 } },
"comparator": "COMPARATOR_EQUALITY"
},
{
"fieldPath": "mil_view.disposition",
"value": {
"listType": {
"values": [
{ "enumType": { "value": 2 } },
{ "enumType": { "value": 3 } }
]
}
},
"comparator": "COMPARATOR_IN"
}
]
}
}
}

To watch for threat tracks, do the following:

1

Build the filter

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
// enumValue builds an enum filter value. Filters take the integer value of
// an ontology enum, for example DISPOSITION_HOSTILE is 2.
func enumValue(v int) *Lattice.Value {
return &Lattice.Value{EnumType: &Lattice.EnumType{Value: Lattice.Int(v)}}
}
// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *Lattice.Statement {
return &Lattice.Statement{
And: &Lattice.AndOperation{
PredicateSet: &Lattice.PredicateSet{
Predicates: []*Lattice.Predicate{
{
FieldPath: Lattice.String("ontology.template"),
Value: enumValue(1), // TEMPLATE_TRACK
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
{
FieldPath: Lattice.String("mil_view.environment"),
Value: enumValue(1), // ENVIRONMENT_AIR
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
{
FieldPath: Lattice.String("mil_view.disposition"),
Value: &Lattice.Value{ListType: &Lattice.ListType{
Values: []*Lattice.Value{
enumValue(2), // DISPOSITION_HOSTILE
enumValue(3), // DISPOSITION_SUSPICIOUS
},
}},
Comparator: Lattice.PredicateComparatorComparatorIn.Ptr(),
},
},
},
},
}
}
// trackPosition is the newest position of a track.
type trackPosition struct {
lat, lon, hae float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Stream every entity that matches the threat filter, with all components.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: threatFilter(),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Candidate table: entity ID to last known position.
candidates := map[string]trackPosition{}
log.Println("Watching for threat tracks...")
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
if message.Event != "entity" {
continue
}
event := message.Entity
entity := event.Entity
if entity == nil {
continue
}
id := deref(entity.EntityID)
switch deref(event.EventType) {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
pos := extractPosition(entity)
if pos == nil {
continue
}
action := "UPDATED"
if _, known := candidates[id]; !known {
action = "ADDED"
}
candidates[id] = *pos
log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
action, id, pos.lat, pos.lon, pos.hae, len(candidates))
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The entity expired, was deleted, or no longer matches the filter.
if _, known := candidates[id]; known {
delete(candidates, id)
log.Printf("REMOVED %s candidates=%d", id, len(candidates))
}
}
}
}
2

Maintain a candidate list

Keep a table of candidate tracks keyed by entity ID. Add or update a candidate on EVENT_TYPE_PREEXISTING, EVENT_TYPE_CREATED, and EVENT_TYPE_UPDATE, and remove it on EVENT_TYPE_DELETED. Because Lattice evaluates the filter continuously, a track that an operator reclassifies as friendly leaves the stream with an EVENT_TYPE_DELETED event:

package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
// enumValue builds an enum filter value. Filters take the integer value of
// an ontology enum, for example DISPOSITION_HOSTILE is 2.
func enumValue(v int) *Lattice.Value {
return &Lattice.Value{EnumType: &Lattice.EnumType{Value: Lattice.Int(v)}}
}
// threatFilter matches air tracks that are hostile or suspicious. The filter is
// evaluated continuously: an entity that starts matching arrives as CREATED, and
// one that stops matching arrives as DELETED.
func threatFilter() *Lattice.Statement {
return &Lattice.Statement{
And: &Lattice.AndOperation{
PredicateSet: &Lattice.PredicateSet{
Predicates: []*Lattice.Predicate{
{
FieldPath: Lattice.String("ontology.template"),
Value: enumValue(1), // TEMPLATE_TRACK
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
{
FieldPath: Lattice.String("mil_view.environment"),
Value: enumValue(1), // ENVIRONMENT_AIR
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
{
FieldPath: Lattice.String("mil_view.disposition"),
Value: &Lattice.Value{ListType: &Lattice.ListType{
Values: []*Lattice.Value{
enumValue(2), // DISPOSITION_HOSTILE
enumValue(3), // DISPOSITION_SUSPICIOUS
},
}},
Comparator: Lattice.PredicateComparatorComparatorIn.Ptr(),
},
},
},
},
}
}
// trackPosition is the newest position of a track.
type trackPosition struct {
lat, lon, hae float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Stream every entity that matches the threat filter, with all components.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: threatFilter(),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Candidate table: entity ID to last known position.
candidates := map[string]trackPosition{}
log.Println("Watching for threat tracks...")
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
if message.Event != "entity" {
continue
}
event := message.Entity
entity := event.Entity
if entity == nil {
continue
}
id := deref(entity.EntityID)
switch deref(event.EventType) {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
pos := extractPosition(entity)
if pos == nil {
continue
}
action := "UPDATED"
if _, known := candidates[id]; !known {
action = "ADDED"
}
candidates[id] = *pos
log.Printf("%s %s lat=%.6f lon=%.6f hae=%.1fm candidates=%d",
action, id, pos.lat, pos.lon, pos.hae, len(candidates))
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The entity expired, was deleted, or no longer matches the filter.
if _, known := candidates[id]; known {
delete(candidates, id)
log.Printf("REMOVED %s candidates=%d", id, len(candidates))
}
}
}
}

If successful, you see the candidate list change as threat tracks appear and disappear:

ADDED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 lat=34.045000 lon=-117.990000 hae=512.1m candidates=1
UPDATED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 lat=34.044715 lon=-117.989957 hae=500.4m candidates=1
REMOVED 2f6a0d1c-4b7e-4c3a-9d55-1e8f0a7b9c21 candidates=0

Best practices

  • Reconnect automatically: Streams can drop on unreliable networks. Reopen the stream with backoff, and expect EVENT_TYPE_PREEXISTING events for the current state after you reconnect. For more information, see Retry connections.
  • Extrapolate between updates: Updates arrive at the rate that sensors detect the target. Between updates, project the last position forward along its velocity, using the age of the measurement.
  • Filter on the server: Send a filter instead of discarding unwanted entities in your code. Server-side filters reduce bandwidth, which matters on tactical networks.

What’s next?