Eve library

Oya Drone Platform — Integration Guides

Guide

Revision 1

On this page

Comprehensive step-by-step guides for integrating the @oya/core library with autopilot systems, simulators, swarm coordination, cinematography, AI/ML pipelines, and safety subsystems.


Table of Contents#

  1. Quick Start
  2. PX4 Integration
  3. ArduPilot Integration
  4. DJI Integration
  5. Swarm Setup
  6. Cinematography
  7. Pose Estimation
  8. Simulation
  9. Edge Deployment
  10. Safety

1. Quick Start#

Overview#

This guide walks through installing @oya/core, creating a minimal configuration, connecting to a drone, and issuing the first commands.

Prerequisites#

  • Node.js >= 18
  • pnpm (or npm/yarn)
  • A drone autopilot (PX4 / ArduPilot / DJI) or simulator (Gazebo / AirSim)

Installation#

bash
pnpm add @oya/core

Import the Library#

typescript
import {
  // Types and schemas
  FlightMode,
  DroneState,
  ConnectionStatus,
  type GPSCoordinates,
  type Telemetry,
  TelemetrySchema,

  // PX4
  PX4SITLConnection,
  PX4SITLState,
  PX4MAVLinkTransport,
  PX4OffboardController,
  PX4OffboardMode,

  // ArduPilot
  APConnectionManager,
  APConnectionType,
  APConnectionState,
  APVehicleType,

  // Mission execution
  MissionUploader,
  MissionValidator,
  WaypointSequencer,

  // Constants
  DEFAULT_CRUISE_SPEED,
  DEFAULT_RTH_ALTITUDE,
  FAA_MAX_ALTITUDE_AGL_M,
  BATTERY_LOW_PERCENT,

  // Math utilities
  haversineDistance,
  degreesToRadians,
} from '@oya/core';

Connect to Your First Drone (PX4 SITL)#

typescript
// 1. Create a SITL connection
const sitl = new PX4SITLConnection({
  host: '127.0.0.1',
  port: 14540,
  vehicleModel: 'iris',
  speedFactor: 1.0,
  headless: false,
});

// 2. Connect
const now = Date.now();
const state = sitl.connect(now);
console.log(`Connection state: ${state}`); // 'Connected'

// 3. Start the simulation
const simState = sitl.startSim(now);
console.log(`Sim state: ${simState}`); // 'SimRunning'

// 4. Set up MAVLink transport
const mavlink = new PX4MAVLinkTransport(1, 1);
console.log(`System ID: ${mavlink.getSystemId()}`);

Send Your First Commands#

typescript
// Create offboard controller for external control
const offboard = new PX4OffboardController();

// Enable offboard mode
offboard.enable(Date.now());

// Send a position setpoint (NED frame: 10m north, 0m east, -5m up)
offboard.setPosition(
  { x: 10, y: 0, z: -5 },
  0, // yaw = 0 radians (north)
  Date.now()
);

// Send a velocity setpoint (1 m/s north)
offboard.setVelocity(
  { x: 1, y: 0, z: 0 },
  0, // yaw rate = 0
  Date.now()
);

Validate Telemetry Data#

typescript
const rawTelemetry = {
  droneId: 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d',
  timestamp: new Date().toISOString(),
  position: { latitude: 47.3977, longitude: 8.5456, altitude: 450 },
  velocity: { vx: 0, vy: 0, vz: 0 },
  acceleration: { ax: 0, ay: 0, az: -9.81 },
  orientation: { roll: 0, pitch: 0, yaw: 0 },
  batteryState: {
    voltage: 22.2,
    current: 5.0,
    percentage: 85,
    temperatureCelsius: 25,
    cellCount: 6,
    timeRemainingSeconds: 1200,
    isCharging: false,
    cycleCount: 42,
  },
  gpsCoordinates: { latitude: 47.3977, longitude: 8.5456, altitude: 450 },
  signalStrength: -45,
  satellites: 14,
  flightMode: FlightMode.Position,
  droneState: DroneState.Hovering,
  connectionStatus: ConnectionStatus.Connected,
};

const result = TelemetrySchema.safeParse(rawTelemetry);
if (result.success) {
  console.log('Telemetry valid:', result.data.position);
} else {
  console.error('Validation errors:', result.error.issues);
}

Troubleshooting#

Problem Solution
Connection refused Ensure SITL is running on the configured host:port
Telemetry validation fails Check that all required fields match the Zod schema
Offboard timeout Send setpoints faster than the 500ms timeout interval

2. PX4 Integration#

Overview#

The PX4 integration layer provides a complete interface to PX4 autopilot firmware. It supports SITL simulation, MAVLink v2 communication, offboard mode control, position/velocity/attitude setpoints, parameter management, mission protocol, telemetry streaming, and EKF2 monitoring.

Prerequisites#

  • PX4 SITL installed (for simulation) or PX4-based flight controller
  • UDP connectivity on port 14540 (SITL default)
  • @oya/core installed

SITL Setup#

typescript
import { PX4SITLConnection, PX4SITLState } from '@oya/core';

// Configure the SITL connection
const sitl = new PX4SITLConnection({
  host: '127.0.0.1',
  port: 14540,
  vehicleModel: 'iris', // Options: iris, typhoon_h480, plane, standard_vtol
  speedFactor: 1.0, // 1.0 = real-time, 2.0 = 2x speed
  headless: false, // true = no GUI
});

// Connect to the SITL instance
const state = sitl.connect(Date.now());
console.log(state); // PX4SITLState.Connected

// Get the connection URI
console.log(sitl.getConnectionString()); // 'udp://127.0.0.1:14540'

// Start simulation
sitl.startSim(Date.now());
console.log(sitl.getState()); // PX4SITLState.SimRunning

// Advance simulation time (call in your main loop)
function simulationLoop() {
  sitl.updateSimTime(Date.now());
  sitl.processHeartbeat(Date.now());

  // Check aliveness (heartbeat within 5s)
  if (!sitl.isAlive(Date.now())) {
    console.warn('SITL connection lost');
  }

  console.log(`Sim time: ${sitl.getSimTimeSec()}s`);
}

// Adjust simulation speed
sitl.setSpeedFactor(2.0); // Run at 2x real-time
typescript
import { PX4MAVLinkTransport, PX4MAVLinkPriority } from '@oya/core';

// Create transport with system/component IDs
const transport = new PX4MAVLinkTransport(1, 1);

// Get the next sequence number for message framing
const seq = transport.nextSequence(); // 0, 1, 2, ... wraps at 255

// Compute CRC for a MAVLink v2 message payload
const payload = [0x01, 0x02, 0x03];
const crc = transport.computeCRC(payload, 33); // msgId = 33 (GLOBAL_POSITION_INT)

// Record sent/received messages for statistics
transport.recordSent(42);
transport.recordReceived(1, seq, 42, true);

// Monitor transport health
const stats = transport.getStats();
console.log(`Messages sent: ${stats.messagesSent}`);
console.log(`Messages received: ${stats.messagesReceived}`);
console.log(`CRC errors: ${stats.crcErrors}`);
console.log(`Lost messages: ${stats.lostMessages}`);
console.log(`Loss rate: ${(transport.getLossRate() * 100).toFixed(1)}%`);

Offboard Mode Control#

typescript
import { PX4OffboardController, PX4OffboardMode } from '@oya/core';

const offboard = new PX4OffboardController(500); // 500ms timeout

// Enable offboard mode
offboard.enable(Date.now());

// Position setpoint (NED frame)
offboard.setPosition(
  { x: 10, y: 5, z: -20 }, // 10m N, 5m E, 20m above origin
  Math.PI / 4, // yaw = 45 degrees
  Date.now()
);

// Velocity setpoint
offboard.setVelocity(
  { x: 2, y: 0, z: -0.5 }, // 2 m/s north, 0.5 m/s ascend
  0.1, // yaw rate = 0.1 rad/s
  Date.now()
);

// Attitude setpoint with quaternion
import { quatIdentity } from '@oya/core';
offboard.setAttitude(
  quatIdentity(),
  { x: 0, y: 0, z: -0.5 }, // thrust body (50% downward)
  Date.now()
);

// Check for timeout (must send setpoints faster than 500ms)
if (offboard.isTimedOut(Date.now())) {
  console.warn('Offboard timeout - vehicle will switch to failsafe');
}

// Disable offboard
offboard.disable();

Mission Protocol#

typescript
import {
  MissionUploader,
  MissionValidator,
  WaypointSequencer,
  type Mission,
  type Waypoint,
  WaypointAction,
  AirspaceClass,
} from '@oya/core';

// Define waypoints
const waypoints: Waypoint[] = [
  {
    id: '11111111-1111-4111-8111-111111111111',
    position: { latitude: 47.3977, longitude: 8.5456, altitude: 50 },
    speed: 5.0,
    heading: 0,
    holdTimeSeconds: 0,
    actions: [],
    radius: 2.0,
  },
  {
    id: '22222222-2222-4222-8222-222222222222',
    position: { latitude: 47.3987, longitude: 8.5466, altitude: 50 },
    speed: 5.0,
    heading: 45,
    holdTimeSeconds: 5,
    actions: [{ action: WaypointAction.TakePhoto, params: {} }],
    radius: 2.0,
  },
];

// Build mission
const mission: Mission = {
  id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',
  name: 'Survey Flight Alpha',
  waypoints,
  constraints: {
    maxAltitude: 120,
    minAltitude: 10,
    maxSpeed: 15,
    minBatteryPercent: 25,
    maxWindSpeed: 10,
    allowedAirspace: [AirspaceClass.G],
  },
  metadata: {
    createdBy: 'pilot-001',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    description: 'Test survey mission',
    tags: ['survey', 'test'],
  },
  estimatedDuration: 300,
  totalDistance: 150,
};

// Upload mission
const uploader = new MissionUploader();
const uploadStatus = uploader.upload(mission);
console.log(`Upload accepted: ${uploadStatus.accepted}`);
console.log(`Checksum: ${uploadStatus.checksum}`);
console.log(`Waypoints: ${uploadStatus.waypointCount}`);

// Validate mission
const validator = new MissionValidator();
const validation = validator.validate(mission);
console.log(`Valid: ${validation.valid}`);
for (const issue of validation.issues) {
  console.log(`  [${issue.severity}] ${issue.message}`);
}

// Verify checksum integrity
const checksumValid = uploader.verifyChecksum(mission);
console.log(`Checksum valid: ${checksumValid}`);

Troubleshooting#

Problem Solution
SITL not connecting Verify PX4 SITL is running: make px4_sitl gazebo
Offboard rejected Send setpoints before enabling offboard mode
Mission upload rejected Check validation errors in uploadStatus.errors
Heartbeat timeout Ensure heartbeats are processed within 5000ms
CRC errors increasing Check for packet corruption; verify transport layer

3. ArduPilot Integration#

Overview#

The ArduPilot integration provides connection management (Serial/UDP/TCP/SITL), MAVLink dialect handling, arming sequences with pre-arm checks, flight mode management, guided mode navigation, auto missions, rally points, geofence polygons, parameter management, and terrain following.

Prerequisites#

  • ArduPilot-based flight controller or ArduPilot SITL
  • Network connectivity (UDP 14550 default)
  • @oya/core installed

Connection Types#

typescript
import {
  APConnectionManager,
  APConnectionType,
  APConnectionState,
  APVehicleType,
} from '@oya/core';

// UDP connection (most common)
const udpConn = new APConnectionManager({
  connectionType: APConnectionType.UDP,
  address: '127.0.0.1',
  port: 14550,
  baudRate: 57600,
  systemId: 255,
  componentId: 190,
});

// Serial connection
const serialConn = new APConnectionManager({
  connectionType: APConnectionType.Serial,
  address: '/dev/ttyACM0',
  port: 0,
  baudRate: 115200,
  systemId: 255,
  componentId: 190,
});

// TCP connection
const tcpConn = new APConnectionManager({
  connectionType: APConnectionType.TCP,
  address: '192.168.1.100',
  port: 5760,
  baudRate: 57600,
  systemId: 255,
  componentId: 190,
});

// SITL local connection
const sitlConn = new APConnectionManager({
  connectionType: APConnectionType.SITLLocal,
  address: '127.0.0.1',
  port: 5762,
  baudRate: 57600,
  systemId: 255,
  componentId: 190,
});

Connection Lifecycle#

typescript
// Connect
const state = udpConn.connect(Date.now());
console.log(state); // APConnectionState.Connected

// Get connection string
console.log(udpConn.getConnectionString()); // 'udp://127.0.0.1:14550'

// Process heartbeats (call when heartbeat message received)
udpConn.processHeartbeat(Date.now(), APVehicleType.Copter);
console.log(udpConn.getState()); // APConnectionState.Heartbeating
console.log(udpConn.getVehicleType()); // APVehicleType.Copter

// Monitor connection health (call periodically)
const healthState = udpConn.checkHealth(Date.now());
if (healthState === APConnectionState.Lost) {
  console.warn('Connection lost - attempting reconnect');
}

// Check connection quality
const quality = udpConn.getConnectionQuality(); // 0.0 - 1.0
console.log(`Connection quality: ${(quality * 100).toFixed(0)}%`);

// Get firmware info
udpConn.setFirmwareVersion('4.5.1');
udpConn.setBoardType('CubeOrange');
console.log(`Firmware: ${udpConn.getFirmwareVersion()}`);

// Disconnect
udpConn.disconnect();
typescript
import {
  APMAVLinkDialectHandler,
  APMAVLinkDialect,
  type APDialectMessage,
} from '@oya/core';

const dialect = new APMAVLinkDialectHandler(APMAVLinkDialect.ArduPilotMega);

// Register a custom message definition
const customMsg: APDialectMessage = {
  msgId: 11000,
  name: 'RANGEFINDER',
  dialect: APMAVLinkDialect.ArduPilotMega,
  fields: [
    { name: 'distance', type: 'float', units: 'm' },
    { name: 'voltage', type: 'float', units: 'V' },
  ],
  crcExtra: 0,
};
dialect.registerMessage(customMsg);

// Look up message definitions
const def = dialect.getMessageDef(11000);
console.log(def?.name); // 'RANGEFINDER'

// Check if message is known
console.log(dialect.isKnownMessage(11000)); // true

// Compute CRC extra for message integrity
const crcExtra = dialect.computeCRCExtra('RANGEFINDER', [
  { name: 'distance', type: 'float' },
  { name: 'voltage', type: 'float' },
]);

Arming with Pre-Arm Checks#

typescript
import { APArmingController, APArmState } from '@oya/core';

const armController = new APArmingController();

// Update pre-arm check results
armController.updateChecks({
  barometer: true,
  compass: true,
  gps: true,
  ins: true,
  parameters: true,
  rcChannels: true,
  boardVoltage: true,
  battery: true,
  logging: true,
  fence: true,
  system: true,
});

// Attempt to arm
const armState = armController.arm(Date.now());
if (armState === APArmState.Armed) {
  console.log('Vehicle armed successfully');
} else if (armState === APArmState.ArmingRejected) {
  console.error('Arming rejected - check pre-arm status');
}

// Disarm
armController.disarm();

Rally Points#

typescript
import { RallyPointSystem, type RallyPoint } from '@oya/core';

const rallySystem = new RallyPointSystem();

// Add rally points (alternate safe landing locations)
const point: RallyPoint = {
  id: 'rally-001',
  position: { latitude: 47.398, longitude: 8.546, altitude: 30 },
  radius: 50,
  isHome: false,
};
rallySystem.addPoint(point);

// Find nearest rally point to a position
const nearest = rallySystem.findNearest({
  latitude: 47.3985,
  longitude: 8.547,
  altitude: 100,
});

Troubleshooting#

Problem Solution
Arming rejected Check all pre-arm checks; ensure GPS lock
Heartbeat timeout Verify baud rate and connection type match autopilot
Unknown message IDs Register dialect messages before parsing
Connection quality low Check antenna and reduce distance to GCS

4. DJI Integration#

Overview#

The DJI integration provides an SDK bridge layer for DJI drones using the Mobile SDK V5 protocol. It covers app key management, aircraft connection, flight controller access, gimbal and camera control, video feed, telemetry, waypoint missions, virtual stick, live streaming, obstacle avoidance, battery management, RTK service, and fleet management.

Prerequisites#

  • DJI MSDK V5 app key (24-character hex string)
  • DJI-compatible drone (Mavic, Phantom, Matrice series)
  • @oya/core installed

App Key Activation#

typescript
import {
  DJIAppKeyManager,
  DJIActivationState,
  type DJIAppKeyConfig,
} from '@oya/core';

const appKeyConfig: DJIAppKeyConfig = {
  appKey: 'a1b2c3d4e5f6a1b2c3d4e5f6', // 24-char hex
  bundleId: 'com.example.oya-drone',
  bridgeMode: false,
  bridgeIp: '192.168.1.100',
  licenseExpiry: Date.now() + 365 * 24 * 60 * 60 * 1000, // 1 year
};

const keyManager = new DJIAppKeyManager(appKeyConfig);

// Validate key format
const formatValid = keyManager.validateKeyFormat();
console.log(`Key format valid: ${formatValid}`);

// Activate (authenticate with DJI servers)
const activationState = keyManager.activate(Date.now());
console.log(`Activation: ${activationState}`);

// Check if license is still valid
const isValid = keyManager.isLicenseValid(Date.now());
console.log(`License valid: ${isValid}`);

Aircraft Connection#

typescript
import { DJIAircraftConnection, DJIAircraftConnectionState } from '@oya/core';

const aircraft = new DJIAircraftConnection();

// Connect to aircraft
aircraft.connect(Date.now());
console.log(aircraft.getState()); // DJIAircraftConnectionState.Connected

// Get aircraft information
const info = aircraft.getAircraftInfo();
console.log(`Model: ${info.model}`);
console.log(`Serial: ${info.serialNumber}`);
console.log(`Firmware: ${info.firmwareVersion}`);

Virtual Stick Control#

typescript
import { DJIVirtualStickController } from '@oya/core';

const stick = new DJIVirtualStickController();

// Enable virtual stick mode
stick.enable();

// Send control inputs (normalized -1 to 1)
stick.setInput({
  pitch: 0.5, // forward
  roll: 0, // no lateral
  yaw: 0, // no rotation
  throttle: 0.2, // slight ascent
});

Waypoint Mission#

typescript
import { DJIWaypointMission, type DJIWaypoint } from '@oya/core';

const djiMission = new DJIWaypointMission();

// Add waypoints
djiMission.addWaypoint({
  latitude: 47.3977,
  longitude: 8.5456,
  altitude: 50,
  speed: 5,
  heading: 0,
  actions: [],
});

// Upload and start
djiMission.upload();
djiMission.start();

Troubleshooting#

Problem Solution
Activation failed Verify app key is 24-char hex and not expired
Connection timeout Ensure drone is powered and RC is connected
Virtual stick rejected Arm aircraft and switch to P-mode first
Mission upload failed Check waypoint count is within DJI limits (65535)

5. Swarm Setup#

Overview#

The swarm coordination system enables multi-drone operations with various coordination architectures: leader-follower, virtual leader, decentralized, consensus-based, and behavior-based. It includes task assignment via auctions and Contract Net Protocol, synchronized takeoff/landing, formation control, heartbeat monitoring, emergency stop, and telemetry aggregation.

Prerequisites#

  • Multiple drones (or simulated drones) with network connectivity
  • @oya/core installed
  • Understanding of swarm roles: leader, follower, scout, relay, standby

Create a Swarm#

typescript
import {
  SwarmManager,
  DroneRegistrationProtocol,
  SwarmHeartbeatMonitor,
  SwarmHealthAggregator,
  SwarmStateMachine,
  type SwarmDrone,
  type DroneCapability,
} from '@oya/core';

// 1. Initialize swarm manager
const swarm = new SwarmManager();

// 2. Set up registration protocol
const registration = new DroneRegistrationProtocol();

// 3. Register drones
const drone1: SwarmDrone = {
  id: 'drone-alpha',
  role: 'leader',
  position: { x: 0, y: 0, z: -10 },
  velocity: { x: 0, y: 0, z: 0 },
  battery: 0.95,
  airborne: false,
  gpsQuality: 'excellent',
  connectionQuality: 'strong',
  capabilities: {
    hasCamera: true,
    hasLidar: false,
    maxSpeed: 15,
    maxFlightTime: 1800,
    payloadCapacity: 0.5,
  },
  priority: 'high',
  active: true,
  lastHeartbeat: Date.now(),
};

const drone2: SwarmDrone = {
  id: 'drone-bravo',
  role: 'follower',
  position: { x: 5, y: 0, z: -10 },
  velocity: { x: 0, y: 0, z: 0 },
  battery: 0.9,
  airborne: false,
  gpsQuality: 'good',
  connectionQuality: 'strong',
  capabilities: {
    hasCamera: true,
    hasLidar: true,
    maxSpeed: 12,
    maxFlightTime: 1500,
    payloadCapacity: 1.0,
  },
  priority: 'medium',
  active: true,
  lastHeartbeat: Date.now(),
};

// Register drones with the swarm
registration.register(drone1);
registration.register(drone2);

Heartbeat Monitoring#

typescript
import { SwarmHeartbeatMonitor, type HeartbeatMessage } from '@oya/core';

const heartbeat = new SwarmHeartbeatMonitor();

// Process incoming heartbeat messages
const hbMessage: HeartbeatMessage = {
  droneId: 'drone-alpha',
  timestamp: Date.now(),
  battery: 0.93,
  position: { x: 0, y: 0, z: -10 },
  velocity: { x: 0, y: 0, z: 0 },
  gpsQuality: 'excellent',
};

heartbeat.processHeartbeat(hbMessage);

// Check for lost drones (no heartbeat within timeout)
const lostDrones = heartbeat.getLostDrones(Date.now());
if (lostDrones.length > 0) {
  console.warn(`Lost drones: ${lostDrones.join(', ')}`);
}

Formation Control#

typescript
import {
  LineFormation,
  VFormation,
  CircleFormation,
  GridFormation,
  FormationTransitioner,
  PositionAssignmentOptimizer,
  type FormationShape,
} from '@oya/core';

// Create formation shapes
const lineForm = new LineFormation();
const veeForm = new VFormation();
const circleForm = new CircleFormation();
const gridForm = new GridFormation();

// Generate positions for 5 drones in a V-formation
const droneCount = 5;
const spacing = 10; // 10 meters between drones
const vPositions = veeForm.generatePositions(droneCount, spacing);

// Optimize assignment (Hungarian algorithm) to minimize total distance
const optimizer = new PositionAssignmentOptimizer();
const currentPositions = [
  { x: 0, y: 0, z: -10 },
  { x: 5, y: 5, z: -10 },
  { x: -5, y: 5, z: -10 },
  { x: 10, y: 0, z: -10 },
  { x: -10, y: 0, z: -10 },
];

// Smooth transition between formations
const transitioner = new FormationTransitioner();
// Transition from line to V-formation over 10 seconds

Task Allocation#

typescript
import {
  AuctionTaskAssigner,
  ContractNetProtocol,
  type SwarmTask,
  type AuctionBid,
} from '@oya/core';

// Create a task
const searchTask: SwarmTask = {
  id: 'task-001',
  targetPosition: { x: 100, y: 200, z: -30 },
  priority: 'high',
  estimatedCost: 50,
  assigned: false,
  completed: false,
  description: 'Search sector 7',
};

// Auction-based assignment
const auction = new AuctionTaskAssigner();
auction.announceTask(searchTask);

// Drones submit bids
const bid: AuctionBid = {
  droneId: 'drone-alpha',
  taskId: 'task-001',
  cost: 30,
  estimatedTime: 120,
};
auction.submitBid(bid);

// Award task to lowest bidder
auction.resolveAuction('task-001');

Synchronized Takeoff/Landing#

typescript
import { SynchronizedTakeoff, SynchronizedLanding } from '@oya/core';

const takeoff = new SynchronizedTakeoff();
const landing = new SynchronizedLanding();

// Initialize synchronized takeoff for all registered drones
takeoff.initiate(['drone-alpha', 'drone-bravo'], {
  targetAltitude: 20, // meters
  staggerDelay: 2000, // 2 seconds between each drone
});

// Execute synchronized landing
landing.initiate(['drone-alpha', 'drone-bravo'], {
  landingOrder: 'priority', // land by priority level
});

Troubleshooting#

Problem Solution
Drones not registering Verify drone IDs are unique strings
Heartbeat timeout Check network latency; increase heartbeat interval
Formation broken Verify all drones have GPS lock and are airborne
Task not assigned Ensure at least one drone has required capabilities

6. Cinematography#

Overview#

The cinematography system provides professional-grade aerial filming capabilities including shot planning with composition rules, subject tracking, trajectory generation, gimbal control, multi-camera coordination, and video streaming.

Prerequisites#

  • Drone with camera and stabilized gimbal
  • @oya/core installed
  • Understanding of cinematography concepts (shot types, composition rules)

Shot Types and Trajectories#

typescript
import {
  OrbitShotTrajectory,
  RevealShotTrajectory,
  DollyZoomTrajectory,
  CraneShotTrajectory,
  DronieShotTrajectory,
  HelixTrajectory,
  BoomerangShotTrajectory,
  FlybyShotTrajectory,
  type TrajectoryWaypoint,
  type SampledTrajectory,
} from '@oya/core';

// Orbit shot around a point of interest
const orbit = new OrbitShotTrajectory();
const orbitTrajectory: SampledTrajectory = orbit.generate({
  center: { x: 0, y: 0, z: 0 }, // POI position
  radius: 30, // 30m radius
  altitude: 20, // 20m above POI
  angularSpeed: 0.1, // rad/s
  totalAngle: 2 * Math.PI, // full 360-degree orbit
  samples: 100, // trajectory resolution
});
console.log(`Orbit duration: ${orbitTrajectory.totalTime}s`);
console.log(`Orbit length: ${orbitTrajectory.totalLength}m`);

// Reveal shot — rise up and pull back to reveal a scene
const reveal = new RevealShotTrajectory();
const revealTrajectory = reveal.generate({
  startPosition: { x: 10, y: 0, z: -5 },
  endPosition: { x: -30, y: 0, z: -40 },
  lookAt: { x: 0, y: 0, z: 0 },
  duration: 12,
  samples: 60,
});

// Dolly zoom (Hitchcock effect)
const dollyZoom = new DollyZoomTrajectory();
const dzTrajectory = dollyZoom.generate({
  startPosition: { x: 20, y: 0, z: -10 },
  endPosition: { x: 50, y: 0, z: -10 },
  lookAt: { x: 0, y: 0, z: -10 },
  startFocalLength: 24,
  endFocalLength: 70,
  duration: 8,
  samples: 48,
});

// Dronie — selfie drone shot (fly backward and up)
const dronie = new DronieShotTrajectory();
const dronieTrajectory = dronie.generate({
  startPosition: { x: 2, y: 0, z: -2 },
  endPosition: { x: -20, y: 0, z: -25 },
  lookAt: { x: 0, y: 0, z: 0 },
  duration: 6,
  samples: 36,
});

Camera and Gimbal Control#

typescript
import {
  ThreeAxisGimbalController,
  GimbalFollowMode,
  GimbalFPVMode,
  GimbalSubjectTrackMode,
  GimbalPOILockMode,
  SmoothGimbalTransitioner,
  HorizonLeveling,
  type GimbalAngles,
} from '@oya/core';

// Initialize 3-axis gimbal
const gimbal = new ThreeAxisGimbalController();

// Set gimbal angles (radians)
const angles: GimbalAngles = {
  roll: 0,
  pitch: -0.5, // tilt down ~29 degrees
  yaw: 0,
};
gimbal.setAngles(angles, Date.now() / 1000);

// Use follow mode (gimbal follows drone heading)
const followMode = new GimbalFollowMode();
followMode.update(
  { roll: 0, pitch: 0, yaw: 0.5 }, // drone heading
  Date.now() / 1000
);

// POI lock mode (gimbal always points at a target)
const poiLock = new GimbalPOILockMode();
poiLock.setTarget({ x: 100, y: 50, z: 0 }); // target world position
poiLock.update(
  { x: 0, y: 0, z: -20 }, // drone position
  Date.now() / 1000
);

// Smooth transition between gimbal states
const transitioner = new SmoothGimbalTransitioner();

// Horizon leveling (compensate for drone roll)
const horizon = new HorizonLeveling();

Composition and Shot Planning#

typescript
import {
  RuleOfThirdsGrid,
  GoldenRatioComposition,
  ShotSizeClassifier,
  ShotAngleClassifier,
  EstablishingShotPlanner,
  MasterShotPlanner,
  Rule180Enforcer,
  type SubjectDescriptor,
  type CameraState,
} from '@oya/core';

// Evaluate composition using rule of thirds
const thirds = new RuleOfThirdsGrid();
const compositionScore = thirds.evaluate({
  box: { u: 0.6, v: 0.3, width: 0.15, height: 0.4 },
  worldPos: { x: 10, y: 0, z: 0 },
  facingDir: { x: -1, y: 0, z: 0 },
  height: 1.8,
});
console.log(`Composition score: ${compositionScore.overall}`);

// Classify shot size (wide, medium, close-up, etc.)
const sizeClassifier = new ShotSizeClassifier();
const angleClassifier = new ShotAngleClassifier();

Subject Tracking#

typescript
import {
  DeepSORTTracker,
  ByteTracker,
  YOLO11Detector,
  ActiveTrackMode,
  POIOrbitTracking,
  type Detection,
  type Track,
} from '@oya/core';

// Initialize detector
const detector = new YOLO11Detector();

// Initialize tracker
const tracker = new DeepSORTTracker();

// Process a frame (normalized detections)
const detections: Detection[] = [
  {
    bbox: { x: 0.4, y: 0.3, w: 0.2, h: 0.5 },
    confidence: 0.92,
    label: 'person',
    classId: 0,
  },
];

// Update tracker with detections
const tracks: Track[] = tracker.update(detections, Date.now() / 1000);
for (const track of tracks) {
  console.log(
    `Track ${track.id}: ${track.label} at (${track.bbox.x}, ${track.bbox.y})`
  );
}

// Active tracking mode (follow primary subject)
const activeTrack = new ActiveTrackMode();

// POI orbit tracking (orbit around tracked subject)
const poiOrbit = new POIOrbitTracking();

Troubleshooting#

Problem Solution
Jerky gimbal movement Enable SmoothGimbalTransitioner; reduce PID gains
Subject tracking lost Lower confidence threshold; use OcclusionHandler
Orbit trajectory unstable Reduce angular speed; verify radius > 5 meters
Poor composition scores Adjust framing to place subjects on thirds intersections

7. Pose Estimation#

Overview#

The pose estimation system provides 2D and 3D human pose detection with support for multiple detector backends (MediaPipe, YOLO11, RTMPose, OpenPose, HRNet, ViTPose), aerial adaptations for drone-perspective footage, multi-person detection, temporal tracking, form analysis, multi-view fusion, and 3D body reconstruction.

Prerequisites#

  • Drone with camera capable of streaming frames
  • @oya/core installed
  • Appropriate model files for the chosen detector

2D Pose Detection Setup#

typescript
import {
  type Keypoint2D,
  type PoseDetection2D,
  type ImageFrame,
  type DetectorCapabilities,
} from '@oya/core';

// Create an image frame descriptor
const frame: ImageFrame = {
  width: 1920,
  height: 1080,
  timestampMs: Date.now(),
  frameIndex: 0,
};

// Process detection results
const pose: PoseDetection2D = {
  id: 0,
  keypoints: [
    { x: 0.5, y: 0.2, confidence: 0.95, name: 'nose', visible: true },
    {
      x: 0.48,
      y: 0.35,
      confidence: 0.92,
      name: 'left_shoulder',
      visible: true,
    },
    {
      x: 0.52,
      y: 0.35,
      confidence: 0.91,
      name: 'right_shoulder',
      visible: true,
    },
    { x: 0.45, y: 0.5, confidence: 0.88, name: 'left_elbow', visible: true },
    { x: 0.55, y: 0.5, confidence: 0.87, name: 'right_elbow', visible: true },
    { x: 0.42, y: 0.65, confidence: 0.85, name: 'left_wrist', visible: true },
    { x: 0.58, y: 0.65, confidence: 0.84, name: 'right_wrist', visible: true },
  ],
  boundingBox: { x: 0.35, y: 0.15, width: 0.3, height: 0.7, confidence: 0.96 },
  confidence: 0.92,
  timestampMs: frame.timestampMs,
};

Aerial Adaptation#

Drone cameras typically view subjects from above, which changes the appearance and proportions of detected poses. The aerial adapter adjusts keypoint coordinates, confidence scoring, and occlusion handling for overhead and oblique angles.

typescript
// The aerial adapter compensates for:
// - Foreshortening from overhead angles
// - Reduced keypoint visibility (top-down vs frontal)
// - Scale changes with altitude variation
// - Motion blur at speed
//
// Key considerations for aerial pose detection:
// 1. Higher altitude = smaller subjects = lower confidence
// 2. Directly overhead = only head/shoulders visible
// 3. 45-degree angle provides best full-body visibility
// 4. Wind-induced drone motion adds jitter to detections

Multi-Person Detection#

typescript
// Process multiple pose detections per frame
// Each detection gets a unique ID within the frame
const multiPersonResults: PoseDetection2D[] = [
  {
    id: 0,
    keypoints: [
      /* person 1 keypoints */
    ],
    boundingBox: { x: 0.1, y: 0.2, width: 0.2, height: 0.5, confidence: 0.94 },
    confidence: 0.94,
    timestampMs: Date.now(),
  },
  {
    id: 1,
    keypoints: [
      /* person 2 keypoints */
    ],
    boundingBox: { x: 0.6, y: 0.3, width: 0.2, height: 0.5, confidence: 0.89 },
    confidence: 0.89,
    timestampMs: Date.now(),
  },
];

// Filter low-confidence detections
const minConfidence = 0.7;
const validDetections = multiPersonResults.filter(
  (d) => d.confidence >= minConfidence
);

Temporal Tracking and Form Analysis#

typescript
// Temporal tracking smooths detections across frames
// and maintains consistent person IDs

// Form analysis evaluates body posture quality:
// - Joint angles and ranges of motion
// - Symmetry between left and right sides
// - Comparison to reference poses
// - Movement pattern recognition

3D Body Reconstruction#

typescript
// Multi-view fusion combines 2D detections from multiple cameras
// to reconstruct 3D body pose using triangulation

// 3D reconstruction provides:
// - Full 3D skeleton with joint positions
// - Body volume estimation
// - Limb length ratios
// - 3D motion trajectories

Troubleshooting#

Problem Solution
Low detection confidence Reduce altitude; use 45-degree camera angle
Missing keypoints Use a detector that supports occluded keypoints
Person ID switching Enable appearance-based re-identification (ReID)
High latency detections Use a lighter model (YOLO11-nano) or edge inference

8. Simulation#

Overview#

The Oya platform integrates with multiple simulation environments for testing and development: Gazebo (ROS-compatible physics simulation), AirSim (Unreal Engine-based), JMAVSim (PX4 lightweight sim), and the built-in physics engine for unit testing without external simulators.

Prerequisites#

  • Gazebo 11+ or Ignition Gazebo (for Gazebo integration)
  • AirSim (for AirSim integration)
  • PX4 SITL (for JMAVSim)
  • @oya/core installed

Gazebo Integration#

typescript
import {
  createDefaultWorldConfig,
  type GazeboWorldConfig,
  type GazeboPhysicsEngine,
} from '@oya/core';

// Create a default Gazebo world configuration
const worldConfig: GazeboWorldConfig = createDefaultWorldConfig();

// World uses ODE physics engine by default:
// - stepSize: 0.001 (1kHz physics)
// - realTimeUpdateRate: 1000 Hz
// - gravity: (0, 0, -9.80665) m/s^2
// - magnetic field: Earth's field at mid-latitude

// Customize the world
const customWorld: GazeboWorldConfig = {
  ...worldConfig,
  name: 'oya_test_world',
  physicsEngine: 'bullet', // Options: 'ode', 'bullet', 'dart', 'simbody'
  windEnabled: true,
  windLinearVelocity: { x: 3, y: 1, z: 0 }, // 3 m/s wind from north
  stepSize: 0.002, // 500Hz physics for faster simulation
  realTimeUpdateRate: 500,
};

// The Gazebo integration provides:
// - SDF model loading for drone, terrain, and obstacles
// - Sensor simulation (IMU, GPS, camera, LiDAR, barometer)
// - Weather effects (wind, rain, fog)
// - Multi-robot simulation
// - ROS bridge for message passing
// - Recording and playback
// - Performance monitoring

AirSim Integration#

typescript
import {
  AirSimConnection,
  type AirSimConnectionConfig,
  type AirSimConnectionState,
} from '@oya/core';

// Create AirSim connection
const airsim = new AirSimConnection({
  host: '127.0.0.1',
  port: 41451, // Default AirSim API port
  timeoutMs: 5000,
  enableApiControl: true,
});

// Connect to AirSim
const connected = airsim.connect();
console.log(`Connected: ${connected}`);

// AirSim features:
// - Vehicle connection and control
// - Image capture (RGB, depth, segmentation, infrared)
// - LiDAR point cloud simulation
// - GPS, IMU, barometer simulation
// - Weather API (rain, snow, fog, dust)
// - Collision detection
// - Multi-vehicle coordination
// - Computer vision mode (camera only, no physics)
// - Reinforcement learning API
// - Performance monitoring

// Disconnect
airsim.disconnect();

Built-in Physics Engine#

typescript
import {
  RigidBody6DOF,
  MultirotorDynamics,
  quadrotorDynamics,
  hexarotorDynamics,
  DrydenTurbulence,
  windDisturbance,
  groundEffectFactor,
  aerodynamicDrag,
  type MultirotorParams,
  type MotorConfig,
} from '@oya/core';

// Create a quadrotor dynamics model
const quad = quadrotorDynamics({
  mass: 1.5, // kg
  armLength: 0.25, // meters
  Ixx: 0.0029,
  Iyy: 0.0029,
  Izz: 0.0055,
});

// Create a rigid body for 6-DOF simulation
const body = new RigidBody6DOF();

// Simulate wind disturbance
const wind = windDisturbance(
  { x: 3, y: 1, z: 0 }, // wind velocity (m/s)
  { x: 5, y: 0, z: -20 }, // drone velocity (m/s)
  0.01, // drag coefficient
  0.04, // cross-sectional area (m^2)
  1.225 // air density (kg/m^3)
);

// Dryden turbulence model
const turbulence = new DrydenTurbulence();

// Ground effect at low altitude
const geFactor = groundEffectFactor(
  2.0, // altitude (meters)
  0.25 // rotor radius (meters)
);
// geFactor > 1.0 means increased thrust efficiency near ground

PX4 SITL (JMAVSim)#

typescript
import { PX4SITLConnection, PX4SITLState } from '@oya/core';

// JMAVSim is a lightweight PX4 simulator
// Start it with: make px4_sitl jmavsim

const jmavsim = new PX4SITLConnection({
  host: '127.0.0.1',
  port: 14540,
  vehicleModel: 'iris',
  speedFactor: 1.0,
  headless: true, // No GUI for CI/CD
});

const state = jmavsim.connect(Date.now());
jmavsim.startSim(Date.now());

// Use higher speed factor for automated tests
jmavsim.setSpeedFactor(10.0); // 10x real-time

Troubleshooting#

Problem Solution
Gazebo crashes on startup Check graphics drivers; try headless mode
AirSim high latency Reduce render quality; check GPU availability
Physics instability Reduce physics time step; check for NaN in state
SITL connection refused Start SITL first; verify port matches configuration

9. Edge Deployment#

Overview#

The edge deployment system manages model optimization and deployment to onboard compute hardware. It supports Jetson Nano/Orin, Coral TPU, Hailo-8, Qualcomm SNPE, and x86 GPU platforms. Features include model quantization, pruning, OTA updates, canary deployment, thermal throttling, inference scheduling, and fleet model management.

Prerequisites#

  • Edge compute hardware (Jetson, Coral, Hailo, or x86 with GPU)
  • @oya/core installed
  • Pre-trained models in ONNX or TensorFlow Lite format

Hardware Capability Detection#

typescript
import {
  type EdgePlatform,
  type HardwareCapability,
  type ResourceSnapshot,
} from '@oya/core';

// Hardware platforms supported:
// - jetson_nano, jetson_orin_nano, jetson_orin_nx, jetson_agx_orin
// - coral_dev_board, coral_usb
// - hailo8, hailo8l
// - qualcomm_rb5, qualcomm_rb3
// - raspberry_pi_5
// - x86_cpu, x86_gpu

// HardwareCapability describes the platform
const capability: HardwareCapability = {
  platform: 'jetson_orin_nano' as EdgePlatform,
  cpuArch: 'arm64',
  cpuCores: 6,
  // ... additional capability fields
};

Model Optimization#

typescript
import {
  type QuantizationType,
  type QuantizationMode,
  type PruningStrategy,
  type OptimizationPass,
} from '@oya/core';

// Quantization types supported:
// - int8, uint8, int4 (for maximum compression)
// - fp16, bf16 (for balanced accuracy/speed)
// - fp8_e4m3, fp8_e5m2 (for newer GPUs)

// Quantization modes:
// - static: calibration dataset required, best accuracy
// - dynamic: no calibration, slightly lower accuracy
// - qat: quantization-aware training, best overall

// Pruning strategies:
// - magnitude: remove smallest weights
// - structured: remove entire channels/filters
// - unstructured: remove individual weights
// - movement: track weight movement during training
// - lottery: lottery ticket hypothesis

// Optimization passes:
// - constant_folding
// - dead_code_elimination
// - common_subexpression
// - operator_fusion
// - layout_optimization
// - memory_planning
// - shape_inference

Model Inference#

typescript
import {
  type InferenceBackend,
  type InferenceDevice,
  type PrecisionMode,
  type Tensor,
  type TensorShape,
  type InferenceResult,
} from '@oya/core';

// Inference backends:
// - tensorrt: NVIDIA TensorRT (fastest on Jetson/GPU)
// - onnxruntime: ONNX Runtime (cross-platform)
// - tflite: TensorFlow Lite (Coral TPU, mobile)
// - openvino: OpenVINO (Intel hardware)

// Inference devices:
// - cpu, gpu, npu, tpu, dla

// Precision modes:
// - fp32: full precision
// - fp16: half precision (2x speedup on GPU)
// - int8: 8-bit integer (4x speedup, requires calibration)
// - mixed: mixed precision (best speed/accuracy tradeoff)

Deployment Lifecycle#

typescript
import { type DeploymentState } from '@oya/core';

// Deployment states:
// pending -> downloading -> installing -> validating -> active
//                                                    -> failed -> rolled_back
//                                                    -> canary (staged rollout)

// Resource monitoring
const snapshot: ResourceSnapshot = {
  cpuPercent: 45,
  gpuPercent: 72,
  memoryUsedBytes: 2 * 1024 * 1024 * 1024, // 2 GB
  memoryTotalBytes: 8 * 1024 * 1024 * 1024, // 8 GB
  gpuMemoryUsedBytes: 3 * 1024 * 1024 * 1024,
  gpuMemoryTotalBytes: 8 * 1024 * 1024 * 1024,
  diskUsedBytes: 20 * 1024 * 1024 * 1024,
  powerWatts: 12.5,
  temperatureC: 62,
  timestampMs: Date.now(),
};

// Thermal throttling: if temperatureC > 80, reduce inference frequency
// Power management: if powerWatts > threshold, switch to lower precision

Troubleshooting#

Problem Solution
Model fails to load Verify model format matches backend (ONNX/TFLite)
INT8 accuracy too low Use a representative calibration dataset
GPU memory exhaustion Reduce batch size; use fp16 instead of fp32
Thermal throttling active Improve cooling; reduce inference frequency
Deployment rollback triggered Check validation logs; verify model compatibility

10. Safety#

Overview#

The safety subsystem provides comprehensive protection through geofencing, failsafe procedures, emergency response, and regulatory compliance. It includes polygon/circular geofences, altitude limits, no-fly zones, graduated warnings, emergency state machine, auto-land, return-to-home, parachute deployment, lost-link procedures, and black box recording.

Prerequisites#

  • @oya/core installed
  • Knowledge of local drone regulations (FAA Part 107, EASA, etc.)
  • Flight area coordinates for geofence configuration

Geofencing#

typescript
import {
  PolygonGeofence,
  type PolygonGeofenceConfig,
  type GeoPoint2D,
  type GeofenceZone,
  GeofenceType,
  GeofenceBehavior,
} from '@oya/core';

// Define a polygon geofence
const geofenceConfig: PolygonGeofenceConfig = {
  vertices: [
    { lat: 47.397, lon: 8.544 },
    { lat: 47.399, lon: 8.544 },
    { lat: 47.399, lon: 8.548 },
    { lat: 47.397, lon: 8.548 },
  ],
  minAlt: 0,
  maxAlt: 120, // FAA max 400ft ~ 122m
  bufferMeters: 20, // Warning zone 20m before boundary
};

const geofence = new PolygonGeofence(geofenceConfig);

// Check if a position is within the geofence
const isInside = geofence.containsPoint(47.398, 8.546);
console.log(`Inside geofence: ${isInside}`); // true

// Using the Zod-validated GeofenceZone type
const zone: GeofenceZone = {
  id: 'zone-001',
  name: 'Operations Area Alpha',
  type: GeofenceType.Polygon,
  vertices: [
    { latitude: 47.397, longitude: 8.544, altitude: 0 },
    { latitude: 47.399, longitude: 8.544, altitude: 0 },
    { latitude: 47.399, longitude: 8.548, altitude: 0 },
    { latitude: 47.397, longitude: 8.548, altitude: 0 },
  ],
  minAltitude: 0,
  maxAltitude: 120,
  behavior: GeofenceBehavior.ReturnToHome,
};

Emergency Procedures#

typescript
import {
  type EmergencyState,
  type EmergencyTrigger,
  type EmergencyTransition,
  EmergencyType,
  type EmergencyProcedure,
} from '@oya/core';

// Emergency states follow a finite state machine:
//
//   nominal -> caution -> warning -> emergency
//                                     |
//                          +-----------+-----------+
//                          |           |           |
//                       auto-land     rth     hover-hold
//                          |           |           |
//                          |     controlled-descent|
//                          |           |           |
//                          +-----+-----+-----+----+
//                                |           |
//                          parachute     motor-kill
//                                |
//                             resolved

// Emergency triggers:
// - low-battery, critical-battery
// - gps-loss
// - imu-failure, motor-failure
// - comm-loss
// - geofence-breach
// - collision-imminent
// - pilot-command
// - system-fault

// Define emergency procedures with priorities
const procedures: EmergencyProcedure[] = [
  {
    type: EmergencyType.ReturnToHome,
    priority: 2,
    conditions: ['low-battery', 'comm-loss'],
    altitudeLimit: 120,
  },
  {
    type: EmergencyType.Land,
    priority: 1,
    conditions: ['critical-battery', 'imu-failure'],
    altitudeLimit: 0,
  },
  {
    type: EmergencyType.Hover,
    priority: 3,
    conditions: ['gps-loss'],
    altitudeLimit: 0,
  },
  {
    type: EmergencyType.MotorKill,
    priority: 0, // Last resort
    conditions: ['collision-imminent'],
    altitudeLimit: 0,
  },
];

Failsafe Configuration#

typescript
import {
  MissionFailsafeManager,
  FailsafeType,
  FailsafeAction,
  type FailsafeConfig,
} from '@oya/core';

// Configure failsafe responses
const failsafeConfig: FailsafeConfig = {
  type: FailsafeType.Battery,
  threshold: 25, // Trigger at 25% battery
  action: FailsafeAction.ReturnToHome,
  enabled: true,
};

const failsafe = new MissionFailsafeManager();

// Failsafe types:
// - Battery: triggers on low battery percentage
// - Communication: triggers on link loss timeout
// - GPS: triggers on GPS fix loss
// - Geofence: triggers on boundary breach
// - Motor: triggers on motor failure detection

Regulatory Compliance#

typescript
import {
  FAA_MAX_ALTITUDE_AGL_M,
  FAA_MAX_ALTITUDE_AGL_FT,
  REGULATORY_MAX_ALTITUDE,
  AirspaceClass,
} from '@oya/core';

// FAA Part 107 limits
console.log(
  `Max altitude AGL: ${FAA_MAX_ALTITUDE_AGL_FT}ft (${FAA_MAX_ALTITUDE_AGL_M}m)`
);

// Airspace classes
// Class A: IFR only, ATC clearance required (18,000ft+)
// Class B: IFR and VFR, ATC clearance (major airports)
// Class C: IFR and VFR, ATC service (medium airports)
// Class D: IFR and VFR, ATC service (small airports)
// Class E: IFR and VFR, ATC for IFR only
// Class G: Uncontrolled (most drone operations)

// Check mission constraints against regulatory limits
const missionAltitude = 100; // meters
if (missionAltitude > FAA_MAX_ALTITUDE_AGL_M) {
  console.error(
    `Altitude ${missionAltitude}m exceeds FAA limit of ${FAA_MAX_ALTITUDE_AGL_M}m`
  );
}

Flight Logging and Black Box#

typescript
import { type FlightPlan, FlightPlanStatus } from '@oya/core';

// Flight plans provide audit trails
const plan: FlightPlan = {
  id: 'plan-001',
  missionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',
  droneId: 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d',
  plannedAt: new Date().toISOString(),
  estimatedStartTime: new Date().toISOString(),
  estimatedEndTime: new Date(Date.now() + 3600000).toISOString(),
  weatherCheck: {
    passed: true,
    conditions: {
      windSpeedMs: 5,
      windDirection: 180,
      temperatureCelsius: 22,
      humidity: 45,
      pressure: 1013,
      visibility: 10000,
      precipitation: 'None',
    },
    warnings: [],
  },
  airspaceCheck: {
    passed: true,
    airspaceClass: AirspaceClass.G,
    authorization: 'LAANC-2024-001',
    warnings: [],
  },
  status: FlightPlanStatus.Approved,
};

Troubleshooting#

Problem Solution
Geofence breach not detected Verify geofence vertices form a closed polygon
Failsafe not triggering Check failsafe config is enabled and threshold set
Emergency RTH overshooting Reduce RTH speed; verify wind compensation
Altitude limit exceeded Set geofence maxAltitude below regulatory limit
Weather check failing Review WeatherConditions thresholds

Appendix: Common Imports Reference#

typescript
// Types and Enums
import {
  FlightMode,
  DroneState,
  ConnectionStatus,
  AirspaceClass,
  GimbalMode,
  GeofenceBehavior,
  GeofenceType,
  EmergencyType,
  FlightPlanStatus,
  WaypointAction,
  WeatherResistance,
} from '@oya/core';

// Branded IDs
import {
  type DroneId,
  type SwarmId,
  type MissionId,
  type WaypointId,
  DroneIdSchema,
  SwarmIdSchema,
  MissionIdSchema,
  WaypointIdSchema,
} from '@oya/core';

// 3D Math
import {
  type Position3D,
  type Velocity3D,
  type Orientation,
  type Quaternion,
  type Vec3,
  type Quat,
  vec3,
  vec3Zero,
  vec3Add,
  vec3Sub,
  vec3Scale,
  vec3Mag,
  vec3Normalize,
  quatIdentity,
} from '@oya/core';

// Coordinates and Transforms
import {
  type GPSCoordinates,
  type LocalCoordinates,
  type BodyCoordinates,
  gpsToLocal,
  localToGps,
  haversineDistance,
  bearing,
  degreesToRadians,
} from '@oya/core';

// Validation
import {
  validateGPSCoordinates,
  validateBatteryState,
  validateFlightPlan,
  validateGeofence,
  validateMission,
} from '@oya/core';

// Telemetry
import {
  type Telemetry,
  type BatteryState,
  TelemetrySchema,
  BatteryStateSchema,
} from '@oya/core';

// Constants
import {
  STANDARD_GRAVITY,
  EARTH_MEAN_RADIUS,
  FAA_MAX_ALTITUDE_AGL_M,
  BATTERY_LOW_PERCENT,
  DEFAULT_CRUISE_SPEED,
  DEFAULT_RTH_ALTITUDE,
} from '@oya/core';