Control Language


SCLAM: Spacecraft Command Language Specification v1.5

Change Log:

  • v1.5: Comprehensive update providing highly detailed explanations for all commands, core concepts, and integration notes. Added multiple, explained examples for nearly every command to illustrate various use cases and parameter effects. Enhanced focus on robustness, error handling, and real-world operational context.
  • v1.4: Incorporated SCRAMJET engine functionality, including specific engine commands, fuel tracking (PROPELLANT_SCRAMJET_FUEL_KG), propulsion modes, flight transitions (JET_TO_SCRAMJET, SCRAMJET_TO_ROCKET), and updated examples.
  • v1.3: Added specific propellant tracking (Kerosene/LOX), current mass query. Enhanced battery monitoring (charge, health, current). Added state parameters for solar array and RTG power sources. Updated relevant commands, examples, and integration notes.
  • v1.2: Major revision focusing on real-world applicability. Added detailed explanations and examples for ALL commands. Introduced commands for constraints, diagnostics, data management, payload control, event triggers, and enhanced system control. Refined error handling concepts. Noted Neural Net use for camera sensors.
  • v1.1: Incorporated specific VTOL space plane hardware (propellers, turbines, heat shields) and operational modes (jet takeoff, aero-to-rocket transition).

  • v0.1: Initial sample iz3-SCLAM language idea - example:

  • FIRE,T1,0.1N,0.2S  // FIRE THRUSTER 1 AT 0.1 NEWTONS FOR 0.2 SECONDS;
    WAIT,20.0S  // WAIT 20 SECONDS BEFORE NEXT INSTRUCTION;
    ROTATE1,-20D,1.0S  // ROTATE UP-DOWN -20 DEGREES OVER 1.0 SECONDS;
    WAIT,5.0S
    ROTATE2,-5D,1.0S  // ROTATE SIDEWAYS -5 DEGREES OVER 1.0 SECONDS;
    CHECKCAMERA,ALL,ISS,T1 // CHECK ALL CAMERAS FOR ISS AND CALL TARGET T1;
    IF T1,CRUISE,T1,50KM,500M  // AUTOMATIC VECTOR TO TARGET T1 IF T1 IS VALID AND STOP 500M AWAY;
    ENDIF;
    IF NO T1, EARTHORBIT,15D,55000M // IF NO TARGET T1 FOUND GO INTO EARTH ORBIT AT 55000M AT 15DEGREES FROM TRUE NORTH;
    REPEAT
    CHECKCAMERA,ALL,ISS,T1 // CHECK ALL CAMERAS FOR ISS AND CALL TARGET T1;
    UNTIL T1 IS FOUND
    ENDIF;
    IF T1,CRUISE,T1,50KM,500M  

1. Introduction

1.1. Philosophy

The Spacecraft Command Language for Advanced Missions (SCLAM) is designed to provide a human-readable, yet robust, verifiable, and comprehensive command interface for controlling complex spacecraft. This version (v1.5) represents a detailed specification intended for direct use in high-fidelity simulation, rigorous testing, and real-world mission operations, particularly for advanced vehicles like VTOL-capable space planes featuring multi-modal propulsion and complex subsystems.

Vehicle Profile:

  • Propulsion: VTOL Propellers (Stabilization, Electric), VTOL/Aero Turbines (Jet Fuel), SCRAMJETs (Hypersonic, SCRAMJET Fuel), Main Rockets (Kerosene/LOX), RCS (Storable).
  • Power: Solar Arrays, Rechargeable Batteries, potentially RTGs.
  • Other: Deployable Propeller Heat Shields, Advanced Sensors (NN-based Vision).

SCLAM balances operational simplicity with the comprehensive capability required for missions where tracking specific propellant levels (including Jet Fuel, Kerosene/LOX, RCS, and SCRAMJET fuel), changing vehicle mass, detailed battery state-of-health, and managing multiple power sources are critical. It emphasizes clarity, verifiability, robustness, detailed state awareness (consumables, mass, power), and predictable behavior.

Target Uses:

  • Mission Planning & Sequence Design: Defining nominal and contingency operations.
  • Automated Onboard Execution: Enabling autonomy through script processing.
  • Ground Control Interface: Facilitating telecommanding and monitoring.
  • Simulation & V&V: Providing a testable interface for validating flight software and mission plans.
  • Flight Software Implementation: Serving as the core command language specification.

1.2. Syntax Overview

  • Commands: Uppercase English keywords (e.g., WAIT, ENGINE_RCS, NAV_MANEUVER). Defined for specific actions.
  • Parameters: Comma-separated values following the command. Order is strict. Data types (Float, Integer, String, Enum, Vector, Boolean) are defined per command.
  • Units: Standard SI units are default and rigorously applied (meters, seconds, kg, N, deg, W, V, A, K, Pa, etc.). Explicitly documented for each parameter. Consistency is safety-critical. Parameter suffixes (e.g., _S, _M, _DEG, _N, _MPS) are used where beneficial for readability but the underlying value is assumed to be in standard base units unless noted.
  • Comments: // denotes single-line comments. Mandatory for explaining script logic and intent.
  • Case Sensitivity: Commands & Enums = CASE-INSENSITIVE. Variables & Strings = CASE-SENSITIVE. Recommendation: UPPERCASE commands, CamelCase or snake_case variables.
  • Variables: VAR for local script storage of state data, sensor results, calculations. Scope is typically execution context.
  • Labels & Flow Control: LABEL, GOTO, IF/THEN/ELSE/ENDIF, REPEAT/UNTIL, CALL/RETURN. Structured control flow (IF, REPEAT, CALL) is strongly preferred over GOTO.

1.3. Standard Units

Strict adherence to standard units is critical. Unless explicitly overridden:

  • Distance: Meters (m)
  • Time: Seconds (s)
  • Velocity: Meters per second (m/s)
  • Acceleration: Meters per second squared (m/s²)
  • Mass: Kilograms (kg)
  • Force: Newtons (N)
  • Angles: Degrees (deg) - Note: Underlying calculations might use radians; conversion handled by implementation.
  • Angular Velocity: Degrees per second (deg/s)
  • Throttle/Level: Percentage (0.0-100.0)
  • RPM: Revolutions Per Minute
  • Data Rate: Bits per second (bps)
  • Power: Watts (W)
  • Temperature: Kelvin (K)
  • Energy: Joules (J) or Watt-hours (Wh) as specified.
  • Current: Amperes (A)
  • Voltage: Volts (V)
  • Mach Number: Dimensionless ratio to local speed of sound.
  • Dynamic Pressure: Pascals (Pa)

2. Core Concepts (Expanded Detail)

2.1. Coordinate Frames

Understanding coordinate frames is absolutely critical for mission safety and success. All vector quantities (position, velocity, delta-V, pointing vectors) and orientations (attitudes) are meaningless without a defined frame. SCLAM uses standard astronomical and aerospace frames. The flight software's GNC component performs all necessary transformations based on the specified frames.

  • BODY: Orthogonal axes fixed to the vehicle structure (e.g., +X Forward, +Y Right, +Z Down). Must be unambiguously defined in vehicle documentation. Used for defining thruster locations, sensor boresights, body rotation rates.
  • INERTIAL Frames: Non-rotating reference frames, essential for orbital mechanics and propagation.
    • EARTH_CI (ECI): Earth-Centered Inertial. Typically aligned with Earth's mean equator and equinox at a specific epoch (e.g., J2000). Standard for Earth orbit calculations.
    • MOON_CI, MARS_CI, SUN_CI (HCI): Similar inertial frames centered on the Moon, Mars, or Sun respectively. Used for operations near those bodies or for interplanetary trajectories.
  • Rotating Frames: Frames that rotate with a celestial body.
    • EARTH_CF (ECEF): Earth-Centered, Earth-Fixed. Rotates with Earth. Useful for targeting fixed points on the surface (landing sites, ground stations). Latitude/Longitude are typically defined relative to this frame.
    • MOON_CF, MARS_CF: Similar body-fixed frames for Moon and Mars.
    • LVLH: Local Vertical / Local Horizontal. An orbiting frame centered on the spacecraft. +Z typically points to the central body's center (Nadir), +Y is often aligned opposite the orbit normal vector, and +X completes the right-handed set (often close to the inertial velocity vector in near-circular orbits). Useful for Earth/Nadir pointing, maintaining stable attitudes relative to the orbit path.
  • Relative Frames: Defined relative to another object or the environment.
    • TARGET_RELATIVE <target_name>: Centered on a target (e.g., "ISS"). Axis definition is crucial and context-dependent. Common definitions include VNC (Velocity-Normal-Cross-product) or RNC (Radial-Normal-Cross-product) relative to the target, or axes aligned with target docking ports. Must be precisely defined for rendezvous/docking operations.
    • LANDING_FRAME: Aligned with the local surface tangent plane at the target landing site (+Z Up, +X North, +Y East). Used for final descent guidance and touchdown attitude.
    • AERO_FRAME: Defined by the vehicle's velocity vector relative to the surrounding atmosphere. Used for specifying Angle of Attack (AoA), Sideslip Angle (SSA), and aerodynamic forces/moments.

2.2. Time Systems & Synchronization

Accurate timekeeping and synchronization are vital.

  • Durations: Simple time intervals in seconds (_S). Used where relative timing is sufficient. Subject to onboard clock drift unless resynchronized.
  • Absolute Time (UTC): The global standard. Format "YYYY-MM-DDTHH:MM:SS.sssZ". Required for coordinating with ground events, predicting celestial body positions, and long-term planning. The spacecraft clock must be periodically synchronized with ground UTC via the communication system. WAIT_UNTIL <time_utc> allows precise event timing.
  • Event-Based Timing: Using WAIT_UNTIL <condition> or SET_EVENT_TRIGGER makes sequences more robust against unexpected delays or variations in execution time compared to relying solely on fixed WAIT durations. It allows the script to react to the actual state of the spacecraft.

2.3. State Variables & Data Management

  • Onboard State Model: The flight software maintains a comprehensive, continuously updated model of the vehicle's status. This includes dynamics (position, velocity, attitude, rates), consumables (propellants by type, battery charge), power generation/consumption, thermal state (temperatures), system health flags, sensor readings, GNC mode, etc.
  • GET_STATE: Provides read-only access to specific state parameters. This is fundamental for decision-making within scripts (IF conditions), logging critical parameters, and checking preconditions before executing commands. Access is synchronous.
  • VAR: Allows scripts to create temporary variables. Useful for storing results from GET_STATE, sensor scans, or intermediate calculations needed for script logic (e.g., calculating required burn time based on current mass and desired delta-V, although GNC often handles this internally for NAV_MANEUVER).
  • Data Management (DATA_MANAGE): Provides basic capabilities to manage the finite onboard data storage (e.g., science data, logs, images) and control how data is prioritized for downlink over limited communication bandwidth.
  • Mass Properties: The GNC system's internal state model includes not just total mass (CURRENT_MASS_KG) but also the calculated Center of Mass (CM) and Moments of Inertia (MoI), which change as propellants are consumed. These are **critical** for accurate thrust vector control, attitude control torque calculations, and maneuver planning. While scripts can query total mass, GNC uses the detailed properties implicitly.

2.4. Error Handling, Status & Constraints (Expanded)

Robust error handling is paramount for autonomous or remotely operated spacecraft. SCLAM provides several mechanisms:

  • Command Status (LAST_COMMAND_STATUS): Every command execution updates this system variable. Scripts must check it after commands that can fail or have preconditions. Standard statuses include:
    • SUCCESS: Command completed nominally.
    • EXECUTING: Asynchronous command started and is ongoing (e.g., NAV_MANEUVER, WAIT_UNTIL, SYSTEM_DEPLOY). Script must typically wait for completion using WAIT_UNTIL specific status flags (e.g., MANEUVER_STATUS == COMPLETE).
    • FAILED_PRECONDITION: Command could not start because a necessary condition was not met (e.g., insufficient fuel/power estimated for NAV_MANEUVER, system off, required attitude not achieved, flight conditions unsuitable for ENGINE_SCRAMJET).
    • FAILED_EXECUTION: Command started but failed during execution (e.g., engine flameout, guidance divergence, mechanism jammed, timeout reached on WAIT_UNTIL, hardware fault detected).
    • INVALID_PARAMETER: Command received parameters of the wrong type, out of range, or inconsistent values. Script error.
    • ABORTED: Command was terminated prematurely by another command, a constraint violation action, or a safety system intervention.
    • UNKNOWN_COMMAND: The command keyword itself was not recognized by the parser/executor. Script error.
  • Script Response Patterns:
    1. Check Status: IF LAST_COMMAND_STATUS != SUCCESS THEN ...
    2. Log Error: LOG ERROR "Command X failed with status: " + LAST_COMMAND_STATUS
    3. Handle Failure:
      • Retry: If appropriate (e.g., transient comm issue), perhaps after a WAIT.
      • Contingency Branch: CALL Contingency_Script.sclam or GOTO Error_Handler_Label.
      • Safe Mode: SET_POWER_MODE SAFE_MODE or CALL Enter_Safe_Mode.sclam for serious issues.
      • Terminate Script: RETURN "SCRIPT_FAILURE" if unable to recover.
  • Logging (LOG): Detailed logging at appropriate levels (DEBUG, INFO, WARN, ERROR, CRITICAL) is indispensable for understanding script execution flow, decision points, state changes, and diagnosing failures post-facto. Log consumable usage, power state, key sensor readings, and command outcomes.
  • Constraints (SET_CONSTRAINT): Proactive safety mechanism. Allows defining operational limits (e.g., TEMPERATURE SensorX > 350.0, BATTERY_CHARGE_PERCENT MainBus < 15.0, PROPELLANT_RCS_KG < 2.0). The flight software monitors these constraints. Violations can automatically trigger actions (LOG_WARN, LOG_ERROR, TRIGGER_EVENT, ENTER_SAFE_MODE), providing an autonomous safety layer independent of immediate script logic.
  • Health Checks & Diagnostics (SYSTEM_HEALTH_CHECK, RUN_DIAGNOSTIC): Allow scripts to verify system readiness before critical operations or to investigate anomalies flagged by telemetry or constraint violations.

3. Command Reference (Detailed Explanations & Examples)


3.1. Control Flow Commands

WAIT <duration_S>

Detailed Explanation: Suspends script execution for a fixed duration in seconds. This is a simple, relative delay. It's useful for allowing physical processes to complete (e.g., valve actuation, thruster plume dissipation, thermal settling) or for pacing commands when absolute timing isn't critical. However, overuse can make sequences brittle; prefer WAIT_UNTIL for synchronization with specific events or states where possible. The duration must be non-negative.

Parameters:

  • duration_S (Float): Time to wait in seconds. Precision depends on the onboard clock and scheduler.

Returns Status: SUCCESS immediately upon completion of the wait period. Cannot typically fail unless the script execution itself is aborted.

Example 1 (Simple Delay):

// Command sequence for deploying an instrument
SYSTEM_POWER "Instrument_A" ON
WAIT 5.0 // Allow 5 seconds for instrument power-up and self-test
LOG INFO "Instrument A powered on, proceeding with configuration."
CALL "Configure_Instrument_A.sclam"

Explanation: Provides a fixed delay for hardware initialization before proceeding.

Example 2 (Pacing):

// Take sensor readings every minute for 10 minutes
VAR Counter = 0
REPEAT
  LOG INFO "Taking sensor reading #" + (Counter + 1)
  CALL "Take_Sensor_Reading.sclam"
  VAR Counter = Counter + 1
  WAIT 60.0 // Wait 1 minute before the next reading
UNTIL Counter >= 10

Explanation: Uses WAIT to create a periodic action within a loop.

WAIT_UNTIL <condition | time_utc>

Detailed Explanation: Suspends script execution until a specific logical condition becomes true or an absolute UTC time is reached. This is a cornerstone command for creating robust, event-driven sequences. The condition string is evaluated periodically by the flight software using current GET_STATE values or script variables. This command is asynchronous; the script yields control while waiting. It's essential to check LAST_COMMAND_STATUS upon resumption, as the wait could time out (if implemented) or the condition might become impossible to meet (e.g., waiting for an altitude that is never reached due to a maneuver failure).

Parameters:

  • condition (String): A boolean expression evaluated against current state. Must resolve to TRUE for the wait to complete successfully. Syntax depends on implementation but typically supports standard operators (<, >, ==, !=, <=, >=) and logical operators (AND, OR, NOT). Can involve GET_STATE calls implicitly or explicitly. Examples: "GET_STATE ALTITUDE_M > 50000", "Sensor_Ready_Flag == TRUE", "(GET_STATE BATTERY_CHARGE_PERCENT MainBus > 95.0) OR (GET_STATE SOLAR_ARRAY_STATUS Port == SUN_TRACKING)".
  • time_utc (String): An absolute UTC time string ("YYYY-MM-DDTHH:MM:SS.sssZ"). The wait completes when the spacecraft clock reaches or exceeds this time.

Returns Status: EXECUTING while waiting. SUCCESS when condition met or time reached. FAILED_EXECUTION if an implementation-defined timeout occurs, the condition expression is invalid, or the condition becomes impossible (e.g., waiting for a system status that enters a FAULT state).

Example 1 (Wait for State):

LOG INFO "Waiting for battery charge to exceed 80%."
WAIT_UNTIL "GET_STATE BATTERY_CHARGE_PERCENT MainBus > 80.0"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO "Battery sufficiently charged."
ELSE
    LOG WARN "Wait for battery charge condition failed or timed out."
ENDIF

Explanation: Pauses the script until the main battery reaches a desired charge level, essential before high-power operations.

Example 2 (Wait for Maneuver Completion):

LOG INFO "Executing orbital maneuver."
NAV_MANEUVER CHANGE_ORBIT 450000 450000 null null null
WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE OR GET_STATE MANEUVER_STATUS == FAILED" // Wait for maneuver end state
VAR ManeuverResult = GET_STATE MANEUVER_STATUS
LOG INFO "Maneuver final status: " + ManeuverResult
IF ManeuverResult != COMPLETE THEN
     CALL "Handle_Maneuver_Failure.sclam"
ENDIF

Explanation: Waits for an asynchronous maneuver to finish, checking its final status to determine the next steps.

Example 3 (Wait for Time):

LOG INFO "Scheduling payload activation for 10:00 UTC."
WAIT_UNTIL "2026-03-01T10:00:00.000Z"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO "Activating payload."
    PAYLOAD_COMMAND "ScienceCam" "START_SEQUENCE_ALPHA"
ELSE
    LOG ERROR "Wait until time failed (clock issue?)."
ENDIF

Explanation: Synchronizes a command with a specific time, perhaps for coordinated observations or communication windows.

VAR <name> = <value | expression | GET_STATE(...) | GET_TARGET_STATE(...)>

Detailed Explanation: Declares or assigns a value to a variable within the script's execution context. Variables are essential for storing intermediate results, making scripts more readable, and enabling complex logic. The type of the variable (Float, Integer, String, Boolean, Vector, Structure) is typically inferred from the assigned value. Simple arithmetic (+, -, *, /) on numeric variables might be supported by the implementation. Scope is usually local to the script instance.

Parameters:

  • name (String): Variable name. Follow consistent naming conventions (e.g., targetAltitudeM, isTargetVisible, deltaV_Vector). Case-sensitive.
  • value | expression | ... (Any): The value to assign. Can be:
    • Literal: 123.4, 100, "Nominal", TRUE, [1.0, 0.0, 0.0]
    • Expression: VariableA + 5.0 (if supported)
    • State Query: GET_STATE ALTITUDE_M, GET_TARGET_STATE "ISS" POSITION_VECTOR "EARTH_CI"
    • Sensor Scan Result: SENSOR_SCAN LIDAR LANDING_ZONE (assigns a structure)

Returns Status: SUCCESS if assignment is syntactically valid, INVALID_PARAMETER if name/value is invalid or expression fails.

Example 1 (Storing State):

VAR CurrentMass = GET_STATE CURRENT_MASS_KG
VAR RcsFuel = GET_STATE PROPELLANT_RCS_KG
LOG INFO "Current Mass: " + CurrentMass + " kg, RCS Fuel: " + RcsFuel + " kg."

Explanation: Retrieves and stores current mass and fuel level, perhaps for logging or subsequent checks.

Example 2 (Storing Calculation):

VAR TargetPeriapsis = 150000.0 // Target 150km
VAR CurrentApoapsis = GET_STATE APOAPSIS_M
VAR RequiredDeltaV = CalculateBurnDeltaV(CurrentApoapsis, TargetPeriapsis) // Assumes a function/lookup exists
LOG INFO "Required DeltaV for periapsis adjust: " + RequiredDeltaV + " m/s."

Explanation: Stores results of calculations (assuming CalculateBurnDeltaV is a conceptual placeholder for GNC interaction or a script function if supported) for use in maneuver planning.

Example 3 (Storing Boolean Flag):

VAR IsSunlit = GET_STATE SOLAR_ARRAY_STATUS "ALL" != "SHADOWED"
IF IsSunlit == TRUE THEN
    LOG DEBUG "Spacecraft is currently in sunlight."
ELSE
    LOG DEBUG "Spacecraft is currently in shadow."
ENDIF

Explanation: Creates a boolean flag based on solar array status for conditional logic.

Example 4 (Storing Sensor Structure):

VAR LandingZoneInfo = SENSOR_SCAN LIDAR LANDING_ZONE
WAIT_UNTIL "GET_STATE SENSOR_STATUS LIDAR == IDLE"
IF LandingZoneInfo.found == TRUE THEN
    LOG INFO "LZ Found. Slope: " + LandingZoneInfo.slope_deg + " deg."
ENDIF

Explanation: Stores the structured output from a sensor scan, allowing access to individual fields like .found or .slope_deg.

IF <condition> THEN

Detailed Explanation: Initiates a conditional block. The commands between IF...THEN and the corresponding ELSE or ENDIF are executed only if the condition evaluates to TRUE. Conditions are boolean expressions involving variables, GET_STATE results, or comparison of LAST_COMMAND_STATUS. Essential for decision-making, error handling, and adapting sequences to the current state.

Parameters:

  • condition (String): A boolean expression (e.g., VariableA > 10.0, GET_STATE SYSTEM_STATUS "Gyro1" == "NOMINAL", LAST_COMMAND_STATUS == SUCCESS). Must evaluate unambiguously to TRUE or FALSE.

Example 1 (Simple State Check):

IF GET_STATE ALTITUDE_M < 10000 THEN
    LOG WARN "Low altitude detected!"
    CALL "Initiate_Climb_Procedure.sclam"
ENDIF

Explanation: Executes a climb procedure only if the altitude drops below a threshold.

Example 2 (Command Status Check):

SYSTEM_DEPLOY SOLAR_PANELS
WAIT_UNTIL "GET_STATE SYSTEM_STATUS SOLAR_PANELS != DEPLOYING"
IF LAST_COMMAND_STATUS == SUCCESS AND GET_STATE SYSTEM_STATUS SOLAR_PANELS == DEPLOYED_LOCKED THEN
    LOG INFO "Solar panels deployed successfully."
ELSE
    LOG ERROR "Solar panel deployment failed! Status: " + GET_STATE SYSTEM_STATUS SOLAR_PANELS
    GOTO Handle_Solar_Panel_Failure
ENDIF

Explanation: Checks both the command completion status and the final system state to confirm successful deployment.

Example 3 (Combined Conditions):

VAR BattCharge = GET_STATE BATTERY_CHARGE_PERCENT "MainBus"
VAR PowerGen = GET_STATE SOLAR_ARRAY_POWER_W "ALL" + GET_STATE RTG_POWER_W "ALL"
VAR PowerLoad = GET_STATE CURRENT_POWER_LOAD_W
IF BattCharge < 20.0 AND PowerGen < PowerLoad THEN
    LOG CRITICAL "Low battery and negative power margin! Entering Safe Mode."
    CALL "Enter_Safe_Mode.sclam"
ENDIF

Explanation: Uses multiple conditions combined with AND to trigger a critical action only if battery is low *and* power generation is less than the current load.

ELSE

Detailed Explanation: Used within an IF block, immediately following the THEN block. The commands following ELSE up to the ENDIF are executed only if the original IF condition evaluated to FALSE. Provides an alternative execution path.

Example:

VAR TargetVisible = SENSOR_SCAN CAMERA TARGET_ID "Debris_X"
WAIT_UNTIL "GET_STATE SENSOR_STATUS CAMERA == IDLE"
IF TargetVisible.found == TRUE THEN
    LOG INFO "Target Debris_X detected. Calculating avoidance maneuver."
    CALL "Calculate_Avoidance.sclam" TargetVisible.position_vector
ELSE
    LOG INFO "Target Debris_X not detected. Continuing nominal path."
ENDIF

Explanation: Executes one action if a target is found, and a different action (or no action) if it isn't.

ENDIF

Detailed Explanation: Terminates an IF block. Every IF statement must have a corresponding ENDIF. It delineates the scope of the conditional execution.

REPEAT

Detailed Explanation: Marks the beginning of a loop block. The commands between REPEAT and the matching UNTIL will be executed one or more times.

UNTIL <condition>

Detailed Explanation: Marks the end of a REPEAT loop and provides the termination condition. The loop executes, and *then* the condition is checked. If the condition is FALSE, the loop repeats from the REPEAT statement. If the condition is TRUE, execution continues with the command following the UNTIL. This means the loop body always executes at least once.

Parameters:

  • condition (String): A boolean expression. The loop terminates when this becomes TRUE.

Example 1 (Polling for Status):

LOG INFO "Waiting for system 'Thermal_Pump_A' to reach NOMINAL status."
REPEAT
    WAIT 5.0 // Check every 5 seconds
    VAR PumpStatus = GET_STATE SYSTEM_STATUS "Thermal_Pump_A"
    LOG DEBUG "Pump A status: " + PumpStatus
UNTIL PumpStatus == "NOMINAL" OR PumpStatus == "FAULT" // Exit if nominal or failed
IF PumpStatus == "FAULT" THEN
    LOG ERROR "Thermal Pump A failed!"
ENDIF

Explanation: Repeatedly checks a system status until it becomes nominal (or enters a fault state).

Example 2 (Iterative Adjustment):

VAR AlignmentError = GET_STATE ANTENNA_POINTING_ERROR_DEG "HGA"
LOG INFO "Fine-tuning High Gain Antenna pointing."
REPEAT
    // Calculate small adjustment pulse based on AlignmentError (conceptual)
    VAR PulseDuration = CalculateRcsPulse(AlignmentError)
    ENGINE_RCS "ANTENNA_ADJUST_JETS" 1.0 PulseDuration
    WAIT 3.0 // Allow settling
    VAR AlignmentError = GET_STATE ANTENNA_POINTING_ERROR_DEG "HGA"
    LOG DEBUG "Antenna alignment error: " + AlignmentError
UNTIL AlignmentError < 0.05 // Repeat until error is very small
LOG INFO "Antenna fine-tuning complete."

Explanation: Performs small adjustments iteratively until a desired state (low pointing error) is achieved.

LABEL <name>

Detailed Explanation: Defines a named location within a script. It serves as a target destination for GOTO commands. Labels themselves do not alter the flow of execution. Choose meaningful names.

Parameters:

  • name (String): A unique identifier within the script scope (e.g., Start_Burn_Phase, Error_Handler_Power).

Example:

// ... script commands ...
GOTO Check_Consumables // Jump to the label below

// ... more commands ...

LABEL Check_Consumables
LOG INFO "Checking propellant levels."
// ... fuel checking logic ...

GOTO <label_name>

Detailed Explanation: Causes an immediate, unconditional jump in script execution to the command immediately following the specified LABEL. Overuse can lead to "spaghetti code", making scripts difficult to understand, debug, and verify. Its use should generally be restricted to:

  1. Jumping to a common error handling routine at the end of a script.
  2. Implementing simple state machine logic where transitions jump to labeled states (though CALL or more structured logic is often better).
  3. Breaking out of deeply nested loops/conditionals in languages lacking specific break statements (though SCLAM structure should ideally avoid excessive nesting).

Parameters:

  • label_name (String): The name of the target LABEL defined elsewhere in the script.

Example (Jump to Error Handler):

LOG INFO "Starting critical sequence."
CALL "Step1_Critical.sclam"
IF LAST_COMMAND_STATUS != SUCCESS THEN GOTO Handle_Critical_Failure ENDIF
CALL "Step2_Critical.sclam"
IF LAST_COMMAND_STATUS != SUCCESS THEN GOTO Handle_Critical_Failure ENDIF
LOG INFO "Critical sequence complete."
GOTO End_Script // Skip error handler

LABEL Handle_Critical_Failure
LOG CRITICAL "Failure during critical sequence! Attempting safe state."
CALL "Enter_Safe_Mode.sclam"

LABEL End_Script
LOG INFO "Script finished."

Explanation: Uses GOTO to jump to a common failure handling section if any critical step fails, and another GOTO to skip that handler if successful.

CALL <script_name.sclam>

Detailed Explanation: Transfers execution control to another SCLAM script file, treating it like a subroutine or function call. When the called script completes (via reaching its end or executing a RETURN), execution resumes at the line immediately following the CALL in the original script. This is essential for modularity, code reuse, and breaking down complex missions into manageable procedures (e.g., PreFlight_Checklist.sclam, Execute_Hohmann_Transfer.sclam, Standard_Docking_Approach.sclam). Called scripts operate within their own variable scope unless a mechanism for passing parameters or accessing global state is implemented.

Parameters:

  • script_name.sclam (String): The filename of the SCLAM script to execute. Path may be relative or absolute depending on implementation.

Returns Status: The LAST_COMMAND_STATUS variable in the calling script is typically updated to reflect the final status returned by the called script (e.g., via its own last command or an explicit RETURN value).

Example 1 (Checklist):

LOG INFO "Performing pre-landing checklist."
CALL "Lunar_Landing_Checklist.sclam"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO "Landing checklist passed."
    VTOL_LAND // Proceed with landing
ELSE
    LOG ERROR "Landing checklist failed! Aborting landing attempt."
ENDIF

Explanation: Executes a standard checklist script before committing to a critical landing operation.

Example 2 (Standard Maneuver):

LOG INFO "Executing standard station-keeping burn."
VAR BurnTargetVector = CalculateStationKeepingDeltaV() // Conceptual
// Assume Execute_Standard_Burn.sclam takes DeltaV as input (implementation detail)
CALL "Execute_Standard_Burn.sclam" BurnTargetVector
// Check status

Explanation: Calls a reusable script to perform a common type of maneuver, potentially passing necessary parameters (parameter passing mechanism depends on implementation).

RETURN [value]

Detailed Explanation: Terminates the execution of the *current* SCLAM script. If this script was invoked via CALL, control returns to the calling script. If it's the main script being executed, this command typically ends the overall sequence execution. An optional value can be returned, which often updates the LAST_COMMAND_STATUS in the calling context or can be used to pass back results (implementation specific).

Parameters:

  • value (Any, Optional): A status code (e.g., SUCCESS, FAILURE, custom error code) or data value to return.

Example (Success Return):

// Inside Configure_Payload.sclam
LOG INFO "Configuring Payload X."
SYSTEM_SET "PayloadX" MODE "Observation"
IF LAST_COMMAND_STATUS != SUCCESS THEN RETURN "CONFIG_FAILED" ENDIF
LOG INFO "Payload X configured."
RETURN "SUCCESS" // Indicate successful completion

Example (Early Exit on Failure):

// Inside Perform_Critical_Task.sclam
VAR PrereqOK = GET_STATE SYSTEM_STATUS "CriticalSystem" == "NOMINAL"
IF PrereqOK == FALSE THEN
    LOG ERROR "Prerequisite CriticalSystem not nominal!"
    RETURN "FAILED_PREREQUISITE" // Exit script immediately with failure status
ENDIF
// ... rest of critical task ...
RETURN "SUCCESS"

LOG <level> <message_string | variable>

Detailed Explanation: Writes a message to the spacecraft's event log or telemetry stream. This is the primary mechanism for recording script progress, decisions, state information, warnings, and errors for ground monitoring and post-flight analysis. Using appropriate log levels allows filtering messages based on severity.

Parameters:

  • level (Enum): Log severity:
    • DEBUG: Detailed information useful for debugging (e.g., variable values, fine steps). Often filtered out in nominal operations.
    • INFO: Informational messages about nominal progress (e.g., starting a phase, command completion). Standard level for monitoring.
    • WARN: Indicates a potential issue or off-nominal condition that doesn't (yet) constitute an error (e.g., temperature slightly high, fuel moderately low, constraint margin decreasing).
    • ERROR: Indicates a definite error occurred during script execution or command processing (e.g., command failed, checklist item failed, unexpected state).
    • CRITICAL: Indicates a severe error potentially jeopardizing the mission or vehicle safety (e.g., major system failure, abort condition met).
  • message_string | variable (String | Any): The message content. Can be a literal string or a variable (implicitly converted to string). String concatenation ("Text: " + Variable) may be supported.

Example:

VAR Temp = GET_STATE BATTERY_TEMP_K "MainBus"
LOG INFO "Starting maneuver."
LOG DEBUG "Current battery temperature: " + Temp + " K"
IF Temp > 310.0 THEN
    LOG WARN "Battery temperature elevated."
ENDIF
LOG ERROR "Failed to deploy landing gear. Status: " + GearStatus

3.2. Propulsion Commands

ENGINE_MAIN <throttle_percent | thrust_N> <duration_S | target_deltaV_mps>

Detailed Explanation: Commands the main rocket engine(s) (e.g., Kerosene/LOX bipropellant). This is used for large orbital changes, interplanetary injection/capture burns, and the final ascent phase. The command can specify either a desired throttle level (as a percentage of maximum rated thrust) and a fixed duration, OR a target total Delta-V (change in velocity). If Delta-V is targeted, the GNC system calculates the required burn duration and attitude based on the current vehicle mass (which changes as propellant is consumed) and engine performance characteristics (Isp, thrust). This is an asynchronous command, often lasting minutes or longer. Precise start/stop and performance depend heavily on the engine controller and GNC implementation. Consumes PROPELLANT_KEROSENE_KG and PROPELLANT_LOX_KG.

Parameters:

  • throttle_percent | thrust_N (Float): Throttle setting (0.0-100.0) OR specific thrust target in Newtons (if engine is throttleable to specific thrust levels).
  • duration_S | target_deltaV_mps (Float): Burn duration in seconds OR target Delta-V magnitude in m/s. The GNC determines the burn vector direction based on the maneuver goal (e.g., prograde for orbit raising).

Returns Status: EXECUTING on successful ignition and start. SUCCESS upon achieving target duration or Delta-V within tolerance. FAILED_PRECONDITION if GNC estimates insufficient fuel/power, or engine health check fails. FAILED_EXECUTION if engine fails to ignite, shuts down prematurely, performance is significantly off-nominal, or guidance diverges.

Example 1 (Fixed Duration Burn):

LOG INFO "Starting fixed duration main engine burn (e.g., for TLI stage)."
ENGINE_MAIN 95.0 450.0 // 95% throttle for 450 seconds
WAIT_UNTIL "GET_STATE ENGINE_MAIN_STATUS == OFF"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    VAR DeltaVAchieved = GET_STATE LAST_MANEUVER_DV_ACHIEVED_MPS
    LOG INFO "Fixed duration burn complete. DeltaV achieved: " + DeltaVAchieved + " m/s."
ELSE
    LOG ERROR "Main engine burn failed!"
ENDIF

Explanation: Commands a burn for a set time at a specific throttle, often used when the exact Delta-V is less critical or managed by staging.

Example 2 (Target Delta-V Burn):

LOG INFO "Performing orbit insertion burn targeting 850.5 m/s Delta-V."
NAV_MANEUVER BURN [850.5, 0.0, 0.0] "LVLH" // Alternative using NAV_MANEUVER for vector control
// OR using ENGINE_MAIN for magnitude targeting if GNC handles direction:
// ENGINE_MAIN 850.5 // Target Delta-V magnitude
WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE OR GET_STATE MANEUVER_STATUS == FAILED"
// Check status

Explanation: Commands the GNC to achieve a specific change in velocity, automatically managing burn time and potentially throttle based on real-time navigation and mass estimates. (Note: NAV_MANEUVER BURN might be preferred for precise vector control).

ENGINE_RCS <thruster_id | group_name> <thrust_N | duty_cycle_percent> <duration_S>

Detailed Explanation: Commands individual Reaction Control System (RCS) thrusters or predefined groups. RCS provides low thrust, suitable for precise attitude control, small translational adjustments (station-keeping, docking), and propellant settling (ullage). Commands can specify a thrust level (if thrusters are throttleable, rare for small RCS) or, more commonly, a duty cycle (percentage of time the thruster is active within a control cycle) for pulsed operation over the specified duration. Consumes PROPELLANT_RCS_KG. GNC uses current mass/inertia for attitude control calculations involving RCS.

Parameters:

  • thruster_id | group_name (String): Identifier like "Thruster_X_Plus_1" or group like "YAW_JETS", "TRANSLATE_FORWARD". Groups must be predefined in flight software.
  • thrust_N | duty_cycle_percent (Float): Specific thrust in Newtons (if applicable) OR duty cycle (0-100).
  • duration_S (Float): Duration for which the pulse/firing command is active.

Returns Status: SUCCESS if the command is accepted by the RCS controller. FAILED_PRECONDITION if the specified thruster/group is disabled, faulted, or out of fuel. INVALID_PARAMETER for bad ID or values. *Note: SUCCESS only means the command was sent; confirmation of actual firing might require checking system telemetry.*

Example 1 (Attitude Correction Pulse):

LOG DEBUG "Applying small positive pitch correction pulse."
ENGINE_RCS "PITCH_UP_JETS" 80.0 0.05 // Fire pitch-up group at 80% duty cycle for 50ms

Explanation: Short, pulsed firing typical for fine attitude adjustments.

Example 2 (Translation Maneuver):

LOG INFO "Performing small forward translation for docking approach."
ENGINE_RCS "TRANSLATE_X_PLUS" 10.0 2.5 // Fire +X thrusters at 10N (if possible) for 2.5s

Explanation: Longer duration firing for a small change in velocity along one axis.

Example 3 (Ullage):

LOG INFO "Performing ullage burn to settle main engine propellants."
ENGINE_RCS "ULLAGE_GROUP" 100.0 1.0 // Fire dedicated ullage thrusters (or forward group) fully for 1s
WAIT 1.0

Explanation: Short burst to push propellants to tank bottoms before main engine ignition.

ENGINE_TURBINE <engine_id | "ALL" | "VTOL_GROUP" | "CRUISE_GROUP"> <throttle_percent | mode> [duration_S]

Detailed Explanation: Controls the air-breathing turbine engines. These are essential for VTOL lift (using directed thrust) and for atmospheric flight segments (acting like jet engines). Requires atmospheric pressure/oxygen to operate. Consumes PROPELLANT_JET_KG. Allows setting specific throttle percentages or predefined operational modes.

Parameters:

  • engine_id | "ALL" | group (String): Specify target: individual engine ("Turbine_Left"), all turbines, or functional groups ("VTOL_GROUP", "CRUISE_GROUP").
  • throttle_percent | mode (Float | Enum): Throttle (0-100) applied to the relevant mode OR a specific mode:
    • OFF: Engine shutdown.
    • IDLE: Engine running at minimum self-sustaining level.
    • VTOL_LIFT: Configure for maximum vertical thrust (throttle likely managed by VTOL controller).
    • AERO_THRUST: Configure for forward thrust for atmospheric flight (throttle percentage applies here).
  • duration_S (Float, Optional): Hold state for this duration; otherwise holds indefinitely.

Returns Status: SUCCESS, FAILED_PRECONDITION (e.g., engine off, faulted, no air), INVALID_PARAMETER.

Example 1 (VTOL Startup):

LOG INFO "Starting VTOL turbines."
SYSTEM_POWER ENGINE_TURBINE "VTOL_GROUP" ON
ENGINE_TURBINE "VTOL_GROUP" IDLE // Start and idle VTOL turbines
WAIT_UNTIL "GET_STATE ENGINE_TURBINE_STATUS VTOL_GROUP == IDLE"
LOG INFO "VTOL Turbines at idle."

Example 2 (Cruise Throttle):

LOG INFO "Setting cruise turbines to 75% throttle for acceleration."
SET_PROP_MODE JET
ENGINE_TURBINE "CRUISE_GROUP" 75.0

Example 3 (Shutdown):

LOG INFO "Shutting down all turbine engines before rocket transition."
ENGINE_TURBINE "ALL" OFF
WAIT_UNTIL "GET_STATE ENGINE_TURBINE_STATUS ALL == OFF"
SYSTEM_POWER ENGINE_TURBINE "ALL" OFF

ENGINE_PROPELLER <prop_id | "ALL"> <rpm | mode> [duration_S]

Detailed Explanation: Controls the wing-mounted electric propellers used primarily for stability and fine attitude control during low-speed VTOL phases. They consume electrical power from the batteries/power bus. Allows setting specific RPMs or engaging an automatic stabilization mode where the flight controller modulates RPM for stability.

Parameters:

  • prop_id | "ALL" (String): Target propeller ("Prop_Left_Inboard", "ALL").
  • rpm | mode (Float | Enum): Target Revolutions Per Minute OR operational mode:
    • OFF: Propeller stopped and feathered/braked.
    • STABILIZE_AUTO: Flight controller manages RPM for stability.
    • MANUAL_RPM: Set a specific RPM target.
  • duration_S (Float, Optional): Duration to hold the state.

Returns Status: SUCCESS, FAILED_PRECONDITION (e.g., unpowered, faulted), INVALID_PARAMETER.

Example 1 (VTOL Stabilization):

LOG INFO "Engaging propellers for VTOL landing stabilization."
SYSTEM_POWER ENGINE_PROPELLER "ALL" ON
ENGINE_PROPELLER "ALL" STABILIZE_AUTO

Example 2 (Manual Control - Test):

LOG DEBUG "Setting left outer propeller to 500 RPM for test."
ENGINE_PROPELLER "Prop_Left_Outer" MANUAL_RPM 500.0
WAIT 10.0
ENGINE_PROPELLER "Prop_Left_Outer" OFF

ENGINE_SCRAMJET <engine_id | "ALL"> <throttle_percent | mode> [duration_S]

Detailed Explanation: Controls the SCRAMJET (Supersonic Combustion Ramjet) engine(s). These are air-breathing engines designed for hypersonic flight (typically Mach 5+) within the atmosphere. They require high-velocity airflow, initiated via FLIGHT_TRANSITION JET_TO_SCRAMJET. Control involves managing fuel flow (PROPELLANT_SCRAMJET_FUEL_KG) and potentially inlet/nozzle geometry to maintain combustion in the supersonic airflow. Throttle percentage is relative, as absolute thrust depends heavily on flight conditions (Mach, altitude, dynamic pressure, temperature). Asynchronous control.

Parameters:

  • engine_id | "ALL" (String): Target SCRAMJET engine(s).
  • throttle_percent | mode (Float | Enum): Throttle (0-100, relative to max thrust at current conditions) OR operational mode:
    • OFF: Engine inactive, fuel off, potentially inlet closed.
    • ACTIVE: Engine operating, fuel flowing, combustion active (throttle likely managed by GNC based on speed/altitude targets).
  • duration_S (Float, Optional): Duration to maintain the commanded state. If omitted, holds until changed.

Returns Status: SUCCESS, FAILED_PRECONDITION (engine off, faulted, flight conditions outside operational envelope - e.g., Mach too low/high, dynamic pressure too low/high), INVALID_PARAMETER.

Example 1 (Activation):

// After successful JET_TO_SCRAMJET transition...
LOG INFO "Activating SCRAMJET engines."
ENGINE_SCRAMJET "ALL" ACTIVE
WAIT 2.0 // Allow stabilization
IF GET_STATE ENGINE_SCRAMJET_STATUS ALL != "ACTIVE" THEN
    LOG ERROR "SCRAMJET failed to activate!"
ENDIF

Example 2 (Throttle Adjustment):

LOG INFO "Commanding SCRAMJET throttle to 90% for acceleration phase."
ENGINE_SCRAMJET "ALL" 90.0

Example 3 (Shutdown):

LOG INFO "Shutting down SCRAMJET engines before rocket transition."
ENGINE_SCRAMJET "ALL" OFF
WAIT_UNTIL "GET_STATE ENGINE_SCRAMJET_STATUS ALL == OFF"
LOG INFO "SCRAMJET engines off."

SET_PROP_MODE <mode>

Detailed Explanation: Selects the primary propulsion system and associated control strategy for the GNC and ACS. This is crucial as it tells the flight computer which actuators (Turbines, SCRAMJETs, Rockets, RCS, Propellers, Aero Surfaces) to use for achieving thrust and attitude control targets set by commands like AERO_FLY, ORIENT, HOLD_ATTITUDE. The selection must match the current flight phase and vehicle capabilities.

Parameters:

  • mode (Enum): Propulsion strategy:
    • ROCKET: Main rocket + RCS (Space).
    • RCS: RCS only (Space, fine control).
    • VTOL_ASSISTED: Turbines (lift) + Propellers (stability) + RCS/Aero (attitude) (Low altitude/speed).
    • JET: Turbines (thrust) + Aero/RCS (attitude) (Atmospheric flight, subsonic/supersonic).
    • SCRAMJET: SCRAMJETs (thrust) + Aero/RCS (attitude) (Hypersonic atmospheric flight).
    • HYBRID_AERO_ROCKET: Turbines + Rockets (thrust) + Aero/RCS (attitude) (Trans-atmospheric ascent).

Returns Status: SUCCESS, FAILED_PRECONDITION (e.g., trying to set SCRAMJET mode at low speed, ROCKET mode in dense atmosphere without thermal protection).

Example 1 (Setting for Jet Cruise):

LOG INFO "Configuring for aerodynamic cruise."
SET_PROP_MODE JET
SET_ATTITUDE_MODE AERO_STABLE

Example 2 (Setting for SCRAMJET phase):

LOG INFO "Configuring for SCRAMJET powered flight."
SET_PROP_MODE SCRAMJET
SET_ATTITUDE_MODE AERO_STABLE // Still using aero/RCS for attitude

Example 3 (Setting for Space Maneuvers):

LOG INFO "Configuring for orbital maneuvers."
SET_PROP_MODE ROCKET // Or RCS if only small adjustments needed
SET_ATTITUDE_MODE INERTIAL_HOLD // Or specific pointing mode

3.3. Attitude Control Commands

SET_ATTITUDE_MODE <mode> [parameters...]

Detailed Explanation: Defines the target attitude reference and control law for the Attitude Control System (ACS). The ACS continuously works to align the spacecraft according to the selected mode, using the actuators specified by SET_PROP_MODE and accounting for current vehicle mass. Selecting the correct mode is vital for thermal control (pointing radiators/sensitive parts), power generation (pointing solar arrays), communications (pointing antennas), navigation (sensor pointing), and maneuver execution (aligning thrust vector).

Parameters:

  • mode (Enum): Attitude control mode:
    • INERTIAL_HOLD: Maintain fixed orientation in inertial space (e.g., for telescope observations).
    • LVLH: Align with orbit frame (Z-nadir, X~velocity). Standard for Earth orbit.
    • TARGET_RELATIVE <target_name>: Point relative to a target (e.g., +X towards ISS for rendezvous). Requires target state.
    • SUN_POINT: Point specified axis (default +X) to Sun (power/thermal).
    • NADIR_POINT: Point specified axis (default +Z) to central body (Earth/Moon/Mars observation).
    • PROGRADE: Align +X with the orbital velocity vector (inertial frame).
    • RETROGRADE: Align +X opposite the orbital velocity vector.
    • BODY_HOLD: Maintain fixed orientation relative to body axes (rarely used).
    • AERO_STABLE: Maintain stable aerodynamic attitude (e.g., specific AoA) using aero surfaces/RCS/turbines. For atmospheric flight.
    • MANUAL_RCS/MANUAL_AERO: Disable automatic ACS loops for direct actuator commands. Use with extreme caution.
  • parameters... (Varies): e.g., <target_name> for TARGET_RELATIVE.

Returns Status: SUCCESS, FAILED_PRECONDITION.

Example 1 (LVLH):

LOG INFO "Setting attitude to LVLH."
SET_ATTITUDE_MODE LVLH
HOLD_ATTITUDE

Example 2 (Sun Pointing for Power):

LOG INFO "Orienting solar arrays towards Sun."
SET_ATTITUDE_MODE SUN_POINT // Assumes ACS knows which axis points to arrays
HOLD_ATTITUDE
// Alternative: Use ORIENT command for specific axis
// ORIENT "SOLAR_PANEL_NORMAL" SUN SUN_CI

Example 3 (Aero Stable):

LOG INFO "Setting attitude mode for atmospheric flight."
SET_ATTITUDE_MODE AERO_STABLE
// GNC now controls AoA/Sideslip using aero surfaces/RCS/turbines

ORIENT <body_axis> <target_vector | celestial_object | target_name> <frame> [tolerance_deg]

Detailed Explanation: Commands the ACS to rotate the spacecraft to point a specific axis fixed in the spacecraft's body frame towards a specified target vector or object within a given coordinate frame. The ACS calculates and executes the required rotation sequence using the active propulsion mode actuators (RCS, potentially aero surfaces). This is an asynchronous command. The body_axis can be a principal axis (+X, -Z) or a predefined vector associated with hardware like an antenna or sensor (HGA_BORESIGHT, SOLAR_PANEL_NORMAL).

Parameters:

  • body_axis (String): Axis/vector fixed in the BODY frame to be pointed.
  • target... (String | Vector): Target direction (e.g., "SUN", "EARTH", "ISS", "VELOCITY_VECTOR", [x,y,z]).
  • frame (Enum): Frame in which the target is defined (e.g., SUN_CI, EARTH_CI, LVLH, TARGET_RELATIVE "ISS").
  • tolerance_deg (Float, Optional): Allowed final pointing error in degrees.

Returns Status: EXECUTING, SUCCESS, FAILED_EXECUTION (e.g., unable to reach target due to constraints or failures).

Example 1 (Antenna Pointing):

LOG INFO "Pointing High Gain Antenna towards Earth."
ORIENT "HGA_BORESIGHT" EARTH EARTH_CI 0.2
WAIT_UNTIL "GET_STATE POINTING_STATUS == STABLE"
LOG INFO "HGA pointing stable."

Example 2 (Velocity Alignment):

LOG INFO "Aligning +X axis with prograde velocity vector for burn."
ORIENT "+X" VELOCITY_VECTOR EARTH_CI 0.5 // Point +X along velocity in ECI
// Alternative, often simpler:
// SET_ATTITUDE_MODE PROGRADE
// HOLD_ATTITUDE
WAIT_UNTIL "GET_STATE ATTITUDE_ERROR_DEG < 0.5"
LOG INFO "Aligned for prograde burn."

ROTATE <axis> <angle_deg> <rate_deg_s>

Detailed Explanation: Commands a simple rotation about one of the principal body axes (PITCH, YAW, ROLL) by a specified relative angle. The rotation is performed at a maximum angular rate. Useful for specific maneuvers like thermal rolls or small alignment tweaks. Asynchronous. GNC accounts for current mass/inertia.

Parameters:

  • axis (Enum): PITCH, YAW, ROLL. Defined by right-hand rule around body axes.
  • angle_deg (Float): The relative angle to rotate in degrees. Sign determines direction.
  • rate_deg_s (Float): Maximum angular rate allowed during rotation (must be positive).

Returns Status: EXECUTING, SUCCESS, FAILED_EXECUTION.

Example 1 (Thermal Roll - Conceptual):

LOG INFO "Starting slow thermal roll (1 deg/min)."
ROTATE ROLL 360.0 (1.0/60.0) // Rotate 360 deg about Roll axis at ~0.0167 deg/s
// Note: Real thermal rolls often use continuous rate control or a dedicated mode.
// This command might complete after 360 deg. Check implementation specifics.

Example 2 (Small Adjustment):

LOG INFO "Performing small pitch adjustment (-5 degrees)."
ROTATE PITCH -5.0 0.2 // Pitch down 5 deg at 0.2 deg/s
WAIT_UNTIL "GET_STATE ROTATION_STATUS == COMPLETE"
LOG INFO "Pitch adjustment complete."

HOLD_ATTITUDE

Detailed Explanation: Explicitly engages the Attitude Control System (ACS) to actively control the spacecraft's orientation according to the currently set attitude mode (SET_ATTITUDE_MODE). If the ACS was previously inactive (e.g., in MANUAL_RCS mode or after KILL_ROTATION without a subsequent pointing command), this command activates it. If already active, it may simply confirm the intent to continue holding the target attitude.

Returns Status: SUCCESS if ACS is active or engages successfully. FAILED_PRECONDITION if ACS unavailable or no valid attitude mode is set.

Example:

// After completing a manual RCS maneuver...
LOG INFO "Finished manual RCS pulses. Re-engaging LVLH hold."
SET_ATTITUDE_MODE LVLH // Ensure target mode is correct
HOLD_ATTITUDE

KILL_ROTATION [tolerance_deg_s]

Detailed Explanation: Commands the ACS to actively counteract any existing angular velocity about all body axes, bringing the rotation rates below a specified tolerance. This is used to stabilize the spacecraft after maneuvers, before precision pointing, or after unexpected disturbances. Uses appropriate actuators (RCS, potentially aero surfaces in atmosphere).

Parameters:

  • tolerance_deg_s (Float, Optional): The target maximum residual angular rate magnitude in deg/s (e.g., 0.01). Uses a system default if omitted.

Returns Status: EXECUTING while damping rates. SUCCESS when rates are within tolerance. FAILED_EXECUTION if unable to stabilize (e.g., persistent disturbance, actuator failure, control instability).

Example:

LOG INFO "Damping residual body rates after maneuver."
KILL_ROTATION 0.01 // Damp rates to below 0.01 deg/s
WAIT_UNTIL "GET_STATE ANGULAR_RATE_MAGNITUDE < 0.01"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO "Spacecraft rotation stabilized."
ELSE
    LOG ERROR "Failed to stabilize rotation!"
ENDIF

3.4. Navigation & Maneuvering Commands (Space)

SET_NAV_FRAME <frame_name>

Detailed Explanation: Sets the default coordinate frame used for interpreting vector quantities (like delta-V vectors, position vectors) in subsequent `NAV_MANEUVER` commands and potentially for state reporting via `GET_STATE`. Choosing the correct frame is essential for ensuring maneuvers are calculated and executed correctly relative to the central body or target.

Parameters:

  • frame_name (Enum): Navigation coordinate frame (e.g., `EARTH_CI`, `MOON_CI`, `SUN_CI`, `ISS_RELATIVE`, `MARS_CF`).

Returns Status: `SUCCESS` if frame is valid, `INVALID_PARAMETER` otherwise.

Example 1 (Earth Orbit Ops):

LOG INFO "Setting navigation frame to Earth Centered Inertial."
SET_NAV_FRAME EARTH_CI

Example 2 (Lunar Approach):

LOG INFO "Approaching Moon, setting frame to Moon Centered Inertial."
SET_NAV_FRAME MOON_CI

Example 3 (Rendezvous):

LOG INFO "Beginning rendezvous phase, setting frame relative to target 'ISS'."
SET_NAV_FRAME TARGET_RELATIVE "ISS"

NAV_MANEUVER <type> <parameters...>

Detailed Explanation: This is a high-level command invoking the GNC system to execute complex orbital maneuvers. The GNC handles trajectory calculation, burn timing, attitude alignment for thrust, engine control, and guidance during the burn(s), all while accounting for current vehicle mass and propellant levels. GNC must perform feasibility checks (propellant, power, timing) before initiating the maneuver. These are typically asynchronous, long-duration commands.

Parameters:

  • type (Enum): The type of maneuver.
  • parameters... (Varies): Specific parameters for each type:
    • BURN <deltaV_vector_mps> <frame>: Execute a single burn defined by a delta-V vector [dVx, dVy, dVz] in the specified frame. GNC calculates burn duration/attitude.
    • CIRCULARIZE <apoapsis|periapsis>: Perform burn(s) at the next specified apsis to make the orbit circular. GNC calculates the required burn.
    • CHANGE_ORBIT <apo_m> <peri_m> [inc_deg] [raan_deg] [aop_deg]: Achieve target orbital elements (Apoapsis, Periapsis, Inclination, Right Ascension of Ascending Node, Argument of Periapsis). Use null to keep an element unchanged. Requires GNC planning (e.g., Hohmann transfer).
    • PHASE <target_mean_anomaly_deg | target_true_anomaly_deg> <target_orbit_time_utc>: Adjust orbit slightly to arrive at a specific point in the orbit at a target time (for rendezvous phasing).
    • TLI <target_c3_energy | target_vector>: Trans-Lunar Injection burn. Target C3 (km²/s²) defines escape energy, or provide specific escape vector.
    • LOI <target_apo_m> <target_peri_m>: Lunar Orbit Insertion burn to achieve a target lunar orbit.
    • TEI <target_escape_c3 | target_vector>: Trans-Earth Injection burn from Moon orbit.
    • TMI <target_c3_energy | target_vector>: Trans-Mars Injection burn.
    • MOI <target_apo_m> <target_peri_m>: Mars Orbit Insertion burn.
    • GRAVITY_ASSIST <body_name> <target_escape_vector | target_orbit_params> <frame>: Sequence of maneuvers (usually small Trajectory Correction Maneuvers - TCMs) to precisely target a gravity assist flyby of <body_name>.
    • DEORBIT <target_lat_deg> <target_lon_deg> [entry_interface_alt_m] : Calculate and execute the deorbit burn targeting atmospheric entry over specific coordinates. entry_interface_alt_m defaults if omitted (e.g., 120000m for Earth).

Returns Status: EXECUTING when started, SUCCESS on nominal completion, FAILED_PRECONDITION (insufficient consumables, invalid target orbit), FAILED_EXECUTION (guidance failure, engine failure).

Example 1 (Change Orbit - Hohmann):

LOG INFO "Raising orbit to 500km circular via Hohmann transfer."
SET_NAV_FRAME EARTH_CI
// GNC calculates the two burns needed for Hohmann transfer
NAV_MANEUVER CHANGE_ORBIT 500000.0 500000.0 null null null
WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE"
// Check status

Explanation: Commands a standard Hohmann transfer to a circular 500km altitude orbit. GNC handles the planning and execution of both burns.

Example 2 (Deorbit):

LOG INFO "Initiating deorbit burn targeting KSC."
NAV_MANEUVER DEORBIT 28.60 -80.65 120000 // Lat/Lon for KSC area, 120km EI
WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE"
// Check status

Explanation: Calculates and executes the single burn needed to lower periapsis for atmospheric entry over the specified coordinates.

Example 3 (TLI):

LOG INFO "Initiating Trans-Lunar Injection maneuver."
VAR TargetC3 = 1.5 // Target C3 energy in km^2/s^2
// GNC performs internal check for Kerosene/LOX/Power before starting
NAV_MANEUVER TLI TargetC3
IF LAST_COMMAND_STATUS == FAILED_PRECONDITION THEN
    LOG ERROR "TLI Pre-check failed! Insufficient consumables."
ELSE
    WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE"
    // Check final status
ENDIF

Explanation: Executes the large burn required to leave Earth orbit and head towards the Moon, targeting a specific escape energy.

Example 4 (Vector Burn):

LOG INFO "Performing trajectory correction burn."
VAR BurnVector = [-2.1, 0.5, 0.1] // Target dV in m/s [x,y,z]
SET_NAV_FRAME SUN_CI
NAV_MANEUVER BURN BurnVector SUN_CI
WAIT_UNTIL "GET_STATE MANEUVER_STATUS == COMPLETE"
// Check status

Explanation: Executes a burn to achieve a specific delta-V vector, often used for mid-course corrections during interplanetary travel.

NAV_RENDEZVOUS <target_name> <approach_profile> <final_distance_m> [final_axis_alignment]

Detailed Explanation: Commands an automated rendezvous sequence to approach a specified target in space, following a defined profile (e.g., V-bar hops for safety along the velocity vector, R-bar for approaches along the radial vector). Requires relative navigation sensors and target state data. The GNC executes a series of burns (often using RCS) to precisely control the relative trajectory and reach the specified standoff distance safely. Checks RCS fuel margin. Asynchronous.

Parameters:

  • target_name (String): Identifier of the target vehicle/station (e.g., `"ISS"`).
  • approach_profile (Enum): Strategy (`VBAR_HOP`, `RBAR_DIRECT`, `AUTO_GUIDED`).
  • final_distance_m (Float): Desired final separation distance (standoff distance).
  • final_axis_alignment (String, Optional): Desired relative orientation at standoff (e.g., `"+X_TOWARDS_TARGET"`, `"ALIGN_DOCKING_AXES"`).

Returns Status: EXECUTING, SUCCESS (stable standoff achieved), `FAILED_PRECONDITION` (target state unknown, insufficient RCS fuel), `FAILED_EXECUTION` (lost target lock, guidance divergence, collision risk detected).

Example 1 (V-Bar Hop):

LOG INFO "Initiating rendezvous with ISS, V-bar hop profile, stop at 150m."
SET_NAV_FRAME TARGET_RELATIVE "ISS" // Set context for relative maneuvers
NAV_RENDEZVOUS "ISS" "VBAR_HOP" 150.0 "+X_TOWARDS_TARGET"
WAIT_UNTIL "GET_STATE RENDEZVOUS_STATUS == STANDOFF_STABLE"
// Check status

Explanation: Uses a common, safe approach method involving hops along the target's velocity vector.

Example 2 (R-Bar Approach):

LOG INFO "Initiating R-bar approach to TargetSat, stop at 50m."
NAV_RENDEZVOUS "TargetSat" "RBAR_DIRECT" 50.0
WAIT_UNTIL "GET_STATE RENDEZVOUS_STATUS == STANDOFF_STABLE"
// Check status

Explanation: Commands a direct approach along the radial direction (towards/away from the central body relative to the target).

NAV_DOCK <target_name> <port_id> [approach_axis]

Detailed Explanation: Commands the final, precision docking maneuver with a specified port on a target. Requires high-precision sensors (vision systems, LIDAR), fine RCS control, and potentially knowledge of the target port's state. GNC manages the slow, controlled approach along the docking axis, monitoring alignment and closure rate, and commanding contact and capture mechanisms. Checks RCS fuel and power. Extremely critical, asynchronous operation.

Parameters:

  • target_name (String): Target vehicle identifier.
  • port_id (String): Specific docking port identifier (e.g., \"PMA-2\", \"IDA-3\").
  • approach_axis (String, Optional): Body axis to align with the docking axis (e.g., \"+X\").

Returns Status: EXECUTING, SUCCESS (capture confirmed), FAILED_PRECONDITION (not at stable standoff, port unavailable, insufficient fuel/power), FAILED_EXECUTION (misalignment tolerance exceeded, high closure rate, contact anomaly, abort triggered by sensors).

Example:

LOG INFO \"Initiating final docking approach to ISS port PMA-2.\"
// Assumes already at stable standoff after NAV_RENDEZVOUS
NAV_DOCK \"ISS\" \"PMA-2\" \"+X\"
WAIT_UNTIL \"GET_STATE DOCKING_STATUS == HARD_CAPTURE\"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO \"Docking successful! Hard capture confirmed.\"
    SYSTEM_SET \"Docking_Mechanism\" STATE \"LATCHED\"
    SET_POWER_MODE DOCKED_ISS_POWER
ELSE
    LOG CRITICAL \"Docking failed! Status: \" + GET_STATE DOCKING_STATUS
    CALL \"Handle_Docking_Abort.sclam\" // Back away procedure
ENDIF

Explanation: Executes the final approach and capture sequence, waits for confirmation of a hard dock, and handles success or failure.

NAV_UNDOCK <port_id> <separation_distance_m> [separation_axis]

Detailed Explanation: Commands an automated undocking sequence. Includes commanding physical latch release, performing a small initial separation push (often spring-loaded or via RCS), and then maneuvering the spacecraft to a specified safe distance along a defined axis relative to the port. Checks RCS fuel and power. Asynchronous.

Parameters:

  • port_id (String): Identifier of the port currently docked to.
  • separation_distance_m (Float): Target separation distance after departure maneuvers.
  • separation_axis (String, Optional): Axis for initial departure relative to the port (e.g., \"-X\" for backing straight out).

Returns Status: EXECUTING, SUCCESS (separated and clear), FAILED_PRECONDITION (latches stuck), FAILED_EXECUTION (separation anomaly, recontact risk).

Example:

VAR CurrentPortID = GET_STATE DOCKED_PORT_ID
LOG INFO \"Preparing to undock from port \" + CurrentPortID
SYSTEM_SET \"Docking_Mechanism\" STATE \"RELEASE\" // Command latch release
WAIT_UNTIL \"GET_STATE SYSTEM_STATUS Docking_Mechanism == RELEASED\"
IF LAST_COMMAND_STATUS != SUCCESS THEN
    LOG ERROR \"Failed to release docking latches!\"
    GOTO Handle_Undock_Fail
ENDIF
LOG INFO \"Initiating undocking maneuver, separating 20m along port -X.\"
NAV_UNDOCK CurrentPortID 20.0 \"-X\"
WAIT_UNTIL \"GET_STATE DOCKING_STATUS == SEPARATED_CLEAR\"
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO \"Undocking and initial separation complete.\"
ELSE
    LABEL Handle_Undock_Fail
    LOG ERROR \"Undocking maneuver failed!\"
    // Contingency actions
ENDIF

Explanation: Retrieves the current docked port, commands release, then executes the separation maneuver, waiting for confirmation.


3.5. VTOL & Atmospheric Flight Commands

VTOL_TAKEOFF <target_altitude_m> <ascent_profile> [propeller_mode]

Detailed Explanation: Commands a fully automated vertical takeoff from the ground. The GNC system manages turbine throttle for lift, propeller RPM for stability (if STABILIZE_AUTO), and attitude control using RCS/aero surfaces/differential thrust to achieve the target altitude following the specified ascent profile (trading off ascent rate vs. fuel consumption). Requires ground idle state, passed pre-flight checks, and sufficient Jet Fuel & Battery power. Asynchronous.

Parameters:

  • target_altitude_m (Float): Target altitude Above Ground Level (AGL).
  • ascent_profile (Enum): Predefined profile (MAX_RATE, FUEL_OPTIMAL, STANDARD).
  • propeller_mode (Enum, Optional): STABILIZE_AUTO (default), OFF.

Returns Status: EXECUTING, SUCCESS (reached target altitude and stabilized), FAILED_PRECONDITION (insufficient fuel/power), FAILED_EXECUTION (e.g., engine failure, instability, ground proximity issue).

Example 1 (Standard Takeoff):

LOG INFO "Commanding VTOL takeoff to 1000m AGL, standard profile."
SET_PROP_MODE VTOL_ASSISTED
ENGINE_TURBINE "VTOL_GROUP" IDLE // Ensure turbines ready
ENGINE_PROPELLER "ALL" STABILIZE_AUTO // Ensure props ready
VTOL_TAKEOFF 1000.0 "STANDARD"
WAIT_UNTIL "GET_STATE FLIGHT_MODE == VTOL_HOVER" // Wait until stable at target altitude
// Check status

Explanation: Initiates a standard VTOL climb to 1km AGL.

Example 2 (Takeoff without Props):

LOG INFO "Commanding VTOL takeoff to 500m AGL, MAX_RATE, props off (test)."
SET_PROP_MODE VTOL_ASSISTED // GNC needs to handle stability differently
VTOL_TAKEOFF 500.0 "MAX_RATE" OFF
WAIT_UNTIL "GET_STATE FLIGHT_MODE == VTOL_HOVER"
// Check status - likely less stable

Explanation: Attempts a VTOL takeoff without propeller stabilization, perhaps for testing control authority (potentially risky).

VTOL_LAND <target_lat_deg> <target_lon_deg | pad_id> <descent_profile> [propeller_mode]

Detailed Explanation: Commands a fully automated vertical landing. Requires the vehicle to be in a suitable state (e.g., hovering or slow approach) and requires reliable navigation data (GPS, terrain relative nav) and landing zone assessment (from SENSOR_SCAN or pre-loaded data). GNC manages descent rate, position control, attitude, turbine throttle, and propeller stabilization to achieve a soft touchdown at the target. Checks Jet Fuel & Battery reserves. Asynchronous, critical operation.

Parameters:

  • target_lat_deg (Float): Target latitude.
  • target_lon_deg | pad_id (Float | String): Target longitude OR identifier of a known landing pad.
  • descent_profile (Enum): Predefined profile (STANDARD, SOFT (minimal touchdown speed), FAST, FUEL_OPTIMAL).
  • propeller_mode (Enum, Optional): STABILIZE_AUTO (default), OFF.

Returns Status: EXECUTING, SUCCESS (touchdown confirmed, engines idle), FAILED_PRECONDITION (unsafe LZ, nav not locked), FAILED_EXECUTION.

Example 1 (Landing at Coordinates):

VAR TargetLat = 28.55
VAR TargetLon = -80.60
LOG INFO "Initiating VTOL landing at specified coordinates, standard profile."
SET_PROP_MODE VTOL_ASSISTED
VTOL_LAND TargetLat TargetLon "STANDARD" STABILIZE_AUTO
WAIT_UNTIL "GET_STATE VEHICLE_STATE == LANDED"
// Check status

Explanation: Commands a landing at specific lat/lon coordinates using the standard descent profile.

Example 2 (Landing on Pad after Scan):

LOG INFO "Scanning potential landing zone Pad_B."
SENSOR_SCAN LIDAR LANDING_ZONE "Pad_B" PadB_Data
WAIT_UNTIL "GET_STATE SENSOR_STATUS LIDAR == IDLE"
IF PadB_Data.found == TRUE AND PadB_Data.safety == "SAFE" THEN
    LOG INFO "Pad B confirmed safe. Initiating VTOL landing, soft profile."
    SET_PROP_MODE VTOL_ASSISTED
    VTOL_LAND "Pad_B" "SOFT" // Target the Pad ID
    WAIT_UNTIL "GET_STATE VEHICLE_STATE == LANDED"
    IF LAST_COMMAND_STATUS == SUCCESS THEN
        LOG INFO "Touchdown confirmed on Pad B."
        ENGINE_TURBINE "ALL" OFF
        ENGINE_PROPELLER "ALL" OFF
    ELSE
        LOG ERROR "VTOL Landing on Pad B failed!"
    ENDIF
ELSE
    LOG ERROR "Landing Pad B scan failed or zone unsafe."
    // Abort logic
ENDIF

Explanation: Scans a predefined landing pad, checks safety, then commands a soft landing specifically targeting that pad ID.

VTOL_HOVER [duration_s]

Detailed Explanation: Commands the GNC to maintain the current 3D position (latitude, longitude, altitude AGL) using the VTOL propulsion system (turbines for lift/position, props for stability). Requires VTOL_ASSISTED mode and sufficient fuel/power. Useful for holding position for sensor scans, waiting for clearance, or stabilizing before/after takeoff/landing. Asynchronous.

Parameters:

  • duration_s (Float, Optional): If provided, hover for this time. If omitted, hover indefinitely until overridden by another command (e.g., VTOL_LAND, FLIGHT_TRANSITION).

Returns Status: EXECUTING, SUCCESS (if duration expires), FAILED_PRECONDITION, FAILED_EXECUTION (e.g., unable to hold position due to winds, low fuel).

Example 1 (Timed Hover):

LOG INFO "Hovering at 50m for 60 seconds for final checks."
VTOL_HOVER 60.0
WAIT_UNTIL "GET_STATE FLIGHT_MODE != VTOL_HOVER" // Wait for command completion
LOG INFO "Timed hover complete."

Example 2 (Indefinite Hover before Landing):

LOG INFO "Reached landing approach point, entering hover."
VTOL_HOVER // Hover indefinitely
// ... perform final landing zone scan or wait for clearance ...
// SENSOR_SCAN ...
// IF condition THEN VTOL_LAND ... ENDIF

AERO_LAND <runway_id> <approach_profile> <touchdown_speed_mps>

Detailed Explanation: Commands a conventional runway landing. GNC uses navigation aids (ILS, GPS/RNAV) and aerodynamic controls to follow the specified approach profile (lateral path and glideslope), manages turbine thrust for speed control, executes the flare maneuver, and commands touchdown near the target speed. Requires JET mode, gear down, flaps set. Checks Jet Fuel. Asynchronous.

Parameters:

  • runway_id (String): Arrival runway identifier.
  • approach_profile (Enum): Type of approach (ILS, GPS_RNAV, VISUAL (requires pilot/operator input or advanced vision), AUTO_LAND).
  • touchdown_speed_mps (Float): Target airspeed (m/s) at touchdown.

Returns Status: EXECUTING, SUCCESS (touchdown, rollout started), FAILED_PRECONDITION, FAILED_EXECUTION (unstable approach, missed approach conditions met).

Example:

LOG INFO "Initiating AUTO_LAND sequence for RWY 33."
SYSTEM_DEPLOY LANDING_GEAR
// Set flaps
SET_PROP_MODE JET
SET_ATTITUDE_MODE AERO_STABLE
AERO_LAND "KSC_RWY33" "AUTO_LAND" 80.0 // Target 80 m/s at touchdown
WAIT_UNTIL "GET_STATE VEHICLE_STATE == LANDED"
// Check status, then manage rollout (braking, reverse thrust if available)
SYSTEM_SET "BRAKING_SYSTEM" MODE "AUTO_MAX"

Explanation: Configures for and executes an auto-land sequence, waits until landed, and then applies maximum automated braking.

AERO_FLY <target_waypoint | flight_plan_id> <target_altitude_m> <target_speed_mps | target_mach>

Detailed Explanation: Commands the GNC to navigate the vehicle through the atmosphere using the currently active air-breathing propulsion mode (`JET` or `SCRAMJET`). It manages heading to follow a flight plan or proceed direct to a waypoint, maintains target altitude, and controls speed (either airspeed in m/s or Mach number). Uses aerodynamic surfaces and potentially RCS/thrust vectoring for control. Checks relevant fuel (Jet or SCRAMJET). Asynchronous.

Parameters:

  • target_waypoint | flight_plan_id (String | LatLon): Target `[lat,lon]` OR ID of a stored flight plan.
  • target_altitude_m (Float): Target cruising altitude (e.g., MSL or AGL depending on context).
  • target_speed_mps | target_mach (Float): Target cruising speed (airspeed in m/s or Mach number).

Returns Status: EXECUTING, SUCCESS (final waypoint/plan end reached), FAILED_PRECONDITION, FAILED_EXECUTION (unable to maintain flight path, engine flameout).

Example 1 (Jet Cruise Leg):

LOG INFO "Flying leg 'Leg3' of flight plan 'Transcon_Plan'."
SET_PROP_MODE JET
AERO_FLY "Transcon_Plan" 12000.0 0.85 // Follow plan, 12km altitude, Mach 0.85
WAIT_UNTIL "GET_STATE NAVIGATION_STATUS == FLIGHT_PLAN_LEG_COMPLETE" // Wait for leg completion
// Check status

Explanation: Commands the aircraft to follow a predefined flight plan segment at a specific altitude and Mach number using jet engines.

Example 2 (SCRAMJET Acceleration):

LOG INFO "Following hypersonic corridor 'HC1', accelerating to Mach 7."
SET_PROP_MODE SCRAMJET
AERO_FLY "HC1" 40000.0 7.0 // Follow plan, 40km alt, target Mach 7
WAIT_UNTIL "GET_STATE NAVIGATION_STATUS == FLIGHT_PLAN_COMPLETE"
// Check status

Explanation: Commands acceleration along a hypersonic corridor using SCRAMJET power, targeting a high Mach number.

Example 3 (Direct To Waypoint):

VAR WaypointCoords = [40.71, -74.00] // New York City approx coords
LOG INFO "Flying direct to waypoint at 10km, 200 m/s."
SET_PROP_MODE JET
AERO_FLY WaypointCoords 10000.0 200.0
WAIT_UNTIL "GET_STATE NAVIGATION_STATUS == WAYPOINT_REACHED"
// Check status

Explanation: Commands flight directly to specified geographic coordinates at a given altitude and airspeed.

AERO_LOITER <center_lat_deg> <center_lon_deg> <radius_m> <altitude_m> <speed_mps | mach>

Detailed Explanation: Commands the GNC to fly a circular holding pattern using the active air-breathing mode (`JET` or potentially `SCRAMJET` if stable). Manages bank angle and thrust to maintain the specified radius, altitude, and speed around the center point. Useful for waiting, sequencing, or observation. Checks relevant fuel. Asynchronous.

Parameters:

  • center_lat_deg, center_lon_deg (Float): Geographic center of the pattern.
  • radius_m (Float): Radius of the circular path in meters.
  • altitude_m (Float): Target altitude.
  • speed_mps | mach (Float): Target speed (m/s or Mach).

Returns Status: EXECUTING, SUCCESS (only if a duration was implicitly or explicitly associated), FAILED_PRECONDITION, FAILED_EXECUTION. Typically runs until overridden.

Example:

LOG INFO "Entering holding pattern east of airfield, 5km radius, 4km alt, 120 m/s."
AERO_LOITER 28.60 -80.50 5000.0 4000.0 120.0
// Script might wait for ground clearance or another event while loitering
WAIT_UNTIL "GET_STATE CLEARANCE_RECEIVED == TRUE"
LOG INFO "Clearance received, exiting loiter."
// Issue AERO_FLY or AERO_LAND command to exit loiter

Explanation: Establishes a holding pattern and waits for an external condition (like ground clearance) before proceeding.

FLIGHT_TRANSITION <mode> [parameters...]

Detailed Explanation: Commands a transition between distinct flight regimes (VTOL, Aero-Jet, Aero-SCRAMJET, Rocket). This is a complex, asynchronous command where the GNC and system controllers manage a sequence of actions: shutting down/starting engines, reconfiguring inlets/nozzles, deploying/stowing hardware (props, heat shields), blending control actuators (aero surfaces, RCS, thrust vectoring), and updating guidance laws. Requires specific entry conditions (altitude, speed, Mach) and sufficient fuel/power for the target mode. Critical, high-risk operations.

Parameters:

  • mode (Enum): Specific transition:
    • VTOL_TO_AERO: Props off/stow, rely on turbines/wings.
    • AERO_TO_VTOL: Deploy/activate props for landing.
    • JET_TO_SCRAMJET <min_mach>: Turbine -> SCRAMJET. Requires Mach > min_mach.
    • SCRAMJET_TO_ROCKET <alt_m | dyn_p_pa>: SCRAMJET -> Rocket. Triggered by altitude or dynamic pressure threshold.
    • AERO_TO_ROCKET <alt_m>: Turbine -> Rocket (bypass SCRAMJET).
    • ROCKET_TO_AERO <alt_m>: Rocket -> Turbine (descent).
    • ROCKET_TO_SCRAMJET <condition>: Rocket -> SCRAMJET (descent, if feasible).
    • SCRAMJET_TO_JET <max_mach>: SCRAMJET -> Turbine (descent).
    • CONFIGURE_REENTRY: Deploy shields, set attitude for entry.
    • CONFIGURE_POST_REENTRY: Retract shields, configure for aero flight.
  • parameters... (Varies): Parameters defining transition conditions (Mach, altitude, dynamic pressure).

Returns Status: EXECUTING, SUCCESS, FAILED_PRECONDITION (entry conditions not met, insufficient resources), FAILED_EXECUTION (hardware failure, instability, engine start/stop failure).

Example 1 (Jet to SCRAMJET):

LOG INFO "Checking conditions for SCRAMJET transition."
VAR CurrentMach = GET_STATE MACH_NUMBER
IF CurrentMach > 5.0 THEN
    LOG INFO "Conditions met (Mach > 5.0). Initiating transition."
    FLIGHT_TRANSITION JET_TO_SCRAMJET 5.0
    WAIT_UNTIL "GET_STATE PROP_MODE == SCRAMJET"
    IF LAST_COMMAND_STATUS == SUCCESS THEN
        LOG INFO "Successfully transitioned to SCRAMJET mode."
        ENGINE_SCRAMJET "ALL" ACTIVE // Activate engine
    ELSE
        LOG ERROR "Failed to transition to SCRAMJET mode."
        // Handle failure (e.g., continue on turbines if possible, or transition to rocket early)
    ENDIF
ELSE
    LOG WARN "Conditions not yet met for SCRAMJET transition (Mach=" + CurrentMach + ")."
ENDIF

Explanation: Explicitly checks the Mach number condition before attempting the transition, handling both success and failure outcomes.

Example 2 (Configure for Re-entry):

LOG INFO "Approaching Entry Interface. Configuring for Re-entry."
FLIGHT_TRANSITION CONFIGURE_REENTRY
WAIT_UNTIL "GET_STATE SYSTEM_STATUS PROPELLER_HEAT_SHIELDS == DEPLOYED AND GET_STATE ATTITUDE_MODE == AERO_STABLE" // Wait for configuration
IF LAST_COMMAND_STATUS == SUCCESS THEN
    LOG INFO "Re-entry configuration complete."
ELSE
    LOG ERROR "Failed to configure for re-entry!"
    // Handle failure
ENDIF

Explanation: Executes the pre-defined sequence to prepare for atmospheric entry, including deploying heat shields and setting the appropriate attitude control mode. Waits for confirmation.


3.6. Sensors & Targeting Commands

SENSOR_SCAN <sensor_id | type> <target_type | id> <output_variable>

Detailed Explanation: Commands the activation and data acquisition for a specified sensor or sensor type to gather information about a target or the environment. For complex tasks like object recognition (ISS, UNKNOWN_OBJECT) using CAMERA, this invokes the onboard neural network processing pipeline. For LANDING_ZONE scans with LIDAR or RADAR, it involves mapping terrain and assessing safety (slope, roughness, hazards). Results are stored in a structured output_variable. Can be asynchronous for scans requiring time (e.g., mapping, long exposure).

Parameters:

  • sensor_id | type (String | Enum): Specific sensor identifier (e.g., "Camera_Nav_Fwd") OR a generic type (CAMERA, LIDAR, RADAR, STAR_TRACKER, THERMAL, AIR_DATA_SENSOR). Using a type might activate multiple relevant sensors.
  • target_type | id (Enum | String): Type of target (ISS, MOON, MARS, LANDING_ZONE, DOCKING_PORT, RUNWAY <id>, STAR_ID <id>, HORIZON, ATMOSPHERE_DATA, TERRAIN_MAP, UNKNOWN_OBJECT) OR a specific known object ID.
  • output_variable (String): Name of the variable to store the structured results (e.g., LZ_Scan_Data, ISS_Relative_State, Runway_Visual_Confirm). Structure includes fields like .found (boolean), .position_vector, .distance_m, .confidence_level, .image_id, .safety_assessment etc., depending on sensor/target.

Returns Status: EXECUTING (for longer scans), SUCCESS (scan complete, check output variable for results), FAILED_EXECUTION (sensor fault, no target found if required, NN failed to classify).

Example 1 (Landing Zone Safety Scan):

LOG INFO "Performing detailed LIDAR scan of potential landing zone."
SENSOR_SCAN LIDAR LANDING_ZONE LZ_Detailed_Data
WAIT_UNTIL "GET_STATE SENSOR_STATUS LIDAR == IDLE" // Wait for scan completion
IF LZ_Detailed_Data.found == TRUE AND LZ_Detailed_Data.safety_assessment == "GO" THEN
    LOG INFO "Landing zone confirmed safe."
    VAR LandingTargetCoords = [LZ_Detailed_Data.latitude, LZ_Detailed_Data.longitude]
ELSE
    LOG WARN "Landing zone scan failed or zone assessed as NO-GO."
    // Trigger search for alternate LZ or abort
ENDIF

Explanation: Uses LIDAR to map and assess a landing area, storing results including a safety flag.

Example 2 (Visual Docking Port ID):

LOG INFO "Using camera NN to identify docking port."
SENSOR_SCAN "DockingCamera" DOCKING_PORT DockingPortInfo
WAIT_UNTIL "GET_STATE SENSOR_STATUS DockingCamera == IDLE"
IF DockingPortInfo.found == TRUE AND DockingPortInfo.id_confidence > 0.8 THEN
    LOG INFO "Identified port: " + DockingPortInfo.port_id + ". Alignment offset: " + DockingPortInfo.alignment_offset
ELSE
    LOG WARN "Could not identify docking port visually."
ENDIF

Explanation: Leverages the camera and NN to identify a specific docking port and get alignment data.

Example 3 (Star Tracker):

LOG INFO "Getting attitude fix from Star Tracker."
SENSOR_SCAN STAR_TRACKER ATTITUDE_FIX StarTracker_Attitude
WAIT_UNTIL "GET_STATE SENSOR_STATUS STAR_TRACKER == IDLE"
IF StarTracker_Attitude.valid == TRUE THEN
     LOG INFO "Star Tracker attitude fix acquired. Quaternion: " + StarTracker_Attitude.quaternion
     // GNC can use this data internally
ELSE
     LOG WARN "Star Tracker failed to acquire attitude fix."
ENDIF

Explanation: Uses the star tracker to get an absolute attitude reference, crucial for navigation.

GET_STATE <parameter_name> [frame | system_qualifier]

Detailed Explanation: Synchronously retrieves the current value of a specific parameter from the spacecraft's internal state model, maintained by the flight software. This is the primary way scripts become "state-aware". It's crucial for decision-making, logging, and verifying the vehicle's condition. The parameter_name uses a hierarchical or standardized naming convention. Qualifiers specify which instance (e.g., which battery, which frame) if multiple exist.

Parameters:

  • parameter_name (String): Hierarchical name of the state parameter. Examples:
    • Mass & Propellants: CURRENT_MASS_KG, PROPELLANT_KEROSENE_KG, PROPELLANT_LOX_KG, PROPELLANT_JET_KG, PROPELLANT_RCS_KG, PROPELLANT_SCRAMJET_FUEL_KG.
    • Power - Battery: BATTERY_CHARGE_PERCENT <id>, BATTERY_VOLTAGE_V <id>, BATTERY_CURRENT_A <id>, BATTERY_HEALTH_PERCENT <id>, BATTERY_TEMP_K <id>.
    • Power - Solar: SOLAR_ARRAY_POWER_W <id>, SOLAR_ARRAY_STATUS <id> (e.g., SUN_TRACKING, SHADOWED).
    • Power - RTG: RTG_POWER_W <id>, RTG_TEMP_K <id>.
    • Power - General: CURRENT_POWER_LOAD_W, POWER_MARGIN_W.
    • Dynamics: ALTITUDE_M, POSITION_VECTOR <frame>, VELOCITY_VECTOR <frame>, AIRSPEED_MPS, MACH_NUMBER, DYNAMIC_PRESSURE_PA, ACCELERATION_G_LOAD.
    • Attitude: ATTITUDE_QUATERNION <frame>, ANGULAR_VELOCITY_VECTOR <frame>, ATTITUDE_ERROR_DEG, ANGLE_OF_ATTACK_DEG.
    • System Status: SYSTEM_STATUS <system_name> (e.g., DEPLOYED, RETRACTED, FAULT, NOMINAL, OFF), TEMPERATURE <sensor_id>, PRESSURE <sensor_id>, ENGINE_TURBINE_STATUS <id>, ENGINE_SCRAMJET_STATUS <id>, ENGINE_MAIN_STATUS.
    • Command/Sequence Status: LAST_COMMAND_STATUS, MANEUVER_STATUS, DOCKING_STATUS, FLIGHT_MODE, FLIGHT_PHASE, POINTING_STATUS, ROTATION_STATUS, SENSOR_STATUS <id>, DIAGNOSTIC_STATUS <system>, DIAGNOSTIC_RESULT <system>.
    • Time: CURRENT_TIME_UTC, MISSION_ELAPSED_TIME_S.
  • frame | system_qualifier (Enum | String, Optional): Frame for vectors (e.g., EARTH_CI). ID for specific component (e.g., "Battery_Main", "Solar_Array_Port", "Engine_Scramjet_1", "Gyro_A").

Returns: The current value (type depends on parameter) or an error indicator (e.g., null) if invalid.

Example 1 (Consumable Check):

VAR KeroMargin = GET_STATE PROPELLANT_KEROSENE_KG - EstimatedKeroUsage
VAR LoxMargin = GET_STATE PROPELLANT_LOX_KG - EstimatedLoxUsage
IF KeroMargin < SafetyMargin_KG OR LoxMargin < SafetyMargin_KG THEN
    LOG WARN "Propellant margins below safety threshold!"
ENDIF

Explanation: Calculates remaining propellant margins after accounting for estimated usage.

Example 2 (Power System Overview):

VAR BattCharge = GET_STATE BATTERY_CHARGE_PERCENT "MainBus"
VAR BattHealth = GET_STATE BATTERY_HEALTH_PERCENT "MainBus"
VAR SolarGen = GET_STATE SOLAR_ARRAY_POWER_W "ALL" // Get total solar power
VAR RtgGen = GET_STATE RTG_POWER_W "ALL" // Get total RTG power
VAR TotalLoad = GET_STATE CURRENT_POWER_LOAD_W
VAR NetPower = SolarGen + RtgGen - TotalLoad
LOG INFO "Power State: Batt=" + BattCharge + "%(H:" + BattHealth + "%), Gen(Solar/RTG)=" + SolarGen + "/" + RtgGen + "W, Load=" + TotalLoad + "W, Net=" + NetPower + "W"

Explanation: Gathers key power system parameters to log a comprehensive status overview.

Example 3 (Checking GNC State):

VAR CurrentAttMode = GET_STATE ATTITUDE_CONTROL_MODE
VAR CurrentPropMode = GET_STATE PROPULSION_MODE
VAR CurrentNavFrame = GET_STATE NAVIGATION_FRAME
LOG DEBUG "Current Modes: Att=" + CurrentAttMode + ", Prop=" + CurrentPropMode + ", Nav=" + CurrentNavFrame

Explanation: Logs the current high-level modes of the GNC system.

GET_TARGET_STATE <target_name> <parameter_name> [frame]

Detailed Explanation: Synchronously retrieves state information about a known external object (ISS, Moon, another S/C). This relies on data uploaded from ground, received via inter-satellite link, or calculated onboard using ephemeris data and propagators. The availability and accuracy depend on the data source and its update frequency. Essential for rendezvous, proximity operations, and relative navigation.

Parameters:

  • target_name (String): Target identifier ("ISS", "Moon", "RelaySat").
  • parameter_name (String): Desired state parameter (POSITION_VECTOR, VELOCITY_VECTOR, ATTITUDE_QUATERNION).
  • frame (Enum, Optional): Coordinate frame for the returned data (defaults to standard inertial).

Returns: Target's parameter value, or an error indicator if data unavailable/stale.

Example:

LOG INFO "Getting current ISS position relative to Earth."
VAR ISS_Pos_ECI = GET_TARGET_STATE "ISS" POSITION_VECTOR "EARTH_CI"
IF ISS_Pos_ECI != null THEN
    LOG DEBUG "ISS ECI Position: " + ISS_Pos_ECI
ELSE
    LOG WARN "ISS state vector unavailable or stale."
ENDIF

Explanation: Retrieves the position vector of the ISS in the Earth-Centered Inertial frame, checking if the data is available.


3.7. System & Payload Commands

SYSTEM_SET <system_name> <parameter> <value>

Detailed Explanation: Allows scripts to configure specific operational parameters or settings within a designated subsystem, overriding defaults or adapting behavior. Requires detailed knowledge of the subsystem's configurable parameters documented elsewhere. Use cases include setting communication antenna gains, adjusting thermal loop setpoints, loading specific control gain profiles, or configuring sensor parameters (like exposure time, sensitivity).

Parameters:

  • system_name (String): Identifier of the target subsystem (e.g., COMM_ANTENNA_HGA, THERMAL_LOOP_B, FLIGHT_CONTROL, SENSOR_CAMERA_NAV, ENGINE_SCRAMJET_INLET).
  • parameter (String): The specific parameter within the subsystem to set (e.g., GAIN_DB, TEMP_SETPOINT_K, GAINS_PROFILE_NAME, EXPOSURE_TIME_MS, INLET_RAMP_ANGLE_DEG).
  • value (Any): The desired value for the parameter (Float, Integer, String, Enum).

Returns Status: SUCCESS, INVALID_PARAMETER (parameter/value invalid or system doesn't support it), FAILED_PRECONDITION (e.g., system powered off, in wrong mode).

Example 1 (Set Camera Exposure):

LOG INFO "Setting NavCam exposure time for low light."
SYSTEM_SET "SENSOR_CAMERA_NAV" EXPOSURE_TIME_MS 100.0

Explanation: Adjusts the camera's exposure time parameter.

Example 2 (Load Control Gains):

LOG INFO "Loading atmospheric entry control gains."
SYSTEM_SET FLIGHT_CONTROL GAINS_PROFILE_NAME "ENTRY_MODE_GAINS"

Explanation: Tells the flight control system to use a specific set of pre-defined control gains suitable for atmospheric entry.

Example 3 (Thermal Setpoint):

LOG INFO "Adjusting battery thermal loop setpoint."
SYSTEM_SET "THERMAL_BATTERY_LOOP" TEMP_SETPOINT_K 283.15 // Target 10 deg C

Explanation: Changes the target temperature for a specific thermal control loop.

SYSTEM_DEPLOY <system_name>

Detailed Explanation: Initiates the deployment sequence for mechanical hardware like landing gear, solar arrays, antennas, radiators, science booms, or the propeller heat shields. This is typically an asynchronous command involving motors, latches, and sensors to confirm deployment status. Requires the system to be powered.

Parameters:

  • system_name (String): Identifier of the deployable system (e.g., LANDING_GEAR, SOLAR_PANELS, COMM_ANTENNA_HGA, PROPELLER_HEAT_SHIELDS, etc.).

Returns Status: EXECUTING, SUCCESS (deployment confirmed by sensors), FAILED_EXECUTION (mechanism jammed, sensor failure).

Example 1 (Landing Gear):

LOG INFO "Deploying landing gear."
SYSTEM_DEPLOY LANDING_GEAR
WAIT_UNTIL "GET_STATE SYSTEM_STATUS LANDING_GEAR == DEPLOYED_LOCKED"
IF LAST_COMMAND_STATUS != SUCCESS THEN
    LOG ERROR "Landing gear deployment failed!"
    // Handle error - critical for landing!
ENDIF

Explanation: Commands gear deployment and waits for confirmation that it's down and locked.

Example 2 (Heat Shields):

LOG INFO "Deploying propeller heat shields for re-entry."
SYSTEM_DEPLOY PROPELLER_HEAT_SHIELDS
WAIT_UNTIL "GET_STATE SYSTEM_STATUS PROPELLER_HEAT_SHIELDS == DEPLOYED"
// Check status

Explanation: Deploys the specialized heat shields before atmospheric entry.

SYSTEM_RETRACT <system_name>

Detailed Explanation: Initiates the retraction/stowing sequence for deployable hardware. Similar to SYSTEM_DEPLOY, it's asynchronous and involves mechanisms and sensors.

Parameters:

  • system_name (String): Identifier of the system to retract.

Returns Status: EXECUTING, SUCCESS (retraction confirmed), FAILED_EXECUTION.

Example 1 (Solar Panels):

LOG INFO "Retracting solar panels before atmospheric entry."
SYSTEM_RETRACT SOLAR_PANELS
WAIT_UNTIL "GET_STATE SYSTEM_STATUS SOLAR_PANELS == RETRACTED_LOCKED"
// Check status

Explanation: Stows solar panels to protect them during high dynamic pressure or entry phases.

Example 2 (Landing Gear after Takeoff):

// Assuming AERO_TAKEOFF was successful and positive climb rate established
LOG INFO "Retracting landing gear."
SYSTEM_RETRACT LANDING_GEAR
WAIT_UNTIL "GET_STATE SYSTEM_STATUS LANDING_GEAR == RETRACTED_LOCKED"
// Check status

Explanation: Retracts landing gear after a conventional runway takeoff.

SYSTEM_POWER <system_name | group_name | "ALL"> <state>

Detailed Explanation: Directly controls the power state of individual subsystems or predefined groups. This allows scripts to manage power consumption by turning devices ON/OFF or placing them in a low-power STANDBY state. ALL typically refers to all non-critical systems. Critical systems (like main flight computers, essential heaters) might be protected from being turned OFF via script.

Parameters:

  • system_name | group_name | "ALL" (String): Target system (e.g., "Payload_Spectrometer"), group (e.g., "ALL_PAYLOADS", "NON_ESSENTIAL_HEATERS"), or "ALL" (non-essential).
  • state (Enum): ON, OFF, STANDBY.

Returns Status: SUCCESS, FAILED_EXECUTION (e.g., power bus fault, protected system).

Example 1 (Payload Power Cycle):

LOG INFO "Power cycling Payload Spectrometer."
SYSTEM_POWER "Payload_Spectrometer" OFF
WAIT 10.0
SYSTEM_POWER "Payload_Spectrometer" ON
WAIT 5.0 // Allow boot
LOG INFO "Payload power cycle complete."

Explanation: Turns a payload off and then back on, often used to reset devices.

Example 2 (Power Saving):

LOG INFO "Entering power saving: shutting down non-essential comms."
SYSTEM_POWER "COMM_ANTENNA_LOW_GAIN" OFF
SYSTEM_POWER "COMM_TRANSMITTER_B" OFF

Explanation: Explicitly turns off specific communication components to save power.

Example 3 (Group Power Down):

LOG INFO "Powering down all science payloads."
SYSTEM_POWER "ALL_PAYLOADS" OFF

Explanation: Uses a predefined group name to power off multiple related systems with one command.

SET_POWER_MODE <mode_name>

Detailed Explanation: Activates a predefined, integrated power management strategy. This is a higher-level command than SYSTEM_POWER. The Power Management System (PMS) interprets the mode and automatically configures power generation (e.g., solar array pointing/tracking), battery charge/discharge logic (e.g., prioritize charging in CRUISE_SOLAR, minimize discharge in SAFE_MODE), and potentially sheds non-critical loads based on available power from all sources (Solar, Battery, RTG).

Parameters:

  • mode_name (Enum): Power mode (PREFLIGHT, VTOL_FLIGHT, AERO_FLIGHT, SCRAMJET_FLIGHT, LAUNCH_ROCKET, CRUISE_MIN_POWER, CRUISE_SOLAR, ORBITAL_OPS, RENDEZVOUS, DOCKED_ISS_POWER, REENTRY, LANDING, SURFACE_IDLE, SURFACE_OPS, SAFE_MODE).

Returns Status: SUCCESS, FAILED_EXECUTION (PMS failure).

Example 1 (Entering Safe Mode):

LOG CRITICAL "Anomaly detected. Entering Safe Mode for power conservation."
SET_POWER_MODE SAFE_MODE
// PMS will automatically shut down non-essentials, minimize consumption, ensure survival power.

Explanation: Commands the PMS to enter its most conservative power state.

Example 2 (Preparing for High Load):

LOG INFO "Setting power mode for high-load Rendezvous operations."
SET_POWER_MODE RENDEZVOUS
// PMS ensures sufficient power is available for sensors, RCS heaters, comms needed for RDV.

Explanation: Configures the power system for a phase expected to have high power demand.

Example 3 (Solar Cruise):

LOG INFO "Entering solar power cruise mode, prioritizing battery charging."
SET_POWER_MODE CRUISE_SOLAR // Power manager optimizes solar use and battery charging
WAIT 5.0 // Allow power system to stabilize
VAR BattCurrent = GET_STATE BATTERY_CURRENT_A "MainBus"
LOG INFO "Main battery current: " + BattCurrent + " A (+ve means charging)"

Explanation: Sets a mode where solar power is maximized, and excess power is used to charge batteries.

SET_COMM_MODE <mode_name>

Detailed Explanation: Configures the communication subsystem(s) for a specific operational scenario. This involves selecting appropriate antennas (high gain, low gain), frequency bands (S-band, Ka-band), data rates, network protocols (DSN, TDRS, ground station specific), and potentially enabling/disabling transmitters/receivers.

Parameters:

  • mode_name (Enum): Comms mode (DEEP_SPACE_NETWORK, LUNAR_RELAY, MARS_RELAY, ISS_PROXIMITY, EARTH_GROUND_LINK_HIGH_BW, EARTH_GROUND_LINK_LOW_BW, AIR_TRAFFIC_CONTROL, COMM_SILENT).

Returns Status: SUCCESS, FAILED_EXECUTION (comm system fault).

Example 1 (DSN):

LOG INFO "Configuring for Deep Space Network communications."
SET_COMM_MODE DEEP_SPACE_NETWORK
// Comm system selects appropriate antenna (likely HGA), frequency, etc.
ORIENT "HGA_BORESIGHT" EARTH // Point antenna towards Earth

Explanation: Sets up the communication system for long-range communication via the DSN.

Example 2 (Proximity Ops):

LOG INFO "Configuring for ISS proximity communications."
SET_COMM_MODE ISS_PROXIMITY
// Comm system selects appropriate low-gain antenna and protocol for short-range comms.

Explanation: Configures for short-range communication suitable for rendezvous and docking with the ISS.

SET_CONSTRAINT <type> <parameter> <operator> <value> [action]

Detailed Explanation: Defines a rule for the flight software to autonomously monitor a specific state parameter. If the parameter crosses the defined threshold (value) according to the type and operator, the specified action is automatically triggered. This provides a layer of autonomous safety and monitoring independent of the running script. Constraints can be set for temperatures, pressures, voltages, currents, charge levels, propellant levels, altitudes, angular rates, etc.

Parameters:

  • type (Enum): UPPER_LIMIT, LOWER_LIMIT, RATE_OF_CHANGE_LIMIT.
  • parameter (String): State parameter to monitor (e.g., TEMPERATURE RTG1, PROPELLANT_LOX_KG, BATTERY_VOLTAGE_V MainBus).
  • operator (Enum): Comparison (>, <) or RATE_LIMIT.
  • value (Float): Threshold value. For RATE_LIMIT, this is the maximum change per second (absolute value).
  • action (Enum, Optional): LOG_WARN (default), LOG_ERROR, TRIGGER_EVENT <event_name>, ENTER_SAFE_MODE.

Returns Status: SUCCESS, INVALID_PARAMETER.

Example 1 (Battery Voltage Limits):

LOG INFO "Setting battery voltage constraints."
SET_CONSTRAINT UPPER_LIMIT "BATTERY_VOLTAGE_V MainBus" > 32.0 LOG_WARN
SET_CONSTRAINT LOWER_LIMIT "BATTERY_VOLTAGE_V MainBus" < 24.0 TRIGGER_EVENT "LowBatteryVoltage"

Explanation: Logs a warning if voltage exceeds 32V, and triggers a specific event if it drops below 24V.

Example 2 (Rate of Descent Limit):

LOG INFO "Setting maximum descent rate constraint during landing approach."
// Monitor vertical velocity (negative for descent)
SET_CONSTRAINT RATE_OF_CHANGE_LIMIT "ALTITUDE_M" > 10.0 TRIGGER_EVENT "HighDescentRate" // Trigger if descent > 10 m/s

Explanation: Monitors the rate of change of altitude, triggering an event if the descent rate becomes too high.

Example 3 (Low Fuel Safe Mode):

LOG INFO "Setting critical low RCS fuel constraint to enter safe mode."
SET_CONSTRAINT LOWER_LIMIT "PROPELLANT_RCS_KG" < 1.5 ENTER_SAFE_MODE

Explanation: Configures the system to automatically enter safe mode if RCS propellant drops below a critical threshold.

RUN_DIAGNOSTIC <system_name> [test_level]

Detailed Explanation: Commands a specific subsystem to execute its built-in self-test or diagnostic routine. These tests can range from simple status checks (QUICK) to more intrusive tests (STANDARD, EXTENDED) that might involve actuating valves, moving mechanisms, or sending test patterns. Useful for verifying system health after anomalies, before critical events, or during commissioning. Asynchronous command.

Parameters:

  • system_name (String): Target system (ENGINE_MAIN, RCS_PLUMBING, SOLAR_ARRAY_GIMBAL, FLIGHT_COMPUTER_B, BATTERY MainBus, ENGINE_SCRAMJET Engine1).
  • test_level (Enum, Optional): QUICK (default), STANDARD, EXTENDED.

Returns Status: EXECUTING, SUCCESS (passed), FAILED_EXECUTION (failed test, system busy/unavailable), INVALID_PARAMETER. Detailed results are usually logged or available via GET_STATE DIAGNOSTIC_RESULT <system_name>.

Example 1 (Quick Check):

LOG INFO "Running quick diagnostic on flight computer B."
RUN_DIAGNOSTIC FLIGHT_COMPUTER_B QUICK
WAIT_UNTIL "GET_STATE DIAGNOSTIC_STATUS FLIGHT_COMPUTER_B != EXECUTING"
LOG INFO "FC-B Quick Diag Result: " + GET_STATE DIAGNOSTIC_RESULT FLIGHT_COMPUTER_B

Explanation: Runs a non-intrusive check on the backup flight computer.

Example 2 (Extended Test):

LOG INFO "Running extended diagnostic on Solar Array Gimbal A."
RUN_DIAGNOSTIC SOLAR_ARRAY_GIMBAL_A EXTENDED
// This might take time and involve movement, monitor progress
WAIT_UNTIL "GET_STATE DIAGNOSTIC_STATUS SOLAR_ARRAY_GIMBAL_A != EXECUTING"
VAR DiagResult = GET_STATE DIAGNOSTIC_RESULT SOLAR_ARRAY_GIMBAL_A
IF DiagResult != "PASSED" THEN
    LOG ERROR "Extended diagnostic failed for Solar Array Gimbal A!"
ENDIF

Explanation: Runs a more thorough test on a mechanical system and checks the result.

SYSTEM_HEALTH_CHECK <system_name | "ALL">

Detailed Explanation: Performs a rapid, passive assessment of system health by evaluating key telemetry points against predefined nominal ranges (e.g., temperatures, voltages, pressures, status flags). It does not run active tests like RUN_DIAGNOSTIC. Provides a quick go/no-go indication. Synchronous check.

Parameters:

  • system_name | "ALL" (String): Target system (POWER_SYSTEM, THERMAL_CONTROL, GNC, ENGINE_SCRAMJET Engine1) or "ALL" for a vehicle-wide summary.

Returns: Overall health status (Enum: NOMINAL, WARN (minor issue detected), ERROR (significant issue detected), UNKNOWN (insufficient data)).

Example 1 (Specific System):

VAR GncHealth = SYSTEM_HEALTH_CHECK "GNC"
IF GncHealth != NOMINAL THEN
    LOG WARN "GNC system health check returned: " + GncHealth
    // Consider running detailed diagnostics or adjusting operations
ELSE
    LOG INFO "GNC system health check nominal."
ENDIF

Explanation: Performs a quick check on the Guidance, Navigation, and Control system.

Example 2 (All Systems):

VAR OverallHealth = SYSTEM_HEALTH_CHECK "ALL"
LOG INFO "Overall vehicle health check status: " + OverallHealth
IF OverallHealth == ERROR THEN
    LOG CRITICAL "Major system health issue detected!"
    // Initiate safe mode or contingency
ENDIF

Explanation: Gets a summary health status for the entire vehicle.

SYSTEM_HEALTH_CHECK <system_name | "ALL">

Detailed Explanation: Performs a rapid, passive assessment of system health by evaluating key telemetry points against predefined nominal ranges (e.g., temperatures, voltages, pressures, status flags). It does not run active tests like RUN_DIAGNOSTIC. Provides a quick go/no-go indication. Synchronous check.

Parameters:

  • system_name | "ALL" (String): Target system (POWER_SYSTEM, THERMAL_CONTROL, GNC, ENGINE_SCRAMJET Engine1) or "ALL" for a vehicle-wide summary.

Returns: Overall health status (Enum: NOMINAL, WARN (minor issue detected), ERROR (significant issue detected), UNKNOWN (insufficient data)).

Example 1 (Specific System):

VAR GncHealth = SYSTEM_HEALTH_CHECK "GNC"
IF GncHealth != NOMINAL THEN
    LOG WARN "GNC system health check returned: " + GncHealth
    // Consider running detailed diagnostics or adjusting operations
ELSE
    LOG INFO "GNC system health check nominal."
ENDIF

Explanation: Performs a quick check on the Guidance, Navigation, and Control system.

Example 2 (All Systems):

VAR OverallHealth = SYSTEM_HEALTH_CHECK "ALL"
LOG INFO "Overall vehicle health check status: " + OverallHealth
IF OverallHealth == ERROR THEN
    LOG CRITICAL "Major system health issue detected!"
    // Initiate safe mode or contingency
ENDIF

Explanation: Gets a summary health status for the entire vehicle.

PAYLOAD_COMMAND <payload_id> <command_string>

Detailed Explanation: Provides a generic mechanism to send command strings to specific payloads (science instruments, robotic arms, deployers, etc.). The command_string content and format are defined by the payload's own interface specification, not by SCLAM itself. SCLAM just acts as a transport mechanism to route the command to the correct payload controller. Payload execution status must typically be monitored via payload-specific telemetry accessed via GET_STATE.

Parameters:

  • payload_id (String): Unique identifier for the payload (e.g., "Spectrometer_VIS", "Robotic_Arm_Main").
  • command_string (String): The command to be interpreted by the payload's controller.

Returns Status: SUCCESS (command successfully relayed to payload interface), FAILED_PRECONDITION (payload powered off, interface inactive), INVALID_PARAMETER (invalid payload ID).

Example 1 (Start Observation):

LOG INFO "Commanding Spectrometer to start observation."
SYSTEM_POWER "Spectrometer_Payload" ON
WAIT 5.0 // Allow power up
PAYLOAD_COMMAND "Spectrometer_Payload" "START_OBSERVATION_MODE_3"
// Monitor payload status via GET_STATE PAYLOAD_STATUS "Spectrometer_Payload"

Explanation: Powers on a payload and sends it a specific command string to begin an observation sequence.

Example 2 (Move Robotic Arm):

LOG INFO "Commanding robotic arm to move to position 'Sample_A'."
PAYLOAD_COMMAND "Robotic_Arm_Main" "MOVE_TO_PRESET Sample_A"
WAIT_UNTIL "GET_STATE PAYLOAD_STATUS Robotic_Arm_Main == IDLE" // Wait for arm motion to complete
// Check status

Explanation: Sends a command to a robotic arm payload to move to a predefined position.

SET_EVENT_TRIGGER <event_condition> <action_command_or_script>

Detailed Explanation: Arms an autonomous trigger within the flight software. The software continuously monitors the event_condition. When the condition transitions from FALSE to TRUE, the specified action_command_or_script is executed automatically, independent of the main script flow. This allows for immediate reactions to specific events (e.g., faults, sensor readings, constraint violations). Multiple triggers can be active simultaneously. Mechanisms may be needed to disarm triggers if no longer needed (e.g., a CLEAR_EVENT_TRIGGER command, which is not specified here but implied).

Parameters:

  • event_condition (String): Boolean condition to monitor (e.g., "GET_STATE SYSTEM_STATUS Power_Converter_A == FAULT", "GET_STATE SENSOR_SUN_SENSOR_ANGLE > 90.0").
  • action_command_or_script (String): A single SCLAM command string (e.g., "LOG CRITICAL 'Sun sensor off-pointing!'") or a CALL to an action script (e.g., "CALL Handle_Power_Fault.sclam").

Returns Status: SUCCESS (trigger armed), INVALID_PARAMETER (invalid condition or action).

Example 1 (Fault Response):

LOG INFO "Arming event trigger for main computer fault."
// Action: Immediately call the script to switch to backup computer
SET_EVENT_TRIGGER "GET_STATE SYSTEM_STATUS FLIGHT_COMPUTER_A == FAULT" "CALL Switch_To_Backup_Computer.sclam"

Explanation: Sets up an autonomous response to switch to the backup flight computer if the primary one faults.

Example 2 (Science Opportunity):

LOG INFO "Arming trigger to start observation if target enters camera FOV."
// Action: Log info and call the observation script
SET_EVENT_TRIGGER "GET_STATE TARGET_IN_FOV Camera_Science == TRUE" "LOG INFO 'Target in FOV, starting observation.'; CALL Run_Science_Observation.sclam"

Explanation: Automatically starts a science observation sequence when the target comes into the camera's field of view.

Example 3 (Constraint Violation Action):

LOG INFO "Arming trigger based on low battery constraint event."
// Assumes a constraint previously set like: SET_CONSTRAINT ... TRIGGER_EVENT "LowBatteryVoltage"
SET_EVENT_TRIGGER "EVENT_OCCURRED LowBatteryVoltage" "LOG CRITICAL 'Low Battery Voltage Event Triggered!'; SET_POWER_MODE SAFE_MODE"

Explanation: Sets up a trigger that waits for an event generated by a separate constraint violation, then executes multiple commands (log critical, enter safe mode).


4. Mission Example Snippets (Expanded)

(Examples in v1.4 already show checks like IF LAST_COMMAND_STATUS != SUCCESS THEN GOTO Handle_Launch_Abort ENDIF. Explicit pre-checks using new GET_STATE parameters should be added to critical CALL scripts like PreFlight_Propulsion_Check.sclam or performed inline before major maneuvers as shown in the updated IF example in section 3.1 and the ENGINE_MAIN example in 3.2.)

Refer to detailed examples under each command in Section 3 for individual command usage illustrations.

(Additional detailed mission phase examples like a full rendezvous or landing sequence could be added here in a full implementation.)


5. Integration Notes (for Unity3D / Real Systems)

  • Parser: Must perform thorough validation of commands, parameters, types, ranges, and enum values based on this detailed specification. Provide clear error messages for script validation.
  • Execution Engine: Needs robust handling of asynchronous commands, accurate state management, reliable interface to flight software modules (GNC, PMS, TCS, Comms, Payloads, etc.), and clear reporting of LAST_COMMAND_STATUS variable. Must handle context switching for CALL/RETURN.
  • State Management: The internal state model must be comprehensive, high-fidelity, and accurately reflect the parameters queryable via GET_STATE, including all consumables, detailed power states per component, current mass properties (mass, CM, MoI), and status flags for all subsystems and ongoing asynchronous operations. Thread safety is crucial if accessed by multiple processes. Rigorously define the full list of available state parameters.
  • Asynchronous Operations: Implement robust mechanisms (e.g., state machines tied to command execution) to track progress and completion/failure of commands like NAV_MANEUVER, FLIGHT_TRANSITION, SYSTEM_DEPLOY, WAIT_UNTIL. Provide clear status updates accessible via GET_STATE (e.g., MANEUVER_STATUS, DEPLOYMENT_STATUS). Implement configurable timeouts for critical async operations.
  • Coordinate Transformations: Use a validated, high-precision library (like the SPICE toolkit or equivalent) for all coordinate frame definitions and transformations. Ensure consistent definition and application of all frames.
  • Flight Computer Functions:
    • GNC: Must handle complex multi-mode guidance (VTOL, Aero, SCRAMJET, Rocket, Rendezvous, Landing), navigation using various sensors, control allocation across diverse actuators (turbines, props, scramjets, rockets, RCS, aero surfaces), and critically, must use the time-varying mass properties and perform consumable availability checks before executing maneuvers. Needs accurate performance models for all engines across their operating envelopes.
    • Power Management System (PMS): Must implement the logic for each SET_POWER_MODE, actively managing power distribution from solar, battery, and RTG sources, prioritizing loads, managing battery charge/discharge cycles based on mode, state of charge, health, and available generation.
    • Thermal Control System (TCS): Must manage heat loads from engines (especially SCRAMJET/Rocket), electronics, and environmental sources (solar, aero heating), potentially adjusting radiator flow and deploying/retracting radiators based on SYSTEM_SET or internal logic.
    • Sensor Fusion / NN Processing: Needs robust algorithms for processing sensor data, including the NN pipeline for vision-based tasks (SENSOR_SCAN).
  • Error Handling Implementation: Define the exact set of status codes and error flags accessible via GET_STATE. Implement the SET_CONSTRAINT monitoring and TRIGGER_EVENT execution logic reliably. Develop comprehensive Fault Detection, Isolation, and Recovery (FDIR) policies that interact predictably with SCLAM execution (e.g., FDIR might pause or abort a script). Provide a mechanism to clear/disable event triggers and constraints.
  • Verification & Validation (V&V): Extensive simulation covering nominal and off-nominal scenarios (engine failures, sensor noise, mechanism jams, low consumables, constraint violations) is essential. Test script robustness and error handling paths thoroughly. Hardware-in-the-loop testing is critical before flight. Simulations must accurately model mass depletion, power budgets, thermal effects, and the behavior of all actuators and sensors across all flight regimes.