refactor: move firmware workspace under firmware

This commit is contained in:
Onur Özkan committed 2026-08-10 16:58:55 +03:00
1 parent 153b0bf262
commit f03fc119a4
222 files changed
+56 -13

No files matched your search

@@ -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;
+270
View File
@@ -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());
}
}
+27
View File
@@ -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]);
}
}