feat(control): 添加选手 FPS 键鼠操作与 C3 用户 UART 输出
This commit is contained in:
43 files changed
+2389
-77
No files matched your search
@@ -3,10 +3,9 @@
|
||||
# CONFIG_IDF_TARGET 必须显式写出来:本机装的是通用 ESP-IDF,默认目标是 ESP32,
|
||||
# 不写这一行会按 ESP32 去配 ADC/RMT 通道,编译期就报"没有这个外设"。
|
||||
#
|
||||
# 串口调试走 UART0(RXD = GPIO20 / TXD = GPIO21,115200 8N1)——这是 C3 的 ROM
|
||||
# 默认控制台引脚,和参考固件里给 DBUS 用的那两个脚是同一对。想改成 USB
|
||||
# Serial/JTAG 输出,把 CONFIG_ESP_CONSOLE_UART_DEFAULT 换成
|
||||
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG 即可。
|
||||
# RXD = GPIO20 / TXD = GPIO21 专用于用户操控协议(115200 8N1)。
|
||||
# 应用与二级引导日志走原生 USB;ROM 启动阶段仍可能从 GPIO21 输出日志,
|
||||
# 外部控制器必须按帧头、长度和 CRC 接收,不得将任意启动字节解释为操控。
|
||||
CONFIG_IDF_TARGET="esp32c3"
|
||||
|
||||
# 4 MB flash;应用分区放到 2 MB(见 partitions.csv),默认的 1 MB 单 app 槽对
|
||||
@@ -14,15 +13,14 @@ CONFIG_IDF_TARGET="esp32c3"
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
|
||||
# 调试口 = UART0(GPIO20 RX / GPIO21 TX)。
|
||||
#
|
||||
# 同时打开 USB Serial/JTAG 作为**次**控制台:日志会同时从板上那个原生 USB 口出来。
|
||||
# 这样现场两种接法都能看到日志 —— 接了 USB-TTL 到 RXD/TXD 的看 UART0,直接插板上
|
||||
# USB 口的看 USB。主控制台仍是 UART0,所以"RXD/TXD 就是调试口"这条成立。
|
||||
#
|
||||
# 只用原生 USB 口烧录(不接 USB-TTL)时,这一条是能看见日志的唯一办法。
|
||||
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
|
||||
# USB Serial/JTAG 是唯一软件控制台;UART1 经 GPIO Matrix 使用用户 RXD/TXD。
|
||||
# CONFIG_ESP_CONSOLE_UART_DEFAULT is not set
|
||||
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||
# CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG is not set
|
||||
CONFIG_ESP_CONSOLE_SECONDARY_NONE=y
|
||||
|
||||
# 1 ms 调度刻度,支持操控任务 5 ms 轮询及 20 ms UART 输出。
|
||||
CONFIG_FREERTOS_HZ=1000
|
||||
|
||||
# Rust 的 main 与规则层在同一个任务栈上跑,另外 log 会用到一些栈;默认 3.5 KB
|
||||
# 在带 WiFi 的固件里容易爆栈。
|
||||
|
||||
@@ -28,17 +28,20 @@
|
||||
//! armor/scripts/flash.sh # 编译 + espflash + 串口日志
|
||||
//! ```
|
||||
//!
|
||||
//! 串口调试走 UART0:RXD = GPIO20 / TXD = GPIO21,115200 8N1(日志从 TX 出来,
|
||||
//! RX 目前空闲,留给以后加命令通道)。USB Serial/JTAG 配成了次控制台,所以插原生
|
||||
//! USB 口也能看到同一份日志。完整接线表、协议与踩坑见 `armor/README.md`。
|
||||
//! 用户 UART:RXD = GPIO20 / TXD = GPIO21,115200 8N1,输出带校验的操控帧。
|
||||
//! 软件日志只走原生 USB Serial/JTAG;UART 接收端须忽略 ROM 启动杂字节。
|
||||
//! 完整接线表、协议与踩坑见 `armor/README.md`。
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration, PmfConfiguration};
|
||||
use esp_idf_svc::eventloop::EspSystemEventLoop;
|
||||
use esp_idf_svc::hal::gpio::{PinDriver, Pull};
|
||||
use esp_idf_svc::hal::gpio::{AnyInputPin, AnyOutputPin, PinDriver, Pull};
|
||||
use esp_idf_svc::hal::peripherals::Peripherals;
|
||||
use esp_idf_svc::hal::uart::{config::Config as UartConfig, UartDriver};
|
||||
use esp_idf_svc::hal::units::Hertz;
|
||||
use esp_idf_svc::nvs::EspDefaultNvsPartition;
|
||||
use esp_idf_svc::wifi::EspWifi;
|
||||
use log::{info, warn};
|
||||
@@ -50,6 +53,7 @@ use armor_protocol::{
|
||||
mod esp;
|
||||
mod leds;
|
||||
mod net;
|
||||
mod operator_uart;
|
||||
mod piezo;
|
||||
mod settings;
|
||||
|
||||
@@ -71,7 +75,7 @@ const THRESHOLD_ENV: &str = match option_env!("ARMOR_THRESHOLD") {
|
||||
/// "装甲板未接入"。
|
||||
const REPORT_HEARTBEAT_MS: u64 = 200;
|
||||
|
||||
/// 状态行的打印周期(UART 调试口)。
|
||||
/// 状态行的打印周期(原生 USB 调试口)。
|
||||
const STATUS_INTERVAL_MS: u64 = 1000;
|
||||
|
||||
/// WiFi 断线检查周期。
|
||||
@@ -117,7 +121,7 @@ fn main() -> Result<()> {
|
||||
|
||||
info!("pins: ws2812 front=IO10 rear=IO5 left=IO6 right=IO7");
|
||||
info!("pins: piezo front=GPIO0 rear=GPIO4 left=GPIO3 right=GPIO1");
|
||||
info!("pins: boot=GPIO9 debug uart0 rxd=GPIO20 txd=GPIO21 115200 8N1");
|
||||
info!("pins: boot=GPIO9 operator uart1 rxd=GPIO20 txd=GPIO21 115200 8N1; logs=USB");
|
||||
info!(
|
||||
"armor board: team={team} ({}), {} hp, -{} per hit, {} ms dark on the hit strip",
|
||||
"client-selected",
|
||||
@@ -140,8 +144,19 @@ fn main() -> Result<()> {
|
||||
warn!("Wi-Fi connection attempt failed: {err:#}");
|
||||
}
|
||||
|
||||
let reporter = net::Reporter::new()?;
|
||||
let reporter = Arc::new(net::Reporter::new()?);
|
||||
let sender_id = net::local_id();
|
||||
let uart = UartDriver::new(
|
||||
peripherals.uart1,
|
||||
peripherals.pins.gpio21,
|
||||
peripherals.pins.gpio20,
|
||||
None::<AnyInputPin>,
|
||||
None::<AnyOutputPin>,
|
||||
&UartConfig::default()
|
||||
.baudrate(Hertz(115_200))
|
||||
.tx_fifo_size(0),
|
||||
)?;
|
||||
let (commands, operator_status) = operator_uart::start(Arc::clone(&reporter), sender_id, uart)?;
|
||||
|
||||
let mut hits: Vec<(Plate, u16)> = Vec::with_capacity(16);
|
||||
let mut reports = ReportSchedule::new(Duration::from_millis(REPORT_HEARTBEAT_MS));
|
||||
@@ -167,11 +182,19 @@ fn main() -> Result<()> {
|
||||
client.disconnect();
|
||||
damage.disconnect();
|
||||
} else {
|
||||
for _ in 0..8 {
|
||||
match reporter.receive() {
|
||||
Ok(Some((net::ControlCommand::Team(command), from))) => {
|
||||
for _ in 0..32 {
|
||||
let Ok(message) = commands.try_recv() else {
|
||||
break;
|
||||
};
|
||||
let from = message.source;
|
||||
let received_at = message.received_at;
|
||||
let processed_at = Duration::from_millis(now_ms());
|
||||
let age = processed_at.saturating_sub(received_at);
|
||||
match message.command {
|
||||
net::ControlCommand::Team(command) => {
|
||||
if command.board_id == sender_id
|
||||
&& client.accept(from, now)
|
||||
&& age < armor_protocol::CLIENT_LEASE
|
||||
&& client.accept(from, received_at)
|
||||
&& team != command.team
|
||||
{
|
||||
team = command.team;
|
||||
@@ -183,17 +206,18 @@ fn main() -> Result<()> {
|
||||
force_report = true;
|
||||
}
|
||||
}
|
||||
Ok(Some((net::ControlCommand::Damage(command), from))) => {
|
||||
if command.board_id == sender_id {
|
||||
damage.accept(command, from, now);
|
||||
net::ControlCommand::Damage(command) => {
|
||||
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||
damage.accept(command, from, received_at);
|
||||
}
|
||||
}
|
||||
Ok(Some((net::ControlCommand::Reset(mut command), from))) => {
|
||||
if command.board_id == sender_id {
|
||||
if let Some(apply) = damage.accept_reset(command, from, now) {
|
||||
net::ControlCommand::Reset(mut command) => {
|
||||
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||
if let Some(apply) = damage.accept_reset(command, from, processed_at) {
|
||||
if apply {
|
||||
armor.set_damage_enabled(false);
|
||||
armor.reset();
|
||||
operator_status.reset();
|
||||
warn!(
|
||||
"referee reset: hp={} reset_id={}",
|
||||
armor.hp(),
|
||||
@@ -210,11 +234,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(err) => {
|
||||
warn!("client control receive failed: {err:#}");
|
||||
break;
|
||||
}
|
||||
net::ControlCommand::Operator(_) | net::ControlCommand::Ignored => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,6 +253,7 @@ fn main() -> Result<()> {
|
||||
|
||||
for (plate, raw) in hits.iter().copied() {
|
||||
if let Some(event) = armor.on_sample(plate, raw, now) {
|
||||
operator_status.set_alive(event.hp > 0);
|
||||
info!(
|
||||
"hit plate={} raw={} hp={} (hits={}, damage_enabled={})",
|
||||
event.plate.name(),
|
||||
@@ -264,6 +285,7 @@ fn main() -> Result<()> {
|
||||
match button_fsm.tick(button.is_low(), now) {
|
||||
ButtonEvent::LongPress => {
|
||||
armor.reset();
|
||||
operator_status.reset();
|
||||
warn!("BOOT long press: hp reset to {} (new round)", armor.hp());
|
||||
force_report = true;
|
||||
}
|
||||
@@ -351,7 +373,7 @@ fn status_with_link(
|
||||
)
|
||||
}
|
||||
|
||||
/// 一行状态,给 UART 调试口用。
|
||||
/// 一行状态,给原生 USB 调试口用。
|
||||
///
|
||||
/// `peak` 是这一秒里每路 ADC 的峰值。它比"有没有受击"更有用:现场要判断阈值该调到
|
||||
/// 多少,靠的就是"没敲时的底噪"和"敲击时的幅度"这两个数字。
|
||||
|
||||
@@ -21,12 +21,17 @@ use anyhow::{anyhow, Result};
|
||||
use esp_idf_svc::sys as ffi;
|
||||
use log::{info, warn};
|
||||
|
||||
use armor_protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_PORT, BROADCAST_ADDR};
|
||||
use armor_protocol::{
|
||||
ArmorControl, ArmorDamageControl, ArmorReset, OperatorControl, ARMOR_PORT, BROADCAST_ADDR,
|
||||
};
|
||||
|
||||
pub enum ControlCommand {
|
||||
Team(ArmorControl),
|
||||
Damage(ArmorDamageControl),
|
||||
Reset(ArmorReset),
|
||||
Operator(OperatorControl),
|
||||
/// A consumed datagram which is not a supported control message.
|
||||
Ignored,
|
||||
}
|
||||
|
||||
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
||||
@@ -72,7 +77,7 @@ pub struct Reporter {
|
||||
}
|
||||
|
||||
impl Reporter {
|
||||
/// 每轮最多由调用方读取 8 包,避免无关流量占住受击循环。
|
||||
/// 只由操控线程接收,每轮有界读取;未知包也计入本轮额度。
|
||||
pub fn receive(&self) -> Result<Option<(ControlCommand, SocketAddrV4)>> {
|
||||
let mut bytes = [0u8; 256];
|
||||
let mut addr: ffi::sockaddr_in = unsafe { core::mem::zeroed() };
|
||||
@@ -101,8 +106,10 @@ impl Reporter {
|
||||
ControlCommand::Damage(control)
|
||||
} else if let Some(control) = ArmorReset::decode(bytes) {
|
||||
ControlCommand::Reset(control)
|
||||
} else if let Some(control) = OperatorControl::decode(bytes) {
|
||||
ControlCommand::Operator(control)
|
||||
} else {
|
||||
return Ok(None);
|
||||
ControlCommand::Ignored
|
||||
};
|
||||
let ip = std::net::Ipv4Addr::from(addr.sin_addr.s_addr.to_le_bytes());
|
||||
Ok(Some((
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! 单独处理操控收包、租约和 UART 输出,不受 ADC 帧等待影响。
|
||||
|
||||
use std::net::SocketAddrV4;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use armor_protocol::{DamageLink, OperatorLink, UartControlFrame};
|
||||
use esp_idf_svc::hal::uart::UartDriver;
|
||||
|
||||
use crate::net::{ControlCommand, Reporter};
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(5);
|
||||
const OUTPUT_INTERVAL_MS: u64 = 20;
|
||||
const MAX_RECEIVE_PER_POLL: usize = 32;
|
||||
|
||||
/// 旧业务保留接收时刻,主循环不得用排队后的处理时刻延长租约。
|
||||
pub struct ReceivedCommand {
|
||||
pub command: ControlCommand,
|
||||
pub source: SocketAddrV4,
|
||||
pub received_at: Duration,
|
||||
}
|
||||
|
||||
pub struct BoardStatus {
|
||||
alive: AtomicBool,
|
||||
resets: AtomicU32,
|
||||
}
|
||||
|
||||
impl BoardStatus {
|
||||
pub fn set_alive(&self, alive: bool) {
|
||||
self.alive.store(alive, Ordering::Release);
|
||||
}
|
||||
|
||||
/// BOOT 或远程复位也结束当前操控会话,满血后仍需重新显式接管。
|
||||
pub fn reset(&self) {
|
||||
self.resets.fetch_add(1, Ordering::AcqRel);
|
||||
self.set_alive(true);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
reporter: Arc<Reporter>,
|
||||
board_id: u32,
|
||||
uart: UartDriver<'static>,
|
||||
) -> Result<(Receiver<ReceivedCommand>, Arc<BoardStatus>)> {
|
||||
let (tx, rx) = sync_channel(MAX_RECEIVE_PER_POLL);
|
||||
let status = Arc::new(BoardStatus {
|
||||
alive: AtomicBool::new(true),
|
||||
resets: AtomicU32::new(0),
|
||||
});
|
||||
let worker_status = Arc::clone(&status);
|
||||
std::thread::Builder::new()
|
||||
.name("operator-uart".into())
|
||||
.stack_size(8192)
|
||||
.spawn(move || run(reporter, board_id, uart, tx, worker_status))?;
|
||||
Ok((rx, status))
|
||||
}
|
||||
|
||||
fn wifi_online() -> bool {
|
||||
let mut record = esp_idf_svc::sys::wifi_ap_record_t::default();
|
||||
// 查询真实链路;不等待关联,也不分配或输出 SSID。
|
||||
(unsafe { esp_idf_svc::sys::esp_wifi_sta_get_ap_info(&mut record) } == esp_idf_svc::sys::ESP_OK)
|
||||
&& crate::sta_ip().is_some()
|
||||
}
|
||||
|
||||
fn run(
|
||||
reporter: Arc<Reporter>,
|
||||
board_id: u32,
|
||||
uart: UartDriver<'static>,
|
||||
legacy: SyncSender<ReceivedCommand>,
|
||||
status: Arc<BoardStatus>,
|
||||
) {
|
||||
let mut operator = OperatorLink::new(board_id);
|
||||
// 与受击主循环使用同一套来源、会话和序号规则;操控许可不等待 ADC。
|
||||
let mut damage = DamageLink::default();
|
||||
let mut reset_generation = 0;
|
||||
let mut next_output_ms = 0;
|
||||
let mut sequence = 0u32;
|
||||
let mut startup_neutral_sent = false;
|
||||
|
||||
loop {
|
||||
let started_ms = crate::now_ms();
|
||||
let wifi_up = wifi_online();
|
||||
let current_reset = status.resets.load(Ordering::Acquire);
|
||||
if current_reset != reset_generation {
|
||||
operator.stop();
|
||||
reset_generation = current_reset;
|
||||
}
|
||||
if !wifi_up {
|
||||
operator.stop();
|
||||
damage.disconnect();
|
||||
}
|
||||
if operator.current(started_ms).is_some_and(|packet| {
|
||||
!status.alive.load(Ordering::Acquire) || !mode_allowed(packet.mode, &damage, started_ms)
|
||||
}) {
|
||||
// 先检查已有许可过期,再处理本轮续约,迟到许可不能复活已停会话。
|
||||
operator.stop();
|
||||
}
|
||||
|
||||
// 只有这里读取 socket;任何一轮都不因收包或下游队列而无限等待。
|
||||
for _ in 0..MAX_RECEIVE_PER_POLL {
|
||||
let (command, source) = match reporter.receive() {
|
||||
Ok(Some(packet)) => packet,
|
||||
Ok(None) => break,
|
||||
Err(_) => {
|
||||
operator.stop();
|
||||
break;
|
||||
}
|
||||
};
|
||||
if !wifi_up {
|
||||
continue;
|
||||
}
|
||||
let received_ms = crate::now_ms();
|
||||
let received_at = Duration::from_millis(received_ms);
|
||||
if operator.current(received_ms).is_some_and(|packet| {
|
||||
!status.alive.load(Ordering::Acquire)
|
||||
|| !mode_allowed(packet.mode, &damage, received_ms)
|
||||
}) {
|
||||
operator.stop();
|
||||
}
|
||||
match command {
|
||||
ControlCommand::Operator(packet) => {
|
||||
if packet.enabled
|
||||
&& (!status.alive.load(Ordering::Acquire)
|
||||
|| !mode_allowed(packet.mode, &damage, received_ms))
|
||||
{
|
||||
// 首次接管可能先于裁判许可到达;未接管的新会话不提前退休。
|
||||
// 已运行会话仍会在本轮门控检查中关闭,不能靠后续包恢复。
|
||||
continue;
|
||||
}
|
||||
operator.receive(packet, *source.ip(), received_ms);
|
||||
}
|
||||
ControlCommand::Damage(packet) => {
|
||||
if packet.board_id != board_id {
|
||||
continue;
|
||||
}
|
||||
let accepted = damage.accept(packet, source, received_at);
|
||||
if accepted
|
||||
&& operator.current(received_ms).is_some_and(|current| {
|
||||
(current.mode == 0 && !packet.enabled)
|
||||
|| (current.mode == 1 && packet.enabled)
|
||||
})
|
||||
{
|
||||
// 即使同轮紧跟另一份许可,也不能把已停止会话重新打开。
|
||||
operator.stop();
|
||||
}
|
||||
forward(&legacy, ControlCommand::Damage(packet), source, received_at);
|
||||
}
|
||||
ControlCommand::Reset(packet) => {
|
||||
if packet.board_id != board_id {
|
||||
continue;
|
||||
}
|
||||
if damage.accept_reset(packet, source, received_at).is_some() {
|
||||
operator.stop();
|
||||
}
|
||||
forward(&legacy, ControlCommand::Reset(packet), source, received_at);
|
||||
}
|
||||
ControlCommand::Team(packet) => {
|
||||
if packet.board_id == board_id {
|
||||
forward(&legacy, ControlCommand::Team(packet), source, received_at);
|
||||
}
|
||||
}
|
||||
ControlCommand::Ignored => {}
|
||||
}
|
||||
}
|
||||
|
||||
let now_ms = crate::now_ms();
|
||||
let current = operator.current(now_ms);
|
||||
// 许可开启会结束调试会话,不能从调试无缝续接到比赛。
|
||||
// 其余调试阶段限制由客户端完整比赛状态判断;固件不猜测暂停/未开始。
|
||||
let allowed = wifi_up
|
||||
&& status.alive.load(Ordering::Acquire)
|
||||
&& current.is_some_and(|packet| mode_allowed(packet.mode, &damage, now_ms));
|
||||
let control = operator.output(now_ms, allowed);
|
||||
|
||||
if now_ms >= next_output_ms {
|
||||
// 跳过错过的节拍,不追发历史帧。TX 没排空时也不排队。
|
||||
// 保持原节拍,避免每次微小调度迟延累积成输出频率下降。
|
||||
next_output_ms = if next_output_ms == 0 {
|
||||
now_ms.saturating_add(OUTPUT_INTERVAL_MS)
|
||||
} else {
|
||||
next_output_ms.saturating_add(
|
||||
((now_ms - next_output_ms) / OUTPUT_INTERVAL_MS + 1) * OUTPUT_INTERVAL_MS,
|
||||
)
|
||||
};
|
||||
if uart.wait_tx_done(0).is_ok() {
|
||||
sequence = sequence.wrapping_add(1);
|
||||
// 即使首轮已有网络控制,也先给接收器一帧完整的禁能同步帧。
|
||||
let frame = if startup_neutral_sent {
|
||||
UartControlFrame::from_control(sequence, control)
|
||||
} else {
|
||||
UartControlFrame::neutral(sequence)
|
||||
};
|
||||
let bytes = frame.encode();
|
||||
if matches!(uart.write_nb(&bytes), Ok(count) if count == bytes.len()) {
|
||||
startup_neutral_sent = true;
|
||||
} else {
|
||||
// 半帧由接收端 CRC/同步丢弃;停止当前会话,下次只发送禁能帧。
|
||||
operator.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = Duration::from_millis(crate::now_ms().saturating_sub(started_ms));
|
||||
if let Some(remaining) = POLL_INTERVAL.checked_sub(elapsed) {
|
||||
std::thread::sleep(remaining);
|
||||
} else {
|
||||
// 有界收包耗满周期时也让出一个 tick,避免高流量饿死低优先级 ADC 任务。
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mode_allowed(mode: u8, damage: &DamageLink, now_ms: u64) -> bool {
|
||||
let running = damage.enabled(Duration::from_millis(now_ms));
|
||||
match mode {
|
||||
0 => running,
|
||||
1 => !running,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn forward(
|
||||
legacy: &SyncSender<ReceivedCommand>,
|
||||
command: ControlCommand,
|
||||
source: SocketAddrV4,
|
||||
received_at: Duration,
|
||||
) {
|
||||
// 队列满时丢本包;原控制协议均会续发/重试,不能让 ADC 拖住操控失联保护。
|
||||
let _ = legacy.try_send(ReceivedCommand {
|
||||
command,
|
||||
source,
|
||||
received_at,
|
||||
});
|
||||
}
|
||||
@@ -38,6 +38,9 @@ use std::time::Duration;
|
||||
|
||||
pub use protocol::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
|
||||
pub use protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_UNASSIGNED};
|
||||
pub use protocol::OperatorControl;
|
||||
mod operator;
|
||||
pub use operator::{OperatorLink, UartControlFrame, OPERATOR_LEASE_MS, SERIAL_FRAME_LEN};
|
||||
|
||||
pub const CLIENT_LEASE: Duration = Duration::from_secs(2);
|
||||
pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! 操控租约与用户 UART 帧。调用方提供单调毫秒时钟,不依赖板上外设。
|
||||
use std::collections::VecDeque;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use protocol::OperatorControl;
|
||||
|
||||
pub const OPERATOR_LEASE_MS: u64 = 150;
|
||||
pub const SERIAL_FRAME_LEN: usize = 20;
|
||||
const RETIRED_SESSIONS: usize = 8;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Owner {
|
||||
source: Ipv4Addr,
|
||||
packet: OperatorControl,
|
||||
at: u64,
|
||||
}
|
||||
|
||||
/// 只保留最新操作量。停止、失联或规则撤销后,该会话不能靠迟到包恢复。
|
||||
/// 最近 8 个关闭会话用于拒绝常见网络乱序,不构成身份认证或无限期防重放。
|
||||
#[derive(Debug)]
|
||||
pub struct OperatorLink {
|
||||
board_id: u32,
|
||||
owner: Option<Owner>,
|
||||
retired: VecDeque<(Ipv4Addr, u64)>,
|
||||
}
|
||||
|
||||
impl OperatorLink {
|
||||
pub fn new(board_id: u32) -> Self {
|
||||
Self {
|
||||
board_id,
|
||||
owner: None,
|
||||
retired: VecDeque::with_capacity(RETIRED_SESSIONS),
|
||||
}
|
||||
}
|
||||
|
||||
fn retire(&mut self, source: Ipv4Addr, session: u64) {
|
||||
let key = (source, session);
|
||||
if !self.retired.contains(&key) {
|
||||
if self.retired.len() == RETIRED_SESSIONS {
|
||||
self.retired.pop_front();
|
||||
}
|
||||
self.retired.push_back(key);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
if let Some(owner) = self.owner.take() {
|
||||
self.retire(owner.source, owner.packet.session);
|
||||
}
|
||||
}
|
||||
|
||||
fn expire(&mut self, now_ms: u64) {
|
||||
if self
|
||||
.owner
|
||||
.as_ref()
|
||||
.is_some_and(|owner| now_ms.saturating_sub(owner.at) >= OPERATOR_LEASE_MS)
|
||||
{
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive(&mut self, packet: OperatorControl, source: Ipv4Addr, now_ms: u64) -> bool {
|
||||
self.expire(now_ms);
|
||||
if !packet.valid()
|
||||
|| packet.board_id != self.board_id
|
||||
|| self.retired.contains(&(source, packet.session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(owner) = self.owner.as_ref() {
|
||||
if owner.source != source || owner.packet.session != packet.session {
|
||||
return false;
|
||||
}
|
||||
if packet.sequence <= owner.packet.sequence {
|
||||
return false;
|
||||
}
|
||||
// 模式切换需要新的显式开启,不能原地把比赛操控改为调试。
|
||||
if packet.mode != owner.packet.mode {
|
||||
self.stop();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if !packet.enabled {
|
||||
self.stop();
|
||||
self.retire(source, packet.session);
|
||||
return true;
|
||||
}
|
||||
self.owner = Some(Owner {
|
||||
source,
|
||||
packet,
|
||||
at: now_ms,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// 查询当前模式后,调用方仍需通过 `output` 应用 HP、比赛许可等规则。
|
||||
pub fn current(&mut self, now_ms: u64) -> Option<OperatorControl> {
|
||||
self.expire(now_ms);
|
||||
self.owner.as_ref().map(|owner| owner.packet)
|
||||
}
|
||||
|
||||
pub fn output(&mut self, now_ms: u64, allowed: bool) -> Option<OperatorControl> {
|
||||
if !allowed {
|
||||
self.stop();
|
||||
}
|
||||
self.current(now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// 115200 8N1 用户 UART 输出帧。所有多字节字段为小端。
|
||||
/// `A5 5A | version=1 | len=20 | seq:u32 | flags | reserved=0 | 4*i16 | CRC16`
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct UartControlFrame {
|
||||
pub sequence: u32,
|
||||
pub enabled: bool,
|
||||
pub debug: bool,
|
||||
pub channels: [i16; 4],
|
||||
pub fire: bool,
|
||||
}
|
||||
|
||||
impl UartControlFrame {
|
||||
pub fn neutral(sequence: u32) -> Self {
|
||||
Self {
|
||||
sequence,
|
||||
enabled: false,
|
||||
debug: false,
|
||||
channels: [0; 4],
|
||||
fire: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_control(sequence: u32, control: Option<OperatorControl>) -> Self {
|
||||
match control.filter(|control| control.valid() && control.enabled) {
|
||||
Some(control) => Self {
|
||||
sequence,
|
||||
enabled: true,
|
||||
debug: control.mode == 1,
|
||||
channels: control.channels,
|
||||
fire: control.fire,
|
||||
},
|
||||
None => Self::neutral(sequence),
|
||||
}
|
||||
}
|
||||
|
||||
fn valid(&self) -> bool {
|
||||
self.channels
|
||||
.iter()
|
||||
.all(|value| (-1000..=1000).contains(value))
|
||||
&& (self.enabled || (!self.debug && !self.fire && self.channels == [0; 4]))
|
||||
}
|
||||
|
||||
/// 非法内部状态也只能编码为全零禁能帧,不能把越界速度发给下位机。
|
||||
pub fn encode(&self) -> [u8; SERIAL_FRAME_LEN] {
|
||||
let value = if self.valid() {
|
||||
*self
|
||||
} else {
|
||||
Self::neutral(self.sequence)
|
||||
};
|
||||
let mut bytes = [0u8; SERIAL_FRAME_LEN];
|
||||
bytes[..4].copy_from_slice(&[0xa5, 0x5a, 1, SERIAL_FRAME_LEN as u8]);
|
||||
bytes[4..8].copy_from_slice(&value.sequence.to_le_bytes());
|
||||
bytes[8] =
|
||||
u8::from(value.enabled) | (u8::from(value.debug) << 1) | (u8::from(value.fire) << 2);
|
||||
for (index, channel) in value.channels.iter().enumerate() {
|
||||
bytes[10 + index * 2..12 + index * 2].copy_from_slice(&channel.to_le_bytes());
|
||||
}
|
||||
let crc = crc16(&bytes[..18]);
|
||||
bytes[18..].copy_from_slice(&crc.to_le_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() != SERIAL_FRAME_LEN
|
||||
|| bytes[..4] != [0xa5, 0x5a, 1, SERIAL_FRAME_LEN as u8]
|
||||
|| bytes[8] & !7 != 0
|
||||
|| bytes[9] != 0
|
||||
|| crc16(&bytes[..18]) != u16::from_le_bytes([bytes[18], bytes[19]])
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let value = Self {
|
||||
sequence: u32::from_le_bytes(bytes[4..8].try_into().ok()?),
|
||||
enabled: bytes[8] & 1 != 0,
|
||||
debug: bytes[8] & 2 != 0,
|
||||
fire: bytes[8] & 4 != 0,
|
||||
channels: [10, 12, 14, 16].map(|at| i16::from_le_bytes([bytes[at], bytes[at + 1]])),
|
||||
};
|
||||
value.valid().then_some(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// CRC-16/CCITT-FALSE:poly 0x1021、init 0xffff、不反射、xorout 0。
|
||||
fn crc16(bytes: &[u8]) -> u16 {
|
||||
let mut crc = 0xffffu16;
|
||||
for byte in bytes {
|
||||
crc ^= u16::from(*byte) << 8;
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 0x8000 != 0 {
|
||||
(crc << 1) ^ 0x1021
|
||||
} else {
|
||||
crc << 1
|
||||
};
|
||||
}
|
||||
}
|
||||
crc
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const SOURCE: Ipv4Addr = Ipv4Addr::new(10, 0, 0, 1);
|
||||
|
||||
fn packet(session: u64, sequence: u64) -> OperatorControl {
|
||||
OperatorControl {
|
||||
board_id: 17,
|
||||
session,
|
||||
sequence,
|
||||
mode: 0,
|
||||
enabled: true,
|
||||
channels: [1000, -1000, 200, -200],
|
||||
fire: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_input_and_exact_timeout_do_not_revive_closed_session() {
|
||||
let mut link = OperatorLink::new(17);
|
||||
assert!(link.receive(packet(10, 1), SOURCE, 0));
|
||||
assert!(link.receive(packet(10, 3), SOURCE, 20));
|
||||
assert!(!link.receive(packet(10, 2), SOURCE, 25));
|
||||
assert!(!link.receive(packet(10, 3), SOURCE, 30));
|
||||
assert_eq!(link.output(169, true), Some(packet(10, 3)));
|
||||
assert_eq!(link.output(170, true), None);
|
||||
assert!(!link.receive(packet(10, 4), SOURCE, 171));
|
||||
assert!(link.receive(packet(11, 1), SOURCE, 171));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_owner_can_release_and_gate_revocation_requires_new_capture() {
|
||||
let mut link = OperatorLink::new(17);
|
||||
assert!(link.receive(packet(10, 1), SOURCE, 0));
|
||||
let mut stop = packet(10, 2);
|
||||
stop.enabled = false;
|
||||
stop.channels = [0; 4];
|
||||
stop.fire = false;
|
||||
assert!(!link.receive(stop, Ipv4Addr::LOCALHOST, 1));
|
||||
assert!(link.current(2).is_some());
|
||||
assert!(link.receive(stop, SOURCE, 3));
|
||||
assert_eq!(link.current(4), None);
|
||||
assert!(!link.receive(packet(10, 3), SOURCE, 4));
|
||||
assert!(link.receive(packet(11, 1), SOURCE, 4));
|
||||
assert_eq!(link.output(5, false), None);
|
||||
assert!(!link.receive(packet(11, 2), SOURCE, 6));
|
||||
assert!(link.receive(packet(12, 1), SOURCE, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_board_mode_and_bounded_retirement_rules() {
|
||||
let mut link = OperatorLink::new(17);
|
||||
let mut wrong = packet(10, 1);
|
||||
wrong.board_id = 99;
|
||||
assert!(!link.receive(wrong, SOURCE, 0));
|
||||
assert!(link.receive(packet(10, 1), SOURCE, 0));
|
||||
assert!(!link.receive(packet(11, 1), Ipv4Addr::LOCALHOST, 1));
|
||||
assert!(!link.receive(packet(11, 1), SOURCE, 1));
|
||||
let mut mode = packet(10, 2);
|
||||
mode.mode = 1;
|
||||
assert!(!link.receive(mode, SOURCE, 2));
|
||||
assert_eq!(link.current(2), None);
|
||||
assert!(!link.receive(packet(10, 3), SOURCE, 3));
|
||||
for session in 11..100 {
|
||||
assert!(link.receive(packet(session, 1), SOURCE, session));
|
||||
link.stop();
|
||||
}
|
||||
assert_eq!(link.retired.len(), RETIRED_SESSIONS);
|
||||
for session in 92..100 {
|
||||
assert!(!link.receive(packet(session, 9), SOURCE, 100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_first_packet_retires_capture_without_arming_it() {
|
||||
let mut link = OperatorLink::new(17);
|
||||
let mut stop = packet(10, 2);
|
||||
stop.enabled = false;
|
||||
stop.channels = [0; 4];
|
||||
stop.fire = false;
|
||||
assert!(link.receive(stop, SOURCE, 0));
|
||||
assert!(!link.receive(packet(10, 1), SOURCE, 1));
|
||||
assert!(!link.receive(packet(10, 3), SOURCE, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_layout_crc_and_strict_field_validation() {
|
||||
assert_eq!(crc16(b"123456789"), 0x29b1);
|
||||
// 与 C 接收示例共用的黄金帧;CRC 同时由 Python binascii.crc_hqx 核对。
|
||||
let golden = [
|
||||
0xa5, 0x5a, 0x01, 0x14, 0x78, 0x56, 0x34, 0x12, 0x05, 0x00, 0xe8, 0x03, 0x18, 0xfc,
|
||||
0xc8, 0x00, 0x38, 0xff, 0x78, 0x60,
|
||||
];
|
||||
assert_eq!(
|
||||
UartControlFrame::from_control(0x12345678, Some(packet(10, 1))).encode(),
|
||||
golden
|
||||
);
|
||||
for control in [None, Some(packet(10, 1))] {
|
||||
let frame = UartControlFrame::from_control(0x12345678, control);
|
||||
let bytes = frame.encode();
|
||||
assert_eq!(UartControlFrame::decode(&bytes), Some(frame));
|
||||
assert_eq!(&bytes[..8], &[0xa5, 0x5a, 1, 20, 0x78, 0x56, 0x34, 0x12]);
|
||||
for len in 0..bytes.len() {
|
||||
assert!(UartControlFrame::decode(&bytes[..len]).is_none());
|
||||
}
|
||||
for index in 0..bytes.len() {
|
||||
let mut corrupt = bytes;
|
||||
corrupt[index] ^= 1;
|
||||
assert!(UartControlFrame::decode(&corrupt).is_none());
|
||||
}
|
||||
}
|
||||
let mut invalid = UartControlFrame::neutral(1);
|
||||
invalid.fire = true;
|
||||
assert_eq!(
|
||||
UartControlFrame::decode(&invalid.encode()),
|
||||
Some(UartControlFrame::neutral(1))
|
||||
);
|
||||
let mut bad = UartControlFrame::neutral(2).encode();
|
||||
bad[8] = 2; // 禁能时调试位也必须为零。
|
||||
let crc = crc16(&bad[..18]);
|
||||
bad[18..].copy_from_slice(&crc.to_le_bytes());
|
||||
assert!(UartControlFrame::decode(&bad).is_none());
|
||||
bad = UartControlFrame::from_control(3, Some(packet(10, 1))).encode();
|
||||
bad[10..12].copy_from_slice(&1001i16.to_le_bytes());
|
||||
let crc = crc16(&bad[..18]);
|
||||
bad[18..].copy_from_slice(&crc.to_le_bytes());
|
||||
assert!(UartControlFrame::decode(&bad).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# 用户 UART 接收示例
|
||||
|
||||
`rmic_control.c` / `.h` 是不依赖 HAL 的 C99 解析器。串口设置、接线和字段定义见[装甲板文档](../../../docs/hardware/armor.md)。示例仅产生操作状态,不直接驱动电机或发射机构。
|
||||
|
||||
接收任务把任意长度的 UART 数据交给 `rmic_receiver_feed`,控制循环每次调用 `rmic_receiver_poll`,再应用其返回的速度比例与发射状态。两个函数须由同一个任务调用,或由调用方保证互斥。`now_ms` 使用持续递增的 32 位毫秒计时器,支持自然回绕。
|
||||
|
||||
启动或连续 100 ms 没收到有效新帧后,输出禁能、四通道归零、发射关闭。恢复时必须先收到完整禁能帧,再接受后续使能帧;这样 C3 重启后序号可以重新从零开始。若接收器在操作中断电重启,需要选手先退出操控再重新开启,使其观察到禁能帧。帧校验用于发现传输损坏,不能认证发送者。
|
||||
|
||||
从此目录运行主机检查:
|
||||
|
||||
```sh
|
||||
clang -std=c99 -Wall -Wextra -Werror rmic_control.c test_receiver.c -o test_receiver
|
||||
./test_receiver
|
||||
```
|
||||
|
||||
Windows 下输出名可写 `test_receiver.exe`。不应把生成的可执行文件提交到仓库;可用 `-o` 输出到仓库 `target/` 下。主机测试覆盖启动杂字节、分段输入、坏帧重同步、乱序、重复、通道边界、超时及计时器回绕;实际 UART 电平和下位机停机行为仍需接线验证。
|
||||
@@ -0,0 +1,107 @@
|
||||
#include "rmic_control.h"
|
||||
#include <string.h>
|
||||
|
||||
static uint16_t read16(const uint8_t *p) {
|
||||
return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8));
|
||||
}
|
||||
|
||||
static uint32_t read32(const uint8_t *p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
static uint16_t crc16(const uint8_t *bytes, size_t count) {
|
||||
uint16_t crc = UINT16_C(0xffff);
|
||||
size_t i;
|
||||
for (i = 0; i < count; ++i) {
|
||||
unsigned int bit;
|
||||
crc ^= (uint16_t)((uint16_t)bytes[i] << 8);
|
||||
for (bit = 0; bit < 8; ++bit) {
|
||||
crc = (uint16_t)((crc & UINT16_C(0x8000)) ?
|
||||
((uint32_t)crc << 1) ^ UINT32_C(0x1021) : (uint32_t)crc << 1);
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
static void stop(rmic_receiver *receiver) {
|
||||
memset(&receiver->control, 0, sizeof(receiver->control));
|
||||
receiver->synchronized = false;
|
||||
}
|
||||
|
||||
void rmic_receiver_init(rmic_receiver *receiver) {
|
||||
memset(receiver, 0, sizeof(*receiver));
|
||||
}
|
||||
|
||||
rmic_control rmic_receiver_poll(rmic_receiver *receiver, uint32_t now_ms) {
|
||||
if (receiver->synchronized &&
|
||||
(uint32_t)(now_ms - receiver->last_valid_ms) >= RMIC_CONTROL_TIMEOUT_MS) {
|
||||
stop(receiver);
|
||||
}
|
||||
return receiver->control;
|
||||
}
|
||||
|
||||
static bool decode(const uint8_t *bytes, rmic_control *result, uint32_t *sequence) {
|
||||
unsigned int i;
|
||||
uint8_t flags = bytes[8];
|
||||
if (bytes[0] != 0xa5 || bytes[1] != 0x5a || bytes[2] != 1 ||
|
||||
bytes[3] != RMIC_CONTROL_FRAME_SIZE || bytes[9] != 0 || (flags & 0xf8) != 0 ||
|
||||
crc16(bytes, 18) != read16(bytes + 18)) {
|
||||
return false;
|
||||
}
|
||||
memset(result, 0, sizeof(*result));
|
||||
result->enabled = (flags & 1) != 0;
|
||||
result->debug = (flags & 2) != 0;
|
||||
result->fire = (flags & 4) != 0;
|
||||
*sequence = read32(bytes + 4);
|
||||
for (i = 0; i < 4; ++i) {
|
||||
uint16_t raw = read16(bytes + 10 + 2 * i);
|
||||
/* Avoid implementation-defined conversion of values above INT16_MAX. */
|
||||
int32_t value = raw <= INT16_MAX ? (int32_t)raw : (int32_t)raw - 65536;
|
||||
if (value < -1000 || value > 1000 || (!result->enabled && value != 0)) {
|
||||
return false;
|
||||
}
|
||||
result->channel[i] = (int16_t)value;
|
||||
}
|
||||
return result->enabled || (!result->debug && !result->fire);
|
||||
}
|
||||
|
||||
size_t rmic_receiver_feed(rmic_receiver *receiver, const uint8_t *data, size_t length,
|
||||
uint32_t now_ms) {
|
||||
size_t accepted = 0;
|
||||
size_t i;
|
||||
(void)rmic_receiver_poll(receiver, now_ms);
|
||||
for (i = 0; i < length; ++i) {
|
||||
rmic_control next;
|
||||
uint32_t sequence;
|
||||
receiver->buffer[receiver->used++] = data[i];
|
||||
if (receiver->used < RMIC_CONTROL_FRAME_SIZE) {
|
||||
continue;
|
||||
}
|
||||
if (!decode(receiver->buffer, &next, &sequence)) {
|
||||
/* One-byte rescan preserves an embedded prefix after noise or a truncated frame. */
|
||||
memmove(receiver->buffer, receiver->buffer + 1, RMIC_CONTROL_FRAME_SIZE - 1);
|
||||
receiver->used = RMIC_CONTROL_FRAME_SIZE - 1;
|
||||
continue;
|
||||
}
|
||||
receiver->used = 0;
|
||||
if (!receiver->synchronized) {
|
||||
/* Cold boot or timeout: first observe a complete neutral frame.
|
||||
* This also permits the C3 sequence to restart at zero after reboot. */
|
||||
if (next.enabled) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
uint32_t delta = sequence - receiver->sequence;
|
||||
if (delta == 0 || delta >= UINT32_C(0x80000000)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
receiver->synchronized = true;
|
||||
receiver->sequence = sequence;
|
||||
receiver->last_valid_ms = now_ms;
|
||||
receiver->control = next;
|
||||
++accepted;
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef RMIC_CONTROL_H
|
||||
#define RMIC_CONTROL_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define RMIC_CONTROL_FRAME_SIZE 20u
|
||||
#define RMIC_CONTROL_TIMEOUT_MS 100u
|
||||
|
||||
/* Channel order: forward, strafe-right, yaw-right, pitch-up. Speed: -1000..1000. */
|
||||
typedef struct {
|
||||
int16_t channel[4];
|
||||
bool enabled;
|
||||
bool debug;
|
||||
bool fire;
|
||||
} rmic_control;
|
||||
|
||||
typedef struct {
|
||||
uint8_t buffer[RMIC_CONTROL_FRAME_SIZE];
|
||||
size_t used;
|
||||
bool synchronized;
|
||||
uint32_t sequence;
|
||||
uint32_t last_valid_ms;
|
||||
rmic_control control;
|
||||
} rmic_receiver;
|
||||
|
||||
void rmic_receiver_init(rmic_receiver *receiver);
|
||||
|
||||
/* Call from one task/context only; feed arbitrary UART chunks, never assume frame alignment.
|
||||
* Returns number of accepted fresh frames. Noise/bad/duplicate frames do not renew timeout.
|
||||
* now_ms is a monotonic uint32 clock (wraparound is supported). */
|
||||
size_t rmic_receiver_feed(rmic_receiver *receiver, const uint8_t *data, size_t length,
|
||||
uint32_t now_ms);
|
||||
|
||||
/* Call at least once per control-loop iteration, including when UART is silent.
|
||||
* This function stops all channels/fire after 100ms and requires a neutral frame to resync.
|
||||
* Use only this returned state when applying motor/gimbal/launcher setpoints. */
|
||||
rmic_control rmic_receiver_poll(rmic_receiver *receiver, uint32_t now_ms);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,145 @@
|
||||
#include "rmic_control.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Deliberately independent fixture encoder; compare the golden frame with Rust tests. */
|
||||
static void finish_crc(uint8_t bytes[20]) {
|
||||
unsigned int i, bit;
|
||||
uint32_t crc = 0xffff;
|
||||
for (i = 0; i < 18; ++i) {
|
||||
crc ^= (uint32_t)bytes[i] << 8;
|
||||
for (bit = 0; bit < 8; ++bit) {
|
||||
crc = ((crc << 1) ^ ((crc & 0x8000) ? 0x1021 : 0)) & 0xffff;
|
||||
}
|
||||
}
|
||||
bytes[18] = (uint8_t)crc;
|
||||
bytes[19] = (uint8_t)(crc >> 8);
|
||||
}
|
||||
|
||||
static void frame(uint8_t bytes[20], uint32_t sequence, bool enabled) {
|
||||
unsigned int i;
|
||||
const uint8_t channels[8] = {0xe8, 0x03, 0x18, 0xfc, 0xc8, 0, 0x38, 0xff};
|
||||
memset(bytes, 0, 20);
|
||||
bytes[0] = 0xa5; bytes[1] = 0x5a; bytes[2] = 1; bytes[3] = 20;
|
||||
for (i = 0; i < 4; ++i) bytes[4 + i] = (uint8_t)(sequence >> (8 * i));
|
||||
if (enabled) {
|
||||
bytes[8] = 5;
|
||||
memcpy(bytes + 10, channels, 8);
|
||||
}
|
||||
finish_crc(bytes);
|
||||
}
|
||||
|
||||
static void expect_stopped(rmic_receiver *receiver, uint32_t now) {
|
||||
unsigned int i;
|
||||
rmic_control state = rmic_receiver_poll(receiver, now);
|
||||
assert(!state.enabled && !state.debug && !state.fire);
|
||||
for (i = 0; i < 4; ++i) assert(state.channel[i] == 0);
|
||||
}
|
||||
|
||||
static void startup_noise_chunks_and_timeout(void) {
|
||||
rmic_receiver receiver;
|
||||
uint8_t bytes[20];
|
||||
const uint8_t noise[] = "ESP-ROM:esp32c3 startup\n\xa5\x5a\x00";
|
||||
unsigned int i;
|
||||
rmic_receiver_init(&receiver);
|
||||
frame(bytes, 1, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, sizeof(bytes), 0) == 0);
|
||||
expect_stopped(&receiver, 0);
|
||||
assert(rmic_receiver_feed(&receiver, noise, sizeof(noise), 1) == 0);
|
||||
frame(bytes, 2, false);
|
||||
for (i = 0; i < 20; ++i) {
|
||||
assert(rmic_receiver_feed(&receiver, bytes + i, 1, 2) == (i == 19 ? 1u : 0u));
|
||||
}
|
||||
frame(bytes, 3, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 7, 10) == 0);
|
||||
assert(rmic_receiver_feed(&receiver, bytes + 7, 13, 10) == 1);
|
||||
assert(receiver.control.enabled && receiver.control.fire);
|
||||
assert(receiver.control.channel[0] == 1000 && receiver.control.channel[1] == -1000);
|
||||
assert(receiver.control.channel[2] == 200 && receiver.control.channel[3] == -200);
|
||||
assert(rmic_receiver_poll(&receiver, 109).enabled);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 109) == 0); /* Duplicate cannot renew. */
|
||||
expect_stopped(&receiver, 110);
|
||||
frame(bytes, 4, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 111) == 0);
|
||||
expect_stopped(&receiver, 111);
|
||||
frame(bytes, 0, false); /* Restarted C3. */
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 112) == 1);
|
||||
frame(bytes, 1, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 113) == 1);
|
||||
assert(receiver.control.enabled);
|
||||
}
|
||||
|
||||
static void corrupt_truncated_and_invalid_frames(void) {
|
||||
rmic_receiver receiver;
|
||||
uint8_t bytes[20], good[20];
|
||||
size_t i;
|
||||
rmic_receiver_init(&receiver);
|
||||
frame(bytes, 1, false);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 0) == 1);
|
||||
frame(good, 2, true);
|
||||
for (i = 0; i < 20; ++i) {
|
||||
memcpy(bytes, good, 20);
|
||||
bytes[i] ^= 1;
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 1) == 0);
|
||||
}
|
||||
memcpy(bytes, good, 20);
|
||||
bytes[8] = 0x85; finish_crc(bytes);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 2) == 0);
|
||||
memcpy(bytes, good, 20);
|
||||
bytes[9] = 1; finish_crc(bytes);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 3) == 0);
|
||||
memcpy(bytes, good, 20);
|
||||
bytes[10] = 0xe9; finish_crc(bytes); /* 1001 */
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 4) == 0);
|
||||
memcpy(bytes, good, 20);
|
||||
bytes[8] = 0; finish_crc(bytes); /* Disabled, nonzero channels. */
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 5) == 0);
|
||||
assert(rmic_receiver_feed(&receiver, good, 7, 6) == 0); /* Half frame followed by whole. */
|
||||
assert(rmic_receiver_feed(&receiver, good, 20, 7) == 1);
|
||||
assert(receiver.control.enabled);
|
||||
frame(bytes, 1, false); /* Old stop must not advance sequence or change output. */
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 8) == 0);
|
||||
assert(receiver.control.enabled);
|
||||
expect_stopped(&receiver, 107);
|
||||
}
|
||||
|
||||
static void wrapping_sequence_and_clock(void) {
|
||||
rmic_receiver receiver;
|
||||
uint8_t bytes[20];
|
||||
rmic_receiver_init(&receiver);
|
||||
frame(bytes, UINT32_MAX - 1, false);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, UINT32_MAX - 30) == 1);
|
||||
frame(bytes, UINT32_MAX, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, UINT32_MAX - 20) == 1);
|
||||
frame(bytes, 0, true);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, UINT32_MAX - 10) == 1);
|
||||
assert(rmic_receiver_poll(&receiver, 88).enabled);
|
||||
expect_stopped(&receiver, 89);
|
||||
}
|
||||
|
||||
static void rust_golden_frame(void) {
|
||||
const uint8_t golden[20] = {
|
||||
0xa5, 0x5a, 0x01, 0x14, 0x78, 0x56, 0x34, 0x12, 0x05, 0x00,
|
||||
0xe8, 0x03, 0x18, 0xfc, 0xc8, 0x00, 0x38, 0xff, 0x78, 0x60
|
||||
};
|
||||
uint8_t bytes[20];
|
||||
rmic_receiver receiver;
|
||||
rmic_receiver_init(&receiver);
|
||||
frame(bytes, UINT32_C(0x12345677), false);
|
||||
assert(rmic_receiver_feed(&receiver, bytes, 20, 0) == 1);
|
||||
assert(rmic_receiver_feed(&receiver, golden, 20, 1) == 1);
|
||||
assert(receiver.sequence == UINT32_C(0x12345678));
|
||||
assert(receiver.control.enabled && receiver.control.fire && !receiver.control.debug);
|
||||
assert(receiver.control.channel[0] == 1000 && receiver.control.channel[1] == -1000);
|
||||
assert(receiver.control.channel[2] == 200 && receiver.control.channel[3] == -200);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
startup_noise_chunks_and_timeout();
|
||||
corrupt_truncated_and_invalid_frames();
|
||||
wrapping_sequence_and_clock();
|
||||
rust_golden_frame();
|
||||
puts("RMIC UART receiver: all tests passed");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user