refactor: move firmware workspace under firmware
This commit is contained in:
1 parent
153b0bf262
commit
f03fc119a4
222 files changed
+56
-13
No files matched your search
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "kaptan-mavlink"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Common MAVLink telemetry/arm acknowledgement is the default surface.
|
||||
default = ["dialect-kaptan", "sensor-telemetry"]
|
||||
# Sensor-domain adapters are physical telemetry only.
|
||||
sensor-telemetry = ["dep:kaptan-sensor"]
|
||||
dialect-kaptan = []
|
||||
|
||||
[dependencies]
|
||||
kaptan-log = { path = "../kaptan-log" }
|
||||
kaptan-dma = { path = "../kaptan-dma" }
|
||||
kaptan-sensor = { path = "../kaptan-sensor", optional = true }
|
||||
kaptan-tx = { path = "../kaptan-tx" }
|
||||
mavlink = { version = "0.18", default-features = false, features = ["embedded", "dialect-common"] }
|
||||
mavlink-core = { version = "0.18", default-features = false, features = ["embedded"] }
|
||||
bitflags = "2"
|
||||
num-derive = "0.4"
|
||||
num-traits = { version = "0.2", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
kaptan-time = { path = "../kaptan-time" }
|
||||
|
||||
[build-dependencies]
|
||||
mavlink-bindgen = "0.18"
|
||||
@@ -0,0 +1,28 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let manifest_directory = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
let dialect = manifest_directory.join("definitions/kaptan.xml");
|
||||
let config = manifest_directory.join("definitions/kaptan/config.xml");
|
||||
let log = manifest_directory.join("definitions/kaptan/log.xml");
|
||||
let error = manifest_directory.join("definitions/kaptan/error.xml");
|
||||
let shutdown = manifest_directory.join("definitions/kaptan/shutdown.xml");
|
||||
for definition in [&dialect, &config, &log, &error, &shutdown] {
|
||||
println!("cargo::rerun-if-changed={}", definition.display());
|
||||
}
|
||||
println!("cargo::rustc-check-cfg=cfg(kaptan_has_messages)");
|
||||
// The upstream generator conditionally emits derives for these optional
|
||||
// ecosystem crates. Kaptan deliberately does not expose those incomplete
|
||||
// features, so tell rustc the generated inactive cfgs are intentional.
|
||||
println!("cargo::rustc-check-cfg=cfg(feature, values(\"serde\", \"arbitrary\", \"ts-rs\"))");
|
||||
if std::env::var_os("CARGO_FEATURE_DIALECT_KAPTAN").is_some() {
|
||||
let output_directory = std::env::var("OUT_DIR").unwrap();
|
||||
let generated = mavlink_bindgen::generate(
|
||||
mavlink_bindgen::XmlDefinitions::Files(vec![dialect]),
|
||||
output_directory,
|
||||
)
|
||||
.unwrap();
|
||||
mavlink_bindgen::emit_cargo_build_messages(&generated);
|
||||
println!("cargo::rustc-cfg=kaptan_has_messages");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<mavlink>
|
||||
<!-- The root is the only bindgen input. Feature domains remain independent
|
||||
fragments so their message catalogs can evolve without a monolith. -->
|
||||
<include>kaptan/config.xml</include>
|
||||
<include>kaptan/log.xml</include>
|
||||
<include>kaptan/error.xml</include>
|
||||
<include>kaptan/shutdown.xml</include>
|
||||
</mavlink>
|
||||
@@ -0,0 +1,270 @@
|
||||
<?xml version="1.0"?>
|
||||
<mavlink>
|
||||
<version>3</version>
|
||||
<dialect>0</dialect>
|
||||
<!-- Kaptan configuration dialect. Register the development IDs before release. 42000
|
||||
belongs to Icarous and is deliberately not used here. -->
|
||||
<enums>
|
||||
<enum name="KAPTAN_CONFIG_VALUE_KIND">
|
||||
<entry value="1" name="KAPTAN_CONFIG_VALUE_KIND_BOOL"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_VALUE_KIND_I32"/>
|
||||
<entry value="3" name="KAPTAN_CONFIG_VALUE_KIND_U32"/>
|
||||
<entry value="4" name="KAPTAN_CONFIG_VALUE_KIND_U64"/>
|
||||
<entry value="5" name="KAPTAN_CONFIG_VALUE_KIND_F32"/>
|
||||
<entry value="6" name="KAPTAN_CONFIG_VALUE_KIND_F64"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_POLICY">
|
||||
<entry value="1" name="KAPTAN_CONFIG_POLICY_LIVE"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_POLICY_DISARMED_RESET"/>
|
||||
<entry value="3" name="KAPTAN_CONFIG_POLICY_RESTART_REQUIRED"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_STATE">
|
||||
<entry value="0" name="KAPTAN_CONFIG_STATE_ACTIVE"/>
|
||||
<entry value="1" name="KAPTAN_CONFIG_STATE_EDITING"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_STATE_RESTART_REQUIRED"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_VALUE_SOURCE">
|
||||
<entry value="0" name="KAPTAN_CONFIG_VALUE_SOURCE_ACTIVE"/>
|
||||
<entry value="1" name="KAPTAN_CONFIG_VALUE_SOURCE_COMMITTED"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_VALUE_SOURCE_TRANSACTION"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_OPERATION">
|
||||
<entry value="1" name="KAPTAN_CONFIG_OPERATION_QUERY"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_OPERATION_BEGIN"/>
|
||||
<entry value="3" name="KAPTAN_CONFIG_OPERATION_SET"/>
|
||||
<entry value="4" name="KAPTAN_CONFIG_OPERATION_VALIDATE"/>
|
||||
<entry value="5" name="KAPTAN_CONFIG_OPERATION_COMMIT"/>
|
||||
<entry value="6" name="KAPTAN_CONFIG_OPERATION_ABORT"/>
|
||||
<entry value="7" name="KAPTAN_CONFIG_OPERATION_IMPORT"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_RESULT">
|
||||
<entry value="0" name="KAPTAN_CONFIG_RESULT_ACCEPTED"/>
|
||||
<entry value="1" name="KAPTAN_CONFIG_RESULT_COMMITTED_RESTART_REQUIRED"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_RESULT_REJECTED"/>
|
||||
</enum>
|
||||
<enum name="KAPTAN_CONFIG_ERROR">
|
||||
<entry value="0" name="KAPTAN_CONFIG_ERROR_NONE"/>
|
||||
<entry value="1" name="KAPTAN_CONFIG_ERROR_BAD_TARGET"/>
|
||||
<entry value="2" name="KAPTAN_CONFIG_ERROR_AUTHORIZATION_DENIED"/>
|
||||
<entry value="3" name="KAPTAN_CONFIG_ERROR_GENERATION_CONFLICT"/>
|
||||
<entry value="4" name="KAPTAN_CONFIG_ERROR_SESSION_BUSY"/>
|
||||
<entry value="5" name="KAPTAN_CONFIG_ERROR_INVALID_SESSION"/>
|
||||
<entry value="6" name="KAPTAN_CONFIG_ERROR_STALE_REVISION"/>
|
||||
<entry value="7" name="KAPTAN_CONFIG_ERROR_BAD_STATE"/>
|
||||
<entry value="8" name="KAPTAN_CONFIG_ERROR_UNKNOWN_FIELD"/>
|
||||
<entry value="9" name="KAPTAN_CONFIG_ERROR_TYPE_MISMATCH"/>
|
||||
<entry value="10" name="KAPTAN_CONFIG_ERROR_NON_FINITE"/>
|
||||
<entry value="11" name="KAPTAN_CONFIG_ERROR_BELOW_MINIMUM"/>
|
||||
<entry value="12" name="KAPTAN_CONFIG_ERROR_ABOVE_MAXIMUM"/>
|
||||
<entry value="13" name="KAPTAN_CONFIG_ERROR_CROSS_FIELD"/>
|
||||
<entry value="14" name="KAPTAN_CONFIG_ERROR_UNSUPPORTED_CAPABILITY"/>
|
||||
<entry value="15" name="KAPTAN_CONFIG_ERROR_UNSUPPORTED_FORMAT"/>
|
||||
<entry value="16" name="KAPTAN_CONFIG_ERROR_STORAGE_FAILURE"/>
|
||||
<entry value="17" name="KAPTAN_CONFIG_ERROR_INTERNAL"/>
|
||||
<entry value="18" name="KAPTAN_CONFIG_ERROR_REQUEST_CONFLICT"/>
|
||||
<entry value="19" name="KAPTAN_CONFIG_ERROR_CBOR_MALFORMED"/>
|
||||
<entry value="20" name="KAPTAN_CONFIG_ERROR_CBOR_TOO_LARGE"/>
|
||||
<entry value="21" name="KAPTAN_CONFIG_ERROR_BLOB_CRC"/>
|
||||
<entry value="22" name="KAPTAN_CONFIG_ERROR_SCHEMA_MISMATCH"/>
|
||||
<entry value="23" name="KAPTAN_CONFIG_ERROR_IMPORT_UNAVAILABLE"/>
|
||||
</enum>
|
||||
</enums>
|
||||
<messages>
|
||||
<message id="51000" name="KAPTAN_CONFIG_INFO">
|
||||
<description>Correlated configuration protocol and active snapshot metadata.</description>
|
||||
<field type="uint64_t" name="active_generation"/>
|
||||
<field type="uint64_t" name="committed_generation"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint8_t[16]" name="schema_id"/>
|
||||
<field type="uint16_t" name="profile_format"/>
|
||||
<field type="uint16_t" name="field_count"/>
|
||||
<field type="uint8_t" name="protocol_major"/>
|
||||
<field type="uint8_t" name="protocol_minor"/>
|
||||
<field type="uint8_t" name="config_state" enum="KAPTAN_CONFIG_STATE"/>
|
||||
<field type="uint8_t" name="capability_flags"/>
|
||||
</message>
|
||||
<message id="51014" name="KAPTAN_CONFIG_INFO_REQUEST">
|
||||
<description>Requests correlated configuration protocol and schema metadata.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51001" name="KAPTAN_CONFIG_DESCRIPTOR_REQUEST">
|
||||
<description>Requests a bounded page of field descriptors.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint16_t" name="first"/>
|
||||
<field type="uint16_t" name="count"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51002" name="KAPTAN_CONFIG_DESCRIPTOR">
|
||||
<description>One self-describing editable scalar field.</description>
|
||||
<field type="uint64_t" name="minimum_bits"/>
|
||||
<field type="uint64_t" name="maximum_bits"/>
|
||||
<field type="uint64_t" name="default_bits"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint16_t" name="descriptor_index"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="char[48]" name="display_key"/>
|
||||
<field type="char[16]" name="unit"/>
|
||||
<field type="uint8_t" name="value_kind" enum="KAPTAN_CONFIG_VALUE_KIND"/>
|
||||
<field type="uint8_t" name="apply_policy" enum="KAPTAN_CONFIG_POLICY"/>
|
||||
<field type="uint8_t" name="flags"/>
|
||||
</message>
|
||||
<message id="51003" name="KAPTAN_CONFIG_VALUE_REQUEST">
|
||||
<description>Reads one active, committed, or transaction value.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="source" enum="KAPTAN_CONFIG_VALUE_SOURCE"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51004" name="KAPTAN_CONFIG_VALUE">
|
||||
<description>One typed configuration scalar as canonical raw bits.</description>
|
||||
<field type="uint64_t" name="value_bits"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="value_kind" enum="KAPTAN_CONFIG_VALUE_KIND"/>
|
||||
</message>
|
||||
<message id="51005" name="KAPTAN_CONFIG_BEGIN">
|
||||
<description>Opens the one lease-bound edit transaction.</description>
|
||||
<field type="uint64_t" name="expected_generation"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51006" name="KAPTAN_CONFIG_SET_F32">
|
||||
<description>Writes one f32 field in the open transaction.</description>
|
||||
<field type="float" name="value"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51007" name="KAPTAN_CONFIG_SET_I32">
|
||||
<description>Writes one i32 field in the open transaction.</description>
|
||||
<field type="int32_t" name="value"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51008" name="KAPTAN_CONFIG_SET_U32">
|
||||
<description>Writes one u32 field in the open transaction.</description>
|
||||
<field type="uint32_t" name="value"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51009" name="KAPTAN_CONFIG_SET_U64">
|
||||
<description>Writes one u64 field in the open transaction.</description>
|
||||
<field type="uint64_t" name="value"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51010" name="KAPTAN_CONFIG_VALIDATE">
|
||||
<description>Validates the complete open transaction.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51011" name="KAPTAN_CONFIG_COMMIT">
|
||||
<description>Validates then atomically persists the open transaction.</description>
|
||||
<field type="uint64_t" name="expected_generation"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51012" name="KAPTAN_CONFIG_ABORT">
|
||||
<description>Discards the open RAM transaction.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51013" name="KAPTAN_CONFIG_RESULT">
|
||||
<description>Authoritative typed completion for a configuration request.</description>
|
||||
<field type="uint64_t" name="generation"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="transfer_id"/>
|
||||
<field type="uint32_t" name="revision"/>
|
||||
<field type="uint16_t" name="primary_field"/>
|
||||
<field type="uint16_t" name="related_field"/>
|
||||
<field type="uint16_t" name="validation_rule"/>
|
||||
<field type="uint8_t" name="operation" enum="KAPTAN_CONFIG_OPERATION"/>
|
||||
<field type="uint8_t" name="result" enum="KAPTAN_CONFIG_RESULT"/>
|
||||
<field type="uint8_t" name="error" enum="KAPTAN_CONFIG_ERROR"/>
|
||||
<field type="uint8_t" name="config_state" enum="KAPTAN_CONFIG_STATE"/>
|
||||
</message>
|
||||
<message id="51015" name="KAPTAN_CONFIG_SET_BOOL">
|
||||
<description>Writes one boolean field in the open transaction.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="value"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51016" name="KAPTAN_CONFIG_SET_F64">
|
||||
<description>Writes one f64 field in the open transaction.</description>
|
||||
<field type="double" name="value"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="field_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51017" name="KAPTAN_CONFIG_IMPORT_BEGIN">
|
||||
<description>Starts a fixed-bounded CBOR import inside an open transaction.</description>
|
||||
<field type="uint32_t" name="crc32c"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint16_t" name="length"/>
|
||||
<field type="uint8_t[16]" name="schema_id"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51018" name="KAPTAN_CONFIG_IMPORT_CHUNK">
|
||||
<description>One aligned, idempotent 192-byte-or-final CBOR import chunk. Chunks may arrive out of order.</description>
|
||||
<field type="uint8_t[192]" name="data"/>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="transfer_id"/>
|
||||
<field type="uint16_t" name="offset"/>
|
||||
<field type="uint8_t" name="length"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
<message id="51019" name="KAPTAN_CONFIG_IMPORT_FINISH">
|
||||
<description>Validates a complete received CBOR import into the transaction.</description>
|
||||
<field type="uint32_t" name="request_id"/>
|
||||
<field type="uint32_t" name="session_id"/>
|
||||
<field type="uint32_t" name="transfer_id"/>
|
||||
<field type="uint32_t" name="expected_revision"/>
|
||||
<field type="uint8_t" name="target_system"/>
|
||||
<field type="uint8_t" name="target_component"/>
|
||||
</message>
|
||||
</messages>
|
||||
</mavlink>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0"?>
|
||||
<mavlink>
|
||||
<version>3</version>
|
||||
<dialect>0</dialect>
|
||||
<!-- Kaptan-reserved development block. Register these IDs before release. -->
|
||||
<enums>
|
||||
<enum name="KAPTAN_ERROR_FLAGS" bitmask="true">
|
||||
<entry value="2" name="KAPTAN_ERROR_FLAG_TRUNCATED">
|
||||
<description>The path or additional-information UTF-8 prefix was truncated to its bounded on-wire field.</description>
|
||||
</entry>
|
||||
<entry value="4" name="KAPTAN_ERROR_FLAG_COALESCED">
|
||||
<description>Error represents repeated adjacent observations with the same path and additional information.</description>
|
||||
</entry>
|
||||
</enum>
|
||||
</enums>
|
||||
<messages>
|
||||
<message id="51021" name="KAPTAN_ERROR">
|
||||
<description>Bounded derived or explicit runtime error. This is distinct from ordinary KAPTAN_LOG records. The display identity is generated from the Rust error type and variant when a KaptanError-derived value is available; structured configuration failures remain authoritative in KAPTAN_CONFIG_RESULT.</description>
|
||||
<field type="uint8_t" name="flags" enum="KAPTAN_ERROR_FLAGS">Known bits are TRUNCATED=2 and COALESCED=4. Receivers ignore unknown future bits.</field>
|
||||
<field type="uint8_t" name="path_length">Number of valid UTF-8 bytes in path; no more than 96.</field>
|
||||
<field type="uint8_t" name="additional_information_length">Number of valid UTF-8 bytes in additional_information; no more than 64.</field>
|
||||
<field type="uint8_t[96]" name="path">Bounded UTF-8 derived or explicit error path. Bytes after path_length are zero.</field>
|
||||
<field type="uint8_t[64]" name="additional_information">Bounded UTF-8 optional error context. Bytes after additional_information_length are zero.</field>
|
||||
</message>
|
||||
</messages>
|
||||
</mavlink>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0"?>
|
||||
<mavlink>
|
||||
<version>3</version>
|
||||
<dialect>0</dialect>
|
||||
<!-- Kaptan-reserved development block. Register these IDs before release. -->
|
||||
<enums>
|
||||
<enum name="KAPTAN_LOG_FLAGS" bitmask="true">
|
||||
<entry value="1" name="KAPTAN_LOG_FLAG_TRACE">
|
||||
<description>Record originated at Rust trace level and uses MAVLink DEBUG severity.</description>
|
||||
</entry>
|
||||
<entry value="2" name="KAPTAN_LOG_FLAG_TRUNCATED">
|
||||
<description>Message text was truncated to the bounded on-wire buffer.</description>
|
||||
</entry>
|
||||
<entry value="4" name="KAPTAN_LOG_FLAG_COALESCED">
|
||||
<description>Message represents repeated adjacent observations.</description>
|
||||
</entry>
|
||||
</enum>
|
||||
</enums>
|
||||
<messages>
|
||||
<message id="51020" name="KAPTAN_LOG">
|
||||
<description>Bounded human-readable runtime log. The receiver needs only level, flags, and the valid UTF-8 text prefix. MAVLink framing, bounded admission, DMA, retries, and local loss accounting remain platform-owned.</description>
|
||||
<field type="uint8_t" name="level">MAV_SEVERITY-compatible level. Rust TRACE uses DEBUG plus the TRACE flag.</field>
|
||||
<field type="uint8_t" name="flags" enum="KAPTAN_LOG_FLAGS">Known bits are TRACE=1, TRUNCATED=2, and COALESCED=4. Receivers ignore unknown future bits.</field>
|
||||
<field type="uint8_t" name="message_length">Number of valid UTF-8 bytes in message; at most 160.</field>
|
||||
<field type="uint8_t[160]" name="message">Bounded UTF-8 message bytes. Bytes after message_length are zero.</field>
|
||||
</message>
|
||||
</messages>
|
||||
</mavlink>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<mavlink>
|
||||
<version>3</version>
|
||||
<dialect>0</dialect>
|
||||
<!-- Kaptan-reserved development block. Register these IDs before release. -->
|
||||
<enums>
|
||||
<enum name="KAPTAN_SHUTDOWN_REASON">
|
||||
<entry value="1" name="KAPTAN_SHUTDOWN_REASON_OPERATOR">
|
||||
<description>An operator initiated the completed controlled firmware shutdown.</description>
|
||||
</entry>
|
||||
<entry value="2" name="KAPTAN_SHUTDOWN_REASON_SAFETY">
|
||||
<description>The safety owner initiated the completed controlled firmware shutdown.</description>
|
||||
</entry>
|
||||
</enum>
|
||||
</enums>
|
||||
<messages>
|
||||
<message id="51022" name="KAPTAN_SHUTDOWN">
|
||||
<description>Typed completed orderly firmware shutdown observation. It is emitted only after a platform coordinator has inhibited outputs. It is not a log record, a shutdown request, or a panic/hard-fault/reset report.</description>
|
||||
<field type="uint8_t" name="reason" enum="KAPTAN_SHUTDOWN_REASON">Typed shutdown reason.</field>
|
||||
</message>
|
||||
</messages>
|
||||
</mavlink>
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Narrow MAVLink arm/disarm command decoding.
|
||||
//!
|
||||
//! This module deliberately accepts no actuator-value or motor-test command.
|
||||
//! A board must pass accepted requests to its single actuator-state owner; this
|
||||
//! decoder has no access to output hardware.
|
||||
|
||||
use mavlink::Message;
|
||||
|
||||
use crate::{MavlinkFrame, message};
|
||||
|
||||
/// A requested change to the vehicle's arming state.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ArmRequest {
|
||||
/// Request the armed-idle state.
|
||||
Arm,
|
||||
/// Request electrically inactive outputs.
|
||||
Disarm,
|
||||
}
|
||||
|
||||
/// Decodes a targeted MAVLink `MAV_CMD_COMPONENT_ARM_DISARM` command.
|
||||
///
|
||||
/// Only `param1` values exactly equal to `0.0` (disarm) or `1.0` (arm) are
|
||||
/// accepted. Broadcast targets are intentionally rejected: an actuator command
|
||||
/// must name this vehicle and its component explicitly.
|
||||
pub fn decode_arm_request(
|
||||
frame: &MavlinkFrame,
|
||||
system_id: u8,
|
||||
component_id: u8,
|
||||
) -> Option<ArmRequest> {
|
||||
let message = message::MavMessage::parse(
|
||||
mavlink::MavlinkVersion::V2,
|
||||
frame.message_id(),
|
||||
frame.payload(),
|
||||
)
|
||||
.ok()?;
|
||||
|
||||
let message::MavMessage::COMMAND_LONG(command) = message else {
|
||||
return None;
|
||||
};
|
||||
if command.command != message::MavCmd::MAV_CMD_COMPONENT_ARM_DISARM
|
||||
|| command.target_system != system_id
|
||||
|| command.target_component != component_id
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
match command.param1 {
|
||||
0.0 => Some(ArmRequest::Disarm),
|
||||
1.0 => Some(ArmRequest::Arm),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ArmRequest, decode_arm_request};
|
||||
use crate::{MavlinkFrame, message};
|
||||
|
||||
fn command(target_system: u8, target_component: u8, value: f32) -> MavlinkFrame {
|
||||
let mut frame = MavlinkFrame::new();
|
||||
frame.serialize_message_data(
|
||||
message::MavHeader {
|
||||
sequence: 0,
|
||||
system_id: 42,
|
||||
component_id: 7,
|
||||
},
|
||||
&message::COMMAND_LONG_DATA {
|
||||
param1: value,
|
||||
param2: 0.0,
|
||||
param3: 0.0,
|
||||
param4: 0.0,
|
||||
param5: 0.0,
|
||||
param6: 0.0,
|
||||
param7: 0.0,
|
||||
command: message::MavCmd::MAV_CMD_COMPONENT_ARM_DISARM,
|
||||
target_system,
|
||||
target_component,
|
||||
confirmation: 0,
|
||||
},
|
||||
);
|
||||
frame
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_explicit_targeted_arm_and_disarm() {
|
||||
assert_eq!(
|
||||
decode_arm_request(&command(1, 1, 1.0), 1, 1),
|
||||
Some(ArmRequest::Arm)
|
||||
);
|
||||
assert_eq!(
|
||||
decode_arm_request(&command(1, 1, 0.0), 1, 1),
|
||||
Some(ArmRequest::Disarm)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_broadcast_wrong_target_and_invalid_parameter() {
|
||||
assert_eq!(decode_arm_request(&command(0, 0, 1.0), 1, 1), None);
|
||||
assert_eq!(decode_arm_request(&command(2, 1, 1.0), 1, 1), None);
|
||||
assert_eq!(decode_arm_request(&command(1, 1, 0.5), 1, 1), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! MAVLink command decoders.
|
||||
|
||||
/// Targeted arm/disarm command decoding.
|
||||
pub mod arm;
|
||||
@@ -0,0 +1,270 @@
|
||||
//! MAVLink frame encoding API.
|
||||
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::imu::ImuSnapshot;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::optical_flow::OpticalFlowSnapshot;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::range::RangeSnapshot;
|
||||
use mavlink::MessageData;
|
||||
|
||||
use crate::{MavlinkFrame, message};
|
||||
|
||||
/// Board-selected MAVLink metadata for a range sensor.
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DistanceSensorConfig {
|
||||
/// MAVLink sensor instance identifier.
|
||||
pub sensor_id: u8,
|
||||
/// Sensor mounting orientation.
|
||||
pub orientation: message::MavSensorOrientation,
|
||||
/// Lower valid measurement bound, in centimetres.
|
||||
pub minimum_distance_centimetres: u16,
|
||||
/// Upper valid measurement bound, in centimetres.
|
||||
pub maximum_distance_centimetres: u16,
|
||||
}
|
||||
|
||||
/// Serializes FC-domain data with MAVLink sender identity and sequence state.
|
||||
pub struct MavlinkEncoder {
|
||||
system_id: u8,
|
||||
component_id: u8,
|
||||
next_sequence: u8,
|
||||
}
|
||||
|
||||
impl MavlinkEncoder {
|
||||
/// Creates an encoder beginning with MAVLink packet sequence zero.
|
||||
pub const fn new(system_id: u8, component_id: u8) -> Self {
|
||||
Self {
|
||||
system_id,
|
||||
component_id,
|
||||
next_sequence: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize<M: MessageData>(&mut self, message: &M) -> MavlinkFrame {
|
||||
let mut raw = MavlinkFrame::new();
|
||||
raw.serialize_message_data(
|
||||
crate::message::MavHeader {
|
||||
sequence: self.next_sequence,
|
||||
system_id: self.system_id,
|
||||
component_id: self.component_id,
|
||||
},
|
||||
message,
|
||||
);
|
||||
self.next_sequence = self.next_sequence.wrapping_add(1);
|
||||
|
||||
raw
|
||||
}
|
||||
|
||||
/// Encodes one generated MAVLink data record through this endpoint's sole
|
||||
/// header-sequence owner. Runtime-log/config adapters return data records
|
||||
/// and must use this method rather than create a competing encoder.
|
||||
pub fn custom<M: MessageData>(&mut self, message: &M) -> MavlinkFrame {
|
||||
self.serialize(message)
|
||||
}
|
||||
|
||||
/// Encodes a board-I/O heartbeat with its current arming state.
|
||||
pub fn heartbeat(&mut self, system_status: message::MavState, armed: bool) -> MavlinkFrame {
|
||||
let heartbeat = message::HEARTBEAT_DATA {
|
||||
custom_mode: 0,
|
||||
mavtype: message::MavType::MAV_TYPE_ONBOARD_CONTROLLER,
|
||||
autopilot: message::MavAutopilot::MAV_AUTOPILOT_INVALID,
|
||||
base_mode: if armed {
|
||||
message::MavModeFlag::MAV_MODE_FLAG_SAFETY_ARMED
|
||||
} else {
|
||||
message::MavModeFlag::empty()
|
||||
},
|
||||
system_status,
|
||||
mavlink_version: 3,
|
||||
};
|
||||
|
||||
self.serialize(&heartbeat)
|
||||
}
|
||||
|
||||
/// Acknowledges a supported MAVLink command.
|
||||
pub fn command_ack(
|
||||
&mut self,
|
||||
command: message::MavCmd,
|
||||
result: message::MavResult,
|
||||
) -> MavlinkFrame {
|
||||
self.serialize(&message::COMMAND_ACK_DATA { command, result })
|
||||
}
|
||||
|
||||
/// Encodes a standard `RAW_IMU` frame.
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
pub fn raw_imu_snapshot(&mut self, snapshot: &ImuSnapshot) -> MavlinkFrame {
|
||||
let raw_imu = message::RAW_IMU_DATA {
|
||||
time_usec: snapshot.timestamp.as_microseconds(),
|
||||
xacc: snapshot.acceleration_milligravity[0],
|
||||
yacc: snapshot.acceleration_milligravity[1],
|
||||
zacc: snapshot.acceleration_milligravity[2],
|
||||
xgyro: snapshot.angular_rate_milliradians_per_second[0],
|
||||
ygyro: snapshot.angular_rate_milliradians_per_second[1],
|
||||
zgyro: snapshot.angular_rate_milliradians_per_second[2],
|
||||
xmag: 0,
|
||||
ymag: 0,
|
||||
zmag: 0,
|
||||
};
|
||||
|
||||
self.serialize(&raw_imu)
|
||||
}
|
||||
|
||||
/// Encodes a standard `DISTANCE_SENSOR` frame for a laser rangefinder.
|
||||
///
|
||||
/// MAVLink represents distance in centimetres; the sensor domain keeps
|
||||
/// millimetres so this conversion happens only at the protocol boundary.
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
pub fn distance_sensor_snapshot(
|
||||
&mut self,
|
||||
snapshot: &RangeSnapshot,
|
||||
config: DistanceSensorConfig,
|
||||
) -> MavlinkFrame {
|
||||
let current_distance = (snapshot.distance_millimetres / 10).clamp(
|
||||
u32::from(config.minimum_distance_centimetres),
|
||||
u32::from(config.maximum_distance_centimetres),
|
||||
) as u16;
|
||||
let distance_sensor = message::DISTANCE_SENSOR_DATA {
|
||||
time_boot_ms: (snapshot.timestamp.as_microseconds() / 1_000) as u32,
|
||||
min_distance: config.minimum_distance_centimetres,
|
||||
max_distance: config.maximum_distance_centimetres,
|
||||
current_distance,
|
||||
mavtype: message::MavDistanceSensor::MAV_DISTANCE_SENSOR_LASER,
|
||||
id: config.sensor_id,
|
||||
orientation: config.orientation,
|
||||
covariance: u8::MAX,
|
||||
};
|
||||
|
||||
self.serialize(&distance_sensor)
|
||||
}
|
||||
|
||||
/// Encodes a standard `OPTICAL_FLOW` frame from a ground-referenced flow
|
||||
/// observation.
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
pub fn optical_flow_snapshot(
|
||||
&mut self,
|
||||
snapshot: &OpticalFlowSnapshot,
|
||||
sensor_id: u8,
|
||||
) -> MavlinkFrame {
|
||||
let optical_flow = message::OPTICAL_FLOW_DATA {
|
||||
time_usec: snapshot.timestamp.as_microseconds(),
|
||||
sensor_id,
|
||||
// Kaptan's sensor domain contains ground-referenced velocity,
|
||||
// not unscaled image-pixel displacement.
|
||||
flow_x: 0,
|
||||
flow_y: 0,
|
||||
flow_comp_m_x: snapshot.velocity_millimetres_per_second[0] as f32 / 1_000.0,
|
||||
flow_comp_m_y: snapshot.velocity_millimetres_per_second[1] as f32 / 1_000.0,
|
||||
quality: snapshot.quality,
|
||||
ground_distance: snapshot.ground_distance_millimetres as f32 / 1_000.0,
|
||||
};
|
||||
|
||||
self.serialize(&optical_flow)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use super::DistanceSensorConfig;
|
||||
use super::MavlinkEncoder;
|
||||
use crate::message::MavState;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::imu::ImuSnapshot;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::optical_flow::OpticalFlowSnapshot;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_sensor::range::RangeSnapshot;
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
use kaptan_time::Timestamp;
|
||||
|
||||
#[test]
|
||||
fn heartbeat_has_the_configured_sender_and_sequence() {
|
||||
let mut encoder = MavlinkEncoder::new(42, 7);
|
||||
let frame = encoder.heartbeat(MavState::MAV_STATE_STANDBY, false);
|
||||
let bytes = frame.raw_bytes();
|
||||
|
||||
assert_eq!(bytes[0], 0xFD);
|
||||
assert_eq!(bytes[2], 0);
|
||||
assert_eq!(bytes[3], 0);
|
||||
assert_eq!(bytes[4], 0);
|
||||
assert_eq!(bytes[5], 42);
|
||||
assert_eq!(bytes[6], 7);
|
||||
assert_eq!(&bytes[7..10], &[0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heartbeat_preserves_the_requested_health_state() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let frame = encoder.heartbeat(MavState::MAV_STATE_CRITICAL, false);
|
||||
|
||||
assert_eq!(frame.raw_bytes()[17], MavState::MAV_STATE_CRITICAL as u8);
|
||||
}
|
||||
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
#[test]
|
||||
fn snapshot_adapter_uses_flight_data_timestamp_and_units() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let snapshot = ImuSnapshot::new(
|
||||
Timestamp::from_microseconds(123),
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
2_500,
|
||||
);
|
||||
|
||||
let frame = encoder.raw_imu_snapshot(&snapshot);
|
||||
|
||||
assert_eq!(&frame.raw_bytes()[7..10], &[27, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn armed_heartbeat_sets_the_standard_armed_flag() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let frame = encoder.heartbeat(MavState::MAV_STATE_ACTIVE, true);
|
||||
|
||||
assert_ne!(frame.raw_bytes()[16] & 0x80, 0);
|
||||
}
|
||||
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
#[test]
|
||||
fn range_snapshot_uses_distance_sensor_centimetres() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let snapshot = RangeSnapshot::new(Timestamp::from_microseconds(123_000), 2_910);
|
||||
|
||||
let frame = encoder.distance_sensor_snapshot(
|
||||
&snapshot,
|
||||
DistanceSensorConfig {
|
||||
sensor_id: 0,
|
||||
orientation: crate::message::MavSensorOrientation::MAV_SENSOR_ROTATION_PITCH_270,
|
||||
minimum_distance_centimetres: 20,
|
||||
maximum_distance_centimetres: 4_000,
|
||||
},
|
||||
);
|
||||
let bytes = frame.raw_bytes();
|
||||
|
||||
assert_eq!(&bytes[7..10], &[132, 0, 0]);
|
||||
// MAVLink payload starts after the ten-byte MAVLink 2 header. The
|
||||
// current distance field follows time, minimum, and maximum range.
|
||||
assert_eq!(&bytes[18..20], &291u16.to_le_bytes());
|
||||
}
|
||||
|
||||
#[cfg(feature = "sensor-telemetry")]
|
||||
#[test]
|
||||
fn optical_flow_snapshot_uses_the_optical_flow_message() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let snapshot = OpticalFlowSnapshot::new(
|
||||
Timestamp::from_microseconds(123_000),
|
||||
[1_000, -500],
|
||||
2_000,
|
||||
200,
|
||||
);
|
||||
|
||||
let frame = encoder.optical_flow_snapshot(&snapshot, 3);
|
||||
let bytes = frame.raw_bytes();
|
||||
|
||||
assert_eq!(&bytes[7..10], &[100, 0, 0]);
|
||||
// Optical-flow payload begins after the MAVLink 2 header.
|
||||
assert_eq!(&bytes[10..18], &123_000_u64.to_le_bytes());
|
||||
assert_eq!(&bytes[18..22], &1.0_f32.to_le_bytes());
|
||||
assert_eq!(&bytes[22..26], &(-0.5_f32).to_le_bytes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! MAVLink protocol adapter for Kaptan.
|
||||
|
||||
#![no_std]
|
||||
|
||||
/// MAVLink command decoders.
|
||||
pub mod commands;
|
||||
/// MAVLink frame encoding API for boards.
|
||||
pub mod encoder;
|
||||
/// Serial-byte MAVLink receive API for boards.
|
||||
pub mod receiver;
|
||||
/// UART DMA MAVLink frame transmission API for boards.
|
||||
pub mod transmitter;
|
||||
|
||||
/// An owned MAVLink 2 frame suitable for UART transmission.
|
||||
pub type MavlinkFrame = message::MAVLinkV2MessageRaw;
|
||||
|
||||
/// Supported MAVLink message types for Kaptan.
|
||||
pub mod message {
|
||||
pub use mavlink::MAVLinkV2MessageRaw;
|
||||
pub use mavlink::MavHeader;
|
||||
pub use mavlink::Message;
|
||||
pub use mavlink::MessageData;
|
||||
pub use mavlink::dialects::common::*;
|
||||
|
||||
#[cfg(kaptan_has_messages)]
|
||||
include!(concat!(env!("OUT_DIR"), "/mod.rs"));
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! MAVLink serial-byte receive API.
|
||||
|
||||
use crate::{MavlinkFrame, message};
|
||||
|
||||
/// Bounded MAVLink 2 receiver for a board's serial-byte interrupt.
|
||||
///
|
||||
/// Boards pass UART bytes to [`Self::receive_byte`] and take complete frames
|
||||
/// from [`Self::take_received`]. Production has no signing verifier or replay
|
||||
/// state, so it never exposes an inbound MAVLink frame as an authority record.
|
||||
pub struct MavlinkReceiver<const N: usize> {
|
||||
frame: MavlinkFrame,
|
||||
received: usize,
|
||||
expected: usize,
|
||||
frames: [Option<MavlinkFrame>; N],
|
||||
front: usize,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> Default for MavlinkReceiver<N> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> MavlinkReceiver<N> {
|
||||
/// Creates a production receiver with space for `N` complete frames.
|
||||
///
|
||||
/// TODO(signing): accept a frame only after verified MAVLink-v2 signing,
|
||||
/// configured sender/target binding, persistent anti-replay state, and
|
||||
/// provisioning/rotation policy exist together. A V2 CRC only detects
|
||||
/// corruption; it is not authentication.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
frame: MavlinkFrame::new(),
|
||||
received: 0,
|
||||
expected: 0,
|
||||
frames: [None; N],
|
||||
front: 0,
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives one UART byte and returns whether it queued a complete frame.
|
||||
///
|
||||
/// Bytes outside MAVLink 2 frames and frames with invalid CRCs are
|
||||
/// discarded. Signed frames are also discarded because this receiver has
|
||||
/// no verifier or replay state. Until the TODO(signing) work is complete,
|
||||
/// unsigned frames are deliberately not promoted to received records
|
||||
/// either.
|
||||
pub fn receive_byte(&mut self, byte: u8) -> bool {
|
||||
if self.received == 0 {
|
||||
if byte == 0xfd {
|
||||
self.frame.as_mut_slice()[0] = byte;
|
||||
self.received = 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
self.frame.as_mut_slice()[self.received] = byte;
|
||||
self.received += 1;
|
||||
|
||||
if self.received == 10 {
|
||||
let header = self.frame.as_slice();
|
||||
// MAVLink's bit 0 means the packet carries a signature. Reject all
|
||||
// nonzero incompatibility flags until a reviewed signature verifier
|
||||
// and persistent replay policy exist.
|
||||
if header[2] != 0 {
|
||||
self.reset();
|
||||
return false;
|
||||
}
|
||||
self.expected = 1 + 9 + usize::from(header[1]) + 2;
|
||||
}
|
||||
|
||||
if self.expected != 0 && self.received == self.expected {
|
||||
let frame = core::mem::replace(&mut self.frame, MavlinkFrame::new());
|
||||
self.received = 0;
|
||||
self.expected = 0;
|
||||
// The production receiver still drops every inbound frame until
|
||||
// signing/replay verification exists. Validate either known
|
||||
// dialect here so a future verifier receives no CRC-corrupt
|
||||
// custom configuration message.
|
||||
if !has_valid_known_crc(&frame) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Discards the in-progress frame after a UART transport fault.
|
||||
pub fn reset(&mut self) {
|
||||
self.frame = MavlinkFrame::new();
|
||||
self.received = 0;
|
||||
self.expected = 0;
|
||||
}
|
||||
|
||||
/// Takes the oldest complete received frame, if one is available.
|
||||
///
|
||||
/// The production receiver returns no frame until signing verification is
|
||||
/// implemented, but retaining this API keeps dispatch ownership explicit.
|
||||
pub fn take_received(&mut self) -> Option<MavlinkFrame> {
|
||||
if self.length == 0 {
|
||||
return None;
|
||||
}
|
||||
let frame = self.frames[self.front].take();
|
||||
self.front = (self.front + 1) % N;
|
||||
self.length -= 1;
|
||||
frame
|
||||
}
|
||||
|
||||
/// Returns whether at least one complete frame awaits dispatch.
|
||||
pub const fn has_received(&self) -> bool {
|
||||
self.length != 0
|
||||
}
|
||||
}
|
||||
|
||||
fn has_valid_known_crc(frame: &MavlinkFrame) -> bool {
|
||||
let common_valid = frame.has_valid_crc::<message::MavMessage>();
|
||||
#[cfg(feature = "dialect-kaptan")]
|
||||
{
|
||||
common_valid || frame.has_valid_crc::<message::kaptan::MavMessage>()
|
||||
}
|
||||
#[cfg(not(feature = "dialect-kaptan"))]
|
||||
{
|
||||
common_valid
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::MavlinkReceiver;
|
||||
use crate::{MavlinkFrame, message};
|
||||
|
||||
fn heartbeat(sequence: u8) -> MavlinkFrame {
|
||||
let mut frame = MavlinkFrame::new();
|
||||
frame.serialize_message_data(
|
||||
message::MavHeader {
|
||||
sequence,
|
||||
system_id: 42,
|
||||
component_id: 7,
|
||||
},
|
||||
&message::HEARTBEAT_DATA {
|
||||
custom_mode: 0,
|
||||
mavtype: message::MavType::MAV_TYPE_QUADROTOR,
|
||||
autopilot: message::MavAutopilot::MAV_AUTOPILOT_GENERIC,
|
||||
base_mode: message::MavModeFlag::empty(),
|
||||
system_status: message::MavState::MAV_STATE_STANDBY,
|
||||
mavlink_version: 3,
|
||||
},
|
||||
);
|
||||
frame
|
||||
}
|
||||
|
||||
fn heartbeat_v1(sequence: u8) -> mavlink::MAVLinkV1MessageRaw {
|
||||
let mut frame = mavlink::MAVLinkV1MessageRaw::new();
|
||||
frame.serialize_message_data(
|
||||
message::MavHeader {
|
||||
sequence,
|
||||
system_id: 42,
|
||||
component_id: 7,
|
||||
},
|
||||
&message::HEARTBEAT_DATA {
|
||||
custom_mode: 0,
|
||||
mavtype: message::MavType::MAV_TYPE_QUADROTOR,
|
||||
autopilot: message::MavAutopilot::MAV_AUTOPILOT_GENERIC,
|
||||
base_mode: message::MavModeFlag::empty(),
|
||||
system_status: message::MavState::MAV_STATE_STANDBY,
|
||||
mavlink_version: 3,
|
||||
},
|
||||
);
|
||||
frame
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discards_a_crc_valid_mavlink_v1_frame() {
|
||||
let mut receiver = MavlinkReceiver::<1>::new();
|
||||
let v1 = heartbeat_v1(3);
|
||||
assert_eq!(v1.raw_bytes()[0], 0xfe);
|
||||
|
||||
for byte in v1.raw_bytes() {
|
||||
assert!(!receiver.receive_byte(*byte));
|
||||
}
|
||||
|
||||
assert_eq!(receiver.take_received(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_rejects_unsigned_frames_without_a_signing_verifier() {
|
||||
let frame = heartbeat(0);
|
||||
let mut receiver = MavlinkReceiver::<1>::new();
|
||||
for byte in frame.raw_bytes() {
|
||||
assert!(!receiver.receive_byte(*byte));
|
||||
}
|
||||
assert!(!receiver.has_received());
|
||||
assert_eq!(receiver.take_received(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_signed_v2_before_accepting_any_payload() {
|
||||
let mut receiver = MavlinkReceiver::<1>::new();
|
||||
// The first ten bytes contain the complete MAVLink 2 header. This
|
||||
// frame advertises a signature (incompatibility bit 0), so rejection
|
||||
// happens before its payload can be considered.
|
||||
for byte in [0xfd, 0, 1, 0, 0, 1, 1, 0, 0, 0] {
|
||||
assert!(!receiver.receive_byte(byte));
|
||||
}
|
||||
assert!(!receiver.has_received());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crc_error_cannot_create_a_received_record() {
|
||||
let frame = heartbeat(0);
|
||||
let mut bytes = frame.into_inner();
|
||||
bytes[10] ^= 1;
|
||||
let corrupt = MavlinkFrame::from_bytes_unparsed(bytes);
|
||||
let mut receiver = MavlinkReceiver::<1>::new();
|
||||
|
||||
for byte in corrupt.raw_bytes() {
|
||||
assert!(!receiver.receive_byte(*byte));
|
||||
}
|
||||
assert!(!receiver.has_received());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! MAVLink frame encoding and UART transmission API.
|
||||
|
||||
use kaptan_dma::{DmaTxBufferFactory, DmaTxEngine, TxCompletion};
|
||||
use kaptan_log::KaptanError;
|
||||
use kaptan_tx::{PendingFrame, TransmitQueue};
|
||||
|
||||
use crate::MavlinkFrame;
|
||||
|
||||
/// Delivery importance used for bounded MAVLink transmission admission.
|
||||
pub use kaptan_tx::{EnqueueResult, FrameClass};
|
||||
|
||||
/// Failure while preparing or starting a MAVLink frame transfer.
|
||||
#[derive(Debug, KaptanError)]
|
||||
pub enum MavlinkTransmitFault<MemoryError, EngineError> {
|
||||
/// DMA-visible frame preparation failed.
|
||||
Memory(MemoryError),
|
||||
/// The UART DMA route rejected a transfer start.
|
||||
Engine(EngineError),
|
||||
}
|
||||
|
||||
/// Transport-neutral class of a terminal link fault.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum TransmitFaultKind {
|
||||
/// DMA-visible frame preparation failed.
|
||||
Memory,
|
||||
/// The UART DMA engine rejected a transfer start.
|
||||
Engine,
|
||||
/// An active DMA transfer ended with a terminal fault or halt.
|
||||
Terminal,
|
||||
}
|
||||
|
||||
impl<MemoryError, EngineError> MavlinkTransmitFault<MemoryError, EngineError> {
|
||||
/// Returns the bounded category a platform may convert to a static log
|
||||
/// message without exposing a generic HAL error value on the wire.
|
||||
pub const fn kind(&self) -> TransmitFaultKind {
|
||||
match self {
|
||||
Self::Memory(_) => TransmitFaultKind::Memory,
|
||||
Self::Engine(_) => TransmitFaultKind::Engine,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined bounded-admission and DMA-start outcome.
|
||||
///
|
||||
/// The two outcomes stay distinct so a platform can account for a failed DMA
|
||||
/// start without falsely treating a queue-full source frame as retained.
|
||||
#[must_use]
|
||||
pub struct AdmissionStart<MemoryError, EngineError> {
|
||||
/// Queue admission for the source frame.
|
||||
pub admission: EnqueueResult,
|
||||
/// One bounded attempt to start pending DMA work.
|
||||
pub start: Result<(), MavlinkTransmitFault<MemoryError, EngineError>>,
|
||||
}
|
||||
|
||||
/// Owns MAVLink frame admission and UART DMA lifecycle.
|
||||
///
|
||||
/// Exactly one worker invokes this type. It accepts local encoded frames and
|
||||
/// received frames alike; the caller owns the policy that decides which frames
|
||||
/// are transmitted.
|
||||
pub struct MavlinkTransmitter<Memory, Engine, const N: usize> {
|
||||
transmit: TransmitQueue<MavlinkFrame, N>,
|
||||
memory: Memory,
|
||||
engine: Engine,
|
||||
}
|
||||
|
||||
impl<Memory, Engine, const N: usize> MavlinkTransmitter<Memory, Engine, N> {
|
||||
/// Creates an empty MAVLink transmitter.
|
||||
pub const fn new(memory: Memory, engine: Engine) -> Self {
|
||||
Self {
|
||||
transmit: TransmitQueue::new(),
|
||||
memory,
|
||||
engine,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Memory, Engine, const N: usize> MavlinkTransmitter<Memory, Engine, N>
|
||||
where
|
||||
Memory: DmaTxBufferFactory,
|
||||
Engine: DmaTxEngine,
|
||||
{
|
||||
/// Admits an already-serialized MAVLink frame for UART transmission.
|
||||
///
|
||||
/// A full queue is a normal bounded-admission outcome, returned as
|
||||
/// [`EnqueueResult`]. DMA preparation and transfer-start failures remain
|
||||
/// [`MavlinkTransmitFault`] errors.
|
||||
pub fn send_frame(
|
||||
&mut self,
|
||||
class: FrameClass,
|
||||
frame: MavlinkFrame,
|
||||
) -> Result<EnqueueResult, MavlinkTransmitFault<Memory::Error, Engine::StartError>> {
|
||||
let outcome = self.admit_and_start(class, frame);
|
||||
outcome.start.map(|()| outcome.admission)
|
||||
}
|
||||
|
||||
/// Admits one frame and attempts one bounded DMA start while preserving
|
||||
/// both outcomes. Platform policy uses this to account for a failed DMA
|
||||
/// start without mistaking an admission rejection for a retained frame.
|
||||
/// A start failure retains the selected frame in the queue reservation for
|
||||
/// a later service-turn retry.
|
||||
pub fn admit_and_start(
|
||||
&mut self,
|
||||
class: FrameClass,
|
||||
frame: MavlinkFrame,
|
||||
) -> AdmissionStart<Memory::Error, Engine::StartError> {
|
||||
let admission = self.enqueue_frame(class, frame);
|
||||
let start = self.start_pending();
|
||||
AdmissionStart { admission, start }
|
||||
}
|
||||
|
||||
/// Admits a frame without attempting to start the DMA engine.
|
||||
///
|
||||
/// This split lifecycle is for hardware routes whose terminal DMA IRQ can
|
||||
/// arrive a few bus cycles before the stream's `EN` bit reads clear. Such
|
||||
/// a route may acknowledge a completion, retain the selected frame, and
|
||||
/// retry [`Self::start_pending`] from its next bounded service turn rather
|
||||
/// than treating that transient `Busy` observation as a transport fault.
|
||||
/// Callers still own the policy for a queue-full result.
|
||||
pub fn enqueue_frame(&mut self, class: FrameClass, frame: MavlinkFrame) -> EnqueueResult {
|
||||
self.transmit.enqueue(PendingFrame { class, frame })
|
||||
}
|
||||
|
||||
/// Attempts to start one pending DMA frame.
|
||||
///
|
||||
/// A rejected engine start leaves the exact frame reserved for a later
|
||||
/// retry. This method therefore does not discard or overwrite DMA source
|
||||
/// storage on a transient hardware-not-ready result.
|
||||
pub fn start_pending(
|
||||
&mut self,
|
||||
) -> Result<(), MavlinkTransmitFault<Memory::Error, Engine::StartError>> {
|
||||
self.start_next()
|
||||
}
|
||||
|
||||
/// Releases a terminal DMA frame and opportunistically starts the next.
|
||||
///
|
||||
/// The returned class is the frame that reached a terminal DMA result,
|
||||
/// not a class selected from newly pending work. A policy can therefore
|
||||
/// distinguish completion classes without inferring them from newly
|
||||
/// pending work.
|
||||
pub fn on_dma_complete(
|
||||
&mut self,
|
||||
completion: TxCompletion,
|
||||
) -> Result<Option<FrameClass>, MavlinkTransmitFault<Memory::Error, Engine::StartError>> {
|
||||
let completed = self.complete_dma(completion)?;
|
||||
if completion == TxCompletion::Complete {
|
||||
self.start_pending()?;
|
||||
}
|
||||
Ok(completed)
|
||||
}
|
||||
|
||||
/// Releases the active frame after a terminal DMA result without starting
|
||||
/// another one.
|
||||
///
|
||||
/// Most routes use [`Self::on_dma_complete`], which preserves legacy
|
||||
/// immediate restart behavior. A route whose hardware exposes terminal
|
||||
/// status before its enable bit is observably low uses this method and
|
||||
/// calls [`Self::start_pending`] from a later bounded service turn.
|
||||
pub fn complete_dma(
|
||||
&mut self,
|
||||
completion: TxCompletion,
|
||||
) -> Result<Option<FrameClass>, MavlinkTransmitFault<Memory::Error, Engine::StartError>> {
|
||||
match completion {
|
||||
TxCompletion::NotPending => Ok(None),
|
||||
TxCompletion::Complete => Ok(self.transmit.complete().map(|frame| frame.class)),
|
||||
TxCompletion::TransferFault | TxCompletion::Halted => {
|
||||
Ok(self.transmit.fail().map(|frame| frame.class))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_next(
|
||||
&mut self,
|
||||
) -> Result<(), MavlinkTransmitFault<Memory::Error, Engine::StartError>> {
|
||||
let (transmit, memory, engine) = (&mut self.transmit, &mut self.memory, &mut self.engine);
|
||||
transmit
|
||||
.start_with(|frame| {
|
||||
let buffer = memory
|
||||
.prepare(frame.raw_bytes())
|
||||
.map_err(MavlinkTransmitFault::Memory)?;
|
||||
engine.start(buffer).map_err(MavlinkTransmitFault::Engine)
|
||||
})
|
||||
.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{EnqueueResult, FrameClass, MavlinkTransmitFault, MavlinkTransmitter};
|
||||
use crate::{encoder::MavlinkEncoder, message::MavState};
|
||||
use kaptan_dma::{DmaReadableBuffer, DmaTxBufferFactory, DmaTxEngine, TxCompletion};
|
||||
|
||||
struct Memory;
|
||||
|
||||
impl DmaTxBufferFactory for Memory {
|
||||
type Error = core::convert::Infallible;
|
||||
|
||||
fn prepare<'a>(&mut self, bytes: &'a [u8]) -> Result<DmaReadableBuffer<'a>, Self::Error> {
|
||||
// SAFETY: this host-only test keeps the queue's active frame alive.
|
||||
Ok(unsafe { DmaReadableBuffer::new_unchecked(bytes) })
|
||||
}
|
||||
}
|
||||
|
||||
struct Engine;
|
||||
|
||||
impl DmaTxEngine for Engine {
|
||||
type StartError = core::convert::Infallible;
|
||||
|
||||
fn start(&mut self, _: DmaReadableBuffer<'_>) -> Result<(), Self::StartError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct RecordingEngine {
|
||||
started_sequences: [u8; 4],
|
||||
starts: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum RetryError {
|
||||
Busy,
|
||||
}
|
||||
|
||||
struct BusyOnceEngine {
|
||||
busy_once: bool,
|
||||
starts: usize,
|
||||
}
|
||||
|
||||
impl DmaTxEngine for BusyOnceEngine {
|
||||
type StartError = RetryError;
|
||||
|
||||
fn start(&mut self, _: DmaReadableBuffer<'_>) -> Result<(), Self::StartError> {
|
||||
if self.busy_once {
|
||||
self.busy_once = false;
|
||||
return Err(RetryError::Busy);
|
||||
}
|
||||
self.starts += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl DmaTxEngine for RecordingEngine {
|
||||
type StartError = core::convert::Infallible;
|
||||
|
||||
fn start(&mut self, buffer: DmaReadableBuffer<'_>) -> Result<(), Self::StartError> {
|
||||
self.started_sequences[self.starts] = buffer.bytes()[4];
|
||||
self.starts += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfer_fault_drops_only_the_active_frame() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let mut transmitter = MavlinkTransmitter::<Memory, Engine, 2>::new(Memory, Engine);
|
||||
transmitter
|
||||
.send_frame(
|
||||
FrameClass::BestEffort,
|
||||
encoder.heartbeat(MavState::MAV_STATE_STANDBY, false),
|
||||
)
|
||||
.unwrap();
|
||||
transmitter
|
||||
.send_frame(
|
||||
FrameClass::BestEffort,
|
||||
encoder.heartbeat(MavState::MAV_STATE_STANDBY, false),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(transmitter.transmit.is_active());
|
||||
|
||||
transmitter
|
||||
.on_dma_complete(TxCompletion::TransferFault)
|
||||
.unwrap();
|
||||
assert!(!transmitter.transmit.is_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_critical_queue_saturation_to_the_policy_owner() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let mut transmitter = MavlinkTransmitter::<Memory, Engine, 1>::new(Memory, Engine);
|
||||
|
||||
assert_eq!(
|
||||
transmitter
|
||||
.send_frame(
|
||||
FrameClass::Critical,
|
||||
encoder.heartbeat(MavState::MAV_STATE_STANDBY, false),
|
||||
)
|
||||
.unwrap(),
|
||||
EnqueueResult::Enqueued
|
||||
);
|
||||
assert_eq!(
|
||||
transmitter
|
||||
.send_frame(
|
||||
FrameClass::Critical,
|
||||
encoder.heartbeat(MavState::MAV_STATE_STANDBY, false),
|
||||
)
|
||||
.unwrap(),
|
||||
EnqueueResult::Enqueued
|
||||
);
|
||||
assert_eq!(
|
||||
transmitter
|
||||
.send_frame(
|
||||
FrameClass::Critical,
|
||||
encoder.heartbeat(MavState::MAV_STATE_STANDBY, false),
|
||||
)
|
||||
.unwrap(),
|
||||
EnqueueResult::CriticalQueueFull
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_completion_can_defer_a_transient_engine_busy_without_losing_frame_order() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let mut transmitter = MavlinkTransmitter::<Memory, BusyOnceEngine, 2>::new(
|
||||
Memory,
|
||||
BusyOnceEngine {
|
||||
busy_once: false,
|
||||
starts: 0,
|
||||
},
|
||||
);
|
||||
let state = MavState::MAV_STATE_STANDBY;
|
||||
|
||||
transmitter.enqueue_frame(FrameClass::Critical, encoder.heartbeat(state, false));
|
||||
transmitter.start_pending().unwrap();
|
||||
assert_eq!(transmitter.engine.starts, 1);
|
||||
transmitter.enqueue_frame(FrameClass::Critical, encoder.heartbeat(state, false));
|
||||
|
||||
// Model the STM32 case: TCIF is acknowledged but CR.EN still reports
|
||||
// busy for the first attempt to start the successor. `complete_dma`
|
||||
// deliberately does not start it in the terminal IRQ path.
|
||||
assert_eq!(
|
||||
transmitter.complete_dma(TxCompletion::Complete).unwrap(),
|
||||
Some(FrameClass::Critical)
|
||||
);
|
||||
assert_eq!(transmitter.engine.starts, 1);
|
||||
transmitter.engine.busy_once = true;
|
||||
assert!(matches!(
|
||||
transmitter.start_pending(),
|
||||
Err(MavlinkTransmitFault::Engine(RetryError::Busy))
|
||||
));
|
||||
assert!(!transmitter.transmit.is_active());
|
||||
|
||||
transmitter.start_pending().unwrap();
|
||||
assert!(transmitter.transmit.is_active());
|
||||
assert_eq!(transmitter.engine.starts, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_retry_starts_pending_best_effort_before_later_critical_frame() {
|
||||
let mut encoder = MavlinkEncoder::new(1, 1);
|
||||
let mut transmitter = MavlinkTransmitter::<Memory, RecordingEngine, 3>::new(
|
||||
Memory,
|
||||
RecordingEngine {
|
||||
started_sequences: [0; 4],
|
||||
starts: 0,
|
||||
},
|
||||
);
|
||||
let state = MavState::MAV_STATE_STANDBY;
|
||||
|
||||
// A critical frame is active. A best-effort sample arrives behind it
|
||||
// before DMA completion.
|
||||
transmitter.enqueue_frame(FrameClass::Critical, encoder.heartbeat(state, false));
|
||||
transmitter.start_pending().unwrap();
|
||||
transmitter.enqueue_frame(FrameClass::BestEffort, encoder.heartbeat(state, false));
|
||||
|
||||
// The completion worker performs its bounded retry before the next
|
||||
// periodic sender can enqueue fresh critical traffic. The existing
|
||||
// best-effort frame therefore cannot starve behind later traffic.
|
||||
transmitter.complete_dma(TxCompletion::Complete).unwrap();
|
||||
transmitter.start_pending().unwrap();
|
||||
transmitter.enqueue_frame(FrameClass::Critical, encoder.heartbeat(state, false));
|
||||
|
||||
assert_eq!(transmitter.engine.starts, 2);
|
||||
assert_eq!(&transmitter.engine.started_sequences[..2], &[0, 1]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user