feat(control): 添加选手 FPS 键鼠操作与 C3 用户 UART 输出
This commit is contained in:
43 files changed
+2389
-77
No files matched your search
@@ -73,9 +73,10 @@ flowchart LR
|
|||||||
| 模块 | 已有功能 | 使用条件与边界 |
|
| 模块 | 已有功能 | 使用条件与边界 |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| 图传固件 | VGA 彩色 JPEG、UDP 分片、多端订阅、Wi-Fi 重连、过期帧放弃 | 当前记录约 30 fps;不同网络、裁判系统与画质下需复测[^performance] |
|
| 图传固件 | VGA 彩色 JPEG、UDP 分片、多端订阅、Wi-Fi 重连、过期帧放弃 | 当前记录约 30 fps;不同网络、裁判系统与画质下需复测[^performance] |
|
||||||
| 用户端 | 全画面 HUD、双方血量、图传与装甲板状态、接收帧率、ESC 设置菜单 | 先绑定图传板与装甲板;改绑、切换模式和退出受密码限制 |
|
| 用户端 | 全画面 HUD、双方血量、图传与装甲板状态、键鼠操作与赛前调试、ESC 设置菜单 | 先绑定图传板与装甲板;改绑、切换模式和退出受密码限制 |
|
||||||
| 裁判端 | 双路画面、队名编辑、装甲板发现、槽位分配、截图、录制与回放 | 录制需要 ffmpeg;图传槽位可手动指定 |
|
| 裁判端 | 双路画面、队名编辑、装甲板发现、槽位分配、截图、录制与回放 | 录制需要 ffmpeg;图传槽位可手动指定 |
|
||||||
| 装甲板 | 四路受击检测与灯带、整车血量、UDP 上报 | 初始 100 血,每次受击扣 3 点;通用固件,队伍由客户端选择,断网黄闪、等待客户端绿闪 |
|
| 装甲板 | 四路受击检测与灯带、整车血量、UDP 上报 | 初始 100 血,每次受击扣 3 点;通用固件,队伍由客户端选择,断网黄闪、等待客户端绿闪 |
|
||||||
|
| 用户 UART | WASD 平移、鼠标云台速度、左键发射,C3 TX21 输出 | [115200 8N1、四轴协议与接收示例](docs/protocol/operator-control.md);需更新 C3 并接入下位机,实机响应待验证 |
|
||||||
| 固件维护 | 图传板 USB 更新、装甲板本机编译与安装、设备/队伍核对、备份和写后回读 | S3 App 写入与回读已有实机记录;S3 完整切换、C3 客户端安装与恢复尚未实机验证 |
|
| 固件维护 | 图传板 USB 更新、装甲板本机编译与安装、设备/队伍核对、备份和写后回读 | S3 App 写入与回读已有实机记录;S3 完整切换、C3 客户端安装与恢复尚未实机验证 |
|
||||||
|
|
||||||
发送端在限定时间内提交当前帧,超时后转向新帧;本地视频通道与 WebView 会放弃滞留超过 100 ms 的旧帧。这个期限只约束本机积压,**不代表相机到屏幕的端到端延迟**。
|
发送端在限定时间内提交当前帧,超时后转向新帧;本地视频通道与 WebView 会放弃滞留超过 100 ms 的旧帧。这个期限只约束本机积压,**不代表相机到屏幕的端到端延迟**。
|
||||||
|
|||||||
@@ -3,10 +3,9 @@
|
|||||||
# CONFIG_IDF_TARGET 必须显式写出来:本机装的是通用 ESP-IDF,默认目标是 ESP32,
|
# CONFIG_IDF_TARGET 必须显式写出来:本机装的是通用 ESP-IDF,默认目标是 ESP32,
|
||||||
# 不写这一行会按 ESP32 去配 ADC/RMT 通道,编译期就报"没有这个外设"。
|
# 不写这一行会按 ESP32 去配 ADC/RMT 通道,编译期就报"没有这个外设"。
|
||||||
#
|
#
|
||||||
# 串口调试走 UART0(RXD = GPIO20 / TXD = GPIO21,115200 8N1)——这是 C3 的 ROM
|
# RXD = GPIO20 / TXD = GPIO21 专用于用户操控协议(115200 8N1)。
|
||||||
# 默认控制台引脚,和参考固件里给 DBUS 用的那两个脚是同一对。想改成 USB
|
# 应用与二级引导日志走原生 USB;ROM 启动阶段仍可能从 GPIO21 输出日志,
|
||||||
# Serial/JTAG 输出,把 CONFIG_ESP_CONSOLE_UART_DEFAULT 换成
|
# 外部控制器必须按帧头、长度和 CRC 接收,不得将任意启动字节解释为操控。
|
||||||
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG 即可。
|
|
||||||
CONFIG_IDF_TARGET="esp32c3"
|
CONFIG_IDF_TARGET="esp32c3"
|
||||||
|
|
||||||
# 4 MB flash;应用分区放到 2 MB(见 partitions.csv),默认的 1 MB 单 app 槽对
|
# 4 MB flash;应用分区放到 2 MB(见 partitions.csv),默认的 1 MB 单 app 槽对
|
||||||
@@ -14,15 +13,14 @@ CONFIG_IDF_TARGET="esp32c3"
|
|||||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
|
|
||||||
# 调试口 = UART0(GPIO20 RX / GPIO21 TX)。
|
# USB Serial/JTAG 是唯一软件控制台;UART1 经 GPIO Matrix 使用用户 RXD/TXD。
|
||||||
#
|
# CONFIG_ESP_CONSOLE_UART_DEFAULT is not set
|
||||||
# 同时打开 USB Serial/JTAG 作为**次**控制台:日志会同时从板上那个原生 USB 口出来。
|
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||||
# 这样现场两种接法都能看到日志 —— 接了 USB-TTL 到 RXD/TXD 的看 UART0,直接插板上
|
# CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG is not set
|
||||||
# USB 口的看 USB。主控制台仍是 UART0,所以"RXD/TXD 就是调试口"这条成立。
|
CONFIG_ESP_CONSOLE_SECONDARY_NONE=y
|
||||||
#
|
|
||||||
# 只用原生 USB 口烧录(不接 USB-TTL)时,这一条是能看见日志的唯一办法。
|
# 1 ms 调度刻度,支持操控任务 5 ms 轮询及 20 ms UART 输出。
|
||||||
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
CONFIG_FREERTOS_HZ=1000
|
||||||
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
|
|
||||||
|
|
||||||
# Rust 的 main 与规则层在同一个任务栈上跑,另外 log 会用到一些栈;默认 3.5 KB
|
# Rust 的 main 与规则层在同一个任务栈上跑,另外 log 会用到一些栈;默认 3.5 KB
|
||||||
# 在带 WiFi 的固件里容易爆栈。
|
# 在带 WiFi 的固件里容易爆栈。
|
||||||
|
|||||||
@@ -28,17 +28,20 @@
|
|||||||
//! armor/scripts/flash.sh # 编译 + espflash + 串口日志
|
//! armor/scripts/flash.sh # 编译 + espflash + 串口日志
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! 串口调试走 UART0:RXD = GPIO20 / TXD = GPIO21,115200 8N1(日志从 TX 出来,
|
//! 用户 UART:RXD = GPIO20 / TXD = GPIO21,115200 8N1,输出带校验的操控帧。
|
||||||
//! RX 目前空闲,留给以后加命令通道)。USB Serial/JTAG 配成了次控制台,所以插原生
|
//! 软件日志只走原生 USB Serial/JTAG;UART 接收端须忽略 ROM 启动杂字节。
|
||||||
//! USB 口也能看到同一份日志。完整接线表、协议与踩坑见 `armor/README.md`。
|
//! 完整接线表、协议与踩坑见 `armor/README.md`。
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration, PmfConfiguration};
|
use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration, PmfConfiguration};
|
||||||
use esp_idf_svc::eventloop::EspSystemEventLoop;
|
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::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::nvs::EspDefaultNvsPartition;
|
||||||
use esp_idf_svc::wifi::EspWifi;
|
use esp_idf_svc::wifi::EspWifi;
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
@@ -50,6 +53,7 @@ use armor_protocol::{
|
|||||||
mod esp;
|
mod esp;
|
||||||
mod leds;
|
mod leds;
|
||||||
mod net;
|
mod net;
|
||||||
|
mod operator_uart;
|
||||||
mod piezo;
|
mod piezo;
|
||||||
mod settings;
|
mod settings;
|
||||||
|
|
||||||
@@ -71,7 +75,7 @@ const THRESHOLD_ENV: &str = match option_env!("ARMOR_THRESHOLD") {
|
|||||||
/// "装甲板未接入"。
|
/// "装甲板未接入"。
|
||||||
const REPORT_HEARTBEAT_MS: u64 = 200;
|
const REPORT_HEARTBEAT_MS: u64 = 200;
|
||||||
|
|
||||||
/// 状态行的打印周期(UART 调试口)。
|
/// 状态行的打印周期(原生 USB 调试口)。
|
||||||
const STATUS_INTERVAL_MS: u64 = 1000;
|
const STATUS_INTERVAL_MS: u64 = 1000;
|
||||||
|
|
||||||
/// WiFi 断线检查周期。
|
/// WiFi 断线检查周期。
|
||||||
@@ -117,7 +121,7 @@ fn main() -> Result<()> {
|
|||||||
|
|
||||||
info!("pins: ws2812 front=IO10 rear=IO5 left=IO6 right=IO7");
|
info!("pins: ws2812 front=IO10 rear=IO5 left=IO6 right=IO7");
|
||||||
info!("pins: piezo front=GPIO0 rear=GPIO4 left=GPIO3 right=GPIO1");
|
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!(
|
info!(
|
||||||
"armor board: team={team} ({}), {} hp, -{} per hit, {} ms dark on the hit strip",
|
"armor board: team={team} ({}), {} hp, -{} per hit, {} ms dark on the hit strip",
|
||||||
"client-selected",
|
"client-selected",
|
||||||
@@ -140,8 +144,19 @@ fn main() -> Result<()> {
|
|||||||
warn!("Wi-Fi connection attempt failed: {err:#}");
|
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 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 hits: Vec<(Plate, u16)> = Vec::with_capacity(16);
|
||||||
let mut reports = ReportSchedule::new(Duration::from_millis(REPORT_HEARTBEAT_MS));
|
let mut reports = ReportSchedule::new(Duration::from_millis(REPORT_HEARTBEAT_MS));
|
||||||
@@ -167,11 +182,19 @@ fn main() -> Result<()> {
|
|||||||
client.disconnect();
|
client.disconnect();
|
||||||
damage.disconnect();
|
damage.disconnect();
|
||||||
} else {
|
} else {
|
||||||
for _ in 0..8 {
|
for _ in 0..32 {
|
||||||
match reporter.receive() {
|
let Ok(message) = commands.try_recv() else {
|
||||||
Ok(Some((net::ControlCommand::Team(command), from))) => {
|
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
|
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
|
||||||
{
|
{
|
||||||
team = command.team;
|
team = command.team;
|
||||||
@@ -183,17 +206,18 @@ fn main() -> Result<()> {
|
|||||||
force_report = true;
|
force_report = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Some((net::ControlCommand::Damage(command), from))) => {
|
net::ControlCommand::Damage(command) => {
|
||||||
if command.board_id == sender_id {
|
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||||
damage.accept(command, from, now);
|
damage.accept(command, from, received_at);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Some((net::ControlCommand::Reset(mut command), from))) => {
|
net::ControlCommand::Reset(mut command) => {
|
||||||
if command.board_id == sender_id {
|
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||||
if let Some(apply) = damage.accept_reset(command, from, now) {
|
if let Some(apply) = damage.accept_reset(command, from, processed_at) {
|
||||||
if apply {
|
if apply {
|
||||||
armor.set_damage_enabled(false);
|
armor.set_damage_enabled(false);
|
||||||
armor.reset();
|
armor.reset();
|
||||||
|
operator_status.reset();
|
||||||
warn!(
|
warn!(
|
||||||
"referee reset: hp={} reset_id={}",
|
"referee reset: hp={} reset_id={}",
|
||||||
armor.hp(),
|
armor.hp(),
|
||||||
@@ -210,11 +234,7 @@ fn main() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(None) => break,
|
net::ControlCommand::Operator(_) | net::ControlCommand::Ignored => {}
|
||||||
Err(err) => {
|
|
||||||
warn!("client control receive failed: {err:#}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,6 +253,7 @@ fn main() -> Result<()> {
|
|||||||
|
|
||||||
for (plate, raw) in hits.iter().copied() {
|
for (plate, raw) in hits.iter().copied() {
|
||||||
if let Some(event) = armor.on_sample(plate, raw, now) {
|
if let Some(event) = armor.on_sample(plate, raw, now) {
|
||||||
|
operator_status.set_alive(event.hp > 0);
|
||||||
info!(
|
info!(
|
||||||
"hit plate={} raw={} hp={} (hits={}, damage_enabled={})",
|
"hit plate={} raw={} hp={} (hits={}, damage_enabled={})",
|
||||||
event.plate.name(),
|
event.plate.name(),
|
||||||
@@ -264,6 +285,7 @@ fn main() -> Result<()> {
|
|||||||
match button_fsm.tick(button.is_low(), now) {
|
match button_fsm.tick(button.is_low(), now) {
|
||||||
ButtonEvent::LongPress => {
|
ButtonEvent::LongPress => {
|
||||||
armor.reset();
|
armor.reset();
|
||||||
|
operator_status.reset();
|
||||||
warn!("BOOT long press: hp reset to {} (new round)", armor.hp());
|
warn!("BOOT long press: hp reset to {} (new round)", armor.hp());
|
||||||
force_report = true;
|
force_report = true;
|
||||||
}
|
}
|
||||||
@@ -351,7 +373,7 @@ fn status_with_link(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 一行状态,给 UART 调试口用。
|
/// 一行状态,给原生 USB 调试口用。
|
||||||
///
|
///
|
||||||
/// `peak` 是这一秒里每路 ADC 的峰值。它比"有没有受击"更有用:现场要判断阈值该调到
|
/// `peak` 是这一秒里每路 ADC 的峰值。它比"有没有受击"更有用:现场要判断阈值该调到
|
||||||
/// 多少,靠的就是"没敲时的底噪"和"敲击时的幅度"这两个数字。
|
/// 多少,靠的就是"没敲时的底噪"和"敲击时的幅度"这两个数字。
|
||||||
|
|||||||
@@ -21,12 +21,17 @@ use anyhow::{anyhow, Result};
|
|||||||
use esp_idf_svc::sys as ffi;
|
use esp_idf_svc::sys as ffi;
|
||||||
use log::{info, warn};
|
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 {
|
pub enum ControlCommand {
|
||||||
Team(ArmorControl),
|
Team(ArmorControl),
|
||||||
Damage(ArmorDamageControl),
|
Damage(ArmorDamageControl),
|
||||||
Reset(ArmorReset),
|
Reset(ArmorReset),
|
||||||
|
Operator(OperatorControl),
|
||||||
|
/// A consumed datagram which is not a supported control message.
|
||||||
|
Ignored,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
||||||
@@ -72,7 +77,7 @@ pub struct Reporter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Reporter {
|
impl Reporter {
|
||||||
/// 每轮最多由调用方读取 8 包,避免无关流量占住受击循环。
|
/// 只由操控线程接收,每轮有界读取;未知包也计入本轮额度。
|
||||||
pub fn receive(&self) -> Result<Option<(ControlCommand, SocketAddrV4)>> {
|
pub fn receive(&self) -> Result<Option<(ControlCommand, SocketAddrV4)>> {
|
||||||
let mut bytes = [0u8; 256];
|
let mut bytes = [0u8; 256];
|
||||||
let mut addr: ffi::sockaddr_in = unsafe { core::mem::zeroed() };
|
let mut addr: ffi::sockaddr_in = unsafe { core::mem::zeroed() };
|
||||||
@@ -101,8 +106,10 @@ impl Reporter {
|
|||||||
ControlCommand::Damage(control)
|
ControlCommand::Damage(control)
|
||||||
} else if let Some(control) = ArmorReset::decode(bytes) {
|
} else if let Some(control) = ArmorReset::decode(bytes) {
|
||||||
ControlCommand::Reset(control)
|
ControlCommand::Reset(control)
|
||||||
|
} else if let Some(control) = OperatorControl::decode(bytes) {
|
||||||
|
ControlCommand::Operator(control)
|
||||||
} else {
|
} else {
|
||||||
return Ok(None);
|
ControlCommand::Ignored
|
||||||
};
|
};
|
||||||
let ip = std::net::Ipv4Addr::from(addr.sin_addr.s_addr.to_le_bytes());
|
let ip = std::net::Ipv4Addr::from(addr.sin_addr.s_addr.to_le_bytes());
|
||||||
Ok(Some((
|
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::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
|
||||||
pub use protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_UNASSIGNED};
|
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 CLIENT_LEASE: Duration = Duration::from_secs(2);
|
||||||
pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
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;
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ pub mod armor;
|
|||||||
pub mod armor_reset;
|
pub mod armor_reset;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod match_clock;
|
pub mod match_clock;
|
||||||
|
pub mod operator;
|
||||||
pub mod password;
|
pub mod password;
|
||||||
pub mod receiver;
|
pub mod receiver;
|
||||||
pub mod slots;
|
pub mod slots;
|
||||||
|
|||||||
@@ -0,0 +1,383 @@
|
|||||||
|
//! 选手操控会话。输入只保留最新值,失焦、失联或比赛条件变化后必须显式重新开启。
|
||||||
|
use crate::config::Role;
|
||||||
|
use protocol::OperatorControl;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const INPUT_LEASE_MS: u64 = 150;
|
||||||
|
const STOP_PACKETS: u8 = 5;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum OperatorMode {
|
||||||
|
Match,
|
||||||
|
Debug,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct OperatorInput {
|
||||||
|
pub capture_id: u32,
|
||||||
|
pub sequence: u32,
|
||||||
|
pub active: bool,
|
||||||
|
pub forward: i16,
|
||||||
|
pub strafe: i16,
|
||||||
|
pub yaw: i16,
|
||||||
|
pub pitch: i16,
|
||||||
|
pub fire: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OperatorContext {
|
||||||
|
pub role: Role,
|
||||||
|
pub role_chosen: bool,
|
||||||
|
pub board_id: Option<u32>,
|
||||||
|
pub board_ready: bool,
|
||||||
|
pub hp: Option<u16>,
|
||||||
|
pub phase: &'static str,
|
||||||
|
pub connected: bool,
|
||||||
|
pub has_source: bool,
|
||||||
|
pub focused: bool,
|
||||||
|
pub demo: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperatorContext {
|
||||||
|
pub fn check(&self, mode: OperatorMode) -> Result<u32, &'static str> {
|
||||||
|
if self.demo {
|
||||||
|
return Err("演示模式不发送真实操控信号");
|
||||||
|
}
|
||||||
|
if self.role != Role::Team || !self.role_chosen {
|
||||||
|
return Err("请先选择选手端身份");
|
||||||
|
}
|
||||||
|
if !self.focused {
|
||||||
|
return Err("窗口失焦,操作已停止");
|
||||||
|
}
|
||||||
|
let board = self
|
||||||
|
.board_id
|
||||||
|
.filter(|id| *id != 0)
|
||||||
|
.ok_or("请先绑定自己的装甲板");
|
||||||
|
let board = board?;
|
||||||
|
if !self.board_ready || self.hp.is_none() {
|
||||||
|
return Err("绑定的装甲板离线或尚未确认队伍");
|
||||||
|
}
|
||||||
|
if self.hp == Some(0) {
|
||||||
|
return Err("装甲板血量为零,请先重置本局");
|
||||||
|
}
|
||||||
|
match mode {
|
||||||
|
OperatorMode::Match if self.phase != "running" || !self.connected => {
|
||||||
|
Err("比赛未进行或裁判已断连,操作已停止")
|
||||||
|
}
|
||||||
|
OperatorMode::Debug if !matches!(self.phase, "idle" | "preparation" | "ready") => {
|
||||||
|
Err("调试仅在未开赛时可用,操作已停止")
|
||||||
|
}
|
||||||
|
OperatorMode::Debug if self.has_source && !self.connected => {
|
||||||
|
Err("裁判已断连,请恢复同步后再调试")
|
||||||
|
}
|
||||||
|
_ => Ok(board),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OperatorView {
|
||||||
|
pub active: bool,
|
||||||
|
pub capture_id: Option<u32>,
|
||||||
|
pub mode: Option<OperatorMode>,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Capture {
|
||||||
|
id: u32,
|
||||||
|
mode: OperatorMode,
|
||||||
|
packet: OperatorControl,
|
||||||
|
input_sequence: u32,
|
||||||
|
last_input: u64,
|
||||||
|
stops_left: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OperatorState {
|
||||||
|
next_id: u32,
|
||||||
|
next_session: u64,
|
||||||
|
capture: Option<Capture>,
|
||||||
|
reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperatorState {
|
||||||
|
pub fn new(session_seed: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
next_id: 0,
|
||||||
|
next_session: session_seed.max(1),
|
||||||
|
capture: None,
|
||||||
|
reason: "尚未开启操作".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(
|
||||||
|
&mut self,
|
||||||
|
mode: OperatorMode,
|
||||||
|
context: &OperatorContext,
|
||||||
|
now: u64,
|
||||||
|
) -> Result<u32, String> {
|
||||||
|
let board_id = context.check(mode).map_err(str::to_owned)?;
|
||||||
|
if self.capture.as_ref().is_some_and(|c| c.packet.enabled) {
|
||||||
|
return Err("操作已开启,请先退出当前操作".into());
|
||||||
|
}
|
||||||
|
if self.capture.as_ref().is_some_and(|c| c.stops_left > 0) {
|
||||||
|
return Err("正在停止上一操作会话,请稍后重新点击".into());
|
||||||
|
}
|
||||||
|
self.next_id = self.next_id.wrapping_add(1).max(1);
|
||||||
|
self.next_session = self.next_session.wrapping_add(1).max(1);
|
||||||
|
self.capture = Some(Capture {
|
||||||
|
id: self.next_id,
|
||||||
|
mode,
|
||||||
|
packet: OperatorControl {
|
||||||
|
board_id,
|
||||||
|
session: self.next_session,
|
||||||
|
sequence: 0,
|
||||||
|
mode: if mode == OperatorMode::Debug { 1 } else { 0 },
|
||||||
|
enabled: true,
|
||||||
|
channels: [0; 4],
|
||||||
|
fire: false,
|
||||||
|
},
|
||||||
|
input_sequence: 0,
|
||||||
|
last_input: now,
|
||||||
|
stops_left: 0,
|
||||||
|
});
|
||||||
|
self.reason.clear();
|
||||||
|
Ok(self.next_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self, reason: &str) {
|
||||||
|
if let Some(c) = &mut self.capture {
|
||||||
|
if c.packet.enabled {
|
||||||
|
c.stops_left = STOP_PACKETS;
|
||||||
|
}
|
||||||
|
c.packet.enabled = false;
|
||||||
|
c.packet.channels = [0; 4];
|
||||||
|
c.packet.fire = false;
|
||||||
|
}
|
||||||
|
self.reason = reason.into();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(&mut self, context: &OperatorContext, now: u64) {
|
||||||
|
let Some(c) = &self.capture else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if !c.packet.enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let reason = if now.saturating_sub(c.last_input) >= INPUT_LEASE_MS {
|
||||||
|
Some("操作输入超时,请重新点击开启")
|
||||||
|
} else {
|
||||||
|
match context.check(c.mode) {
|
||||||
|
Ok(board) if board != c.packet.board_id => Some("装甲板绑定已改变,请重新开启操作"),
|
||||||
|
Ok(_) => None,
|
||||||
|
Err(reason) => Some(reason),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(reason) = reason {
|
||||||
|
self.stop(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input(
|
||||||
|
&mut self,
|
||||||
|
input: OperatorInput,
|
||||||
|
context: &OperatorContext,
|
||||||
|
now: u64,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
// 旧捕获的迟到释放/输入不能终止或续约新捕获。
|
||||||
|
if self.capture.as_ref().map(|c| c.id) != Some(input.capture_id) {
|
||||||
|
return Err("操作会话已更换,请重新开启".into());
|
||||||
|
}
|
||||||
|
if !input.active {
|
||||||
|
self.stop("操作已退出");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
self.check(context, now);
|
||||||
|
let c = self.capture.as_mut().unwrap();
|
||||||
|
if !c.packet.enabled {
|
||||||
|
return Err(self.reason.clone());
|
||||||
|
}
|
||||||
|
if input.sequence == 0 || input.sequence <= c.input_sequence {
|
||||||
|
return Err("已忽略过期的操作输入".into());
|
||||||
|
}
|
||||||
|
let mut channels = [input.forward, input.strafe, input.yaw, input.pitch];
|
||||||
|
if channels.iter().any(|v| !(-1000..=1000).contains(v)) {
|
||||||
|
self.stop("操作通道超出范围,已停止");
|
||||||
|
return Err(self.reason.clone());
|
||||||
|
}
|
||||||
|
// 即使绕过前端,斜向平移也不能超过单位速度圆。
|
||||||
|
let length = ((channels[0] as f64).powi(2) + (channels[1] as f64).powi(2)).sqrt();
|
||||||
|
if length > 1000.0 {
|
||||||
|
channels[0] = (channels[0] as f64 * 1000.0 / length).round() as i16;
|
||||||
|
channels[1] = (channels[1] as f64 * 1000.0 / length).round() as i16;
|
||||||
|
}
|
||||||
|
c.input_sequence = input.sequence;
|
||||||
|
c.last_input = now;
|
||||||
|
c.packet.channels = channels;
|
||||||
|
c.packet.fire = input.fire;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 由独立 20 ms 任务调用;不重放历史输入,不在定时器停顿后补发。
|
||||||
|
pub fn packet(&mut self, context: &OperatorContext, now: u64) -> Option<OperatorControl> {
|
||||||
|
self.check(context, now);
|
||||||
|
let c = self.capture.as_mut()?;
|
||||||
|
if !c.packet.enabled {
|
||||||
|
if c.stops_left == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
c.stops_left -= 1;
|
||||||
|
}
|
||||||
|
c.packet.sequence = c.packet.sequence.checked_add(1)?;
|
||||||
|
Some(c.packet)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(&self) -> OperatorView {
|
||||||
|
OperatorView {
|
||||||
|
active: self.capture.as_ref().is_some_and(|c| c.packet.enabled),
|
||||||
|
capture_id: self.capture.as_ref().map(|c| c.id),
|
||||||
|
mode: self.capture.as_ref().map(|c| c.mode),
|
||||||
|
reason: self.reason.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
fn context() -> OperatorContext {
|
||||||
|
OperatorContext {
|
||||||
|
role: Role::Team,
|
||||||
|
role_chosen: true,
|
||||||
|
board_id: Some(7),
|
||||||
|
board_ready: true,
|
||||||
|
hp: Some(100),
|
||||||
|
phase: "running",
|
||||||
|
connected: true,
|
||||||
|
has_source: true,
|
||||||
|
focused: true,
|
||||||
|
demo: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn input(id: u32, sequence: u32) -> OperatorInput {
|
||||||
|
OperatorInput {
|
||||||
|
capture_id: id,
|
||||||
|
sequence,
|
||||||
|
active: true,
|
||||||
|
forward: 1000,
|
||||||
|
strafe: 1000,
|
||||||
|
yaw: -900,
|
||||||
|
pitch: 400,
|
||||||
|
fire: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn only_explicit_bound_team_can_start_and_debug_cannot_bypass_match() {
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let mut c = context();
|
||||||
|
assert!(s.start(OperatorMode::Debug, &c, 0).is_err());
|
||||||
|
c.phase = "idle";
|
||||||
|
c.has_source = false;
|
||||||
|
c.connected = false;
|
||||||
|
assert!(s.start(OperatorMode::Match, &c, 0).is_err());
|
||||||
|
for change in 0..6 {
|
||||||
|
let mut bad = context();
|
||||||
|
match change {
|
||||||
|
0 => bad.role = Role::Referee,
|
||||||
|
1 => bad.board_id = None,
|
||||||
|
2 => bad.board_ready = false,
|
||||||
|
3 => bad.hp = Some(0),
|
||||||
|
4 => bad.demo = true,
|
||||||
|
_ => bad.focused = false,
|
||||||
|
}
|
||||||
|
assert!(s.start(OperatorMode::Match, &bad, 0).is_err());
|
||||||
|
}
|
||||||
|
assert!(s.start(OperatorMode::Debug, &c, 0).is_ok());
|
||||||
|
c.has_source = true;
|
||||||
|
assert!(!s.packet(&c, 20).unwrap().enabled);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn stale_inputs_never_rearm_and_stops_are_bounded_neutral() {
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let c = context();
|
||||||
|
let id = s.start(OperatorMode::Match, &c, 0).unwrap();
|
||||||
|
s.input(input(id, 1), &c, 10).unwrap();
|
||||||
|
let p = s.packet(&c, 20).unwrap();
|
||||||
|
assert_eq!(p.channels, [707, 707, -900, 400]);
|
||||||
|
assert!(p.fire);
|
||||||
|
assert!(s.input(input(id, 1), &c, 100).is_err());
|
||||||
|
let p = s.packet(&c, 160).unwrap();
|
||||||
|
assert!(!p.enabled);
|
||||||
|
assert_eq!(p.channels, [0; 4]);
|
||||||
|
assert!(!p.fire);
|
||||||
|
assert!(s.input(input(id, 2), &c, 161).is_err());
|
||||||
|
for n in 1..STOP_PACKETS {
|
||||||
|
assert!(s.packet(&c, 160 + n as u64 * 20).is_some());
|
||||||
|
}
|
||||||
|
assert!(s.packet(&c, 300).is_none());
|
||||||
|
let new_id = s.start(OperatorMode::Match, &c, 310).unwrap();
|
||||||
|
assert_ne!(new_id, id);
|
||||||
|
let mut old_stop = input(id, 4);
|
||||||
|
old_stop.active = false;
|
||||||
|
assert!(s.input(old_stop, &c, 320).is_err());
|
||||||
|
assert!(s.view().active);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn pause_binding_change_loss_and_invalid_values_end_the_capture() {
|
||||||
|
for change in 0..6 {
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let mut c = context();
|
||||||
|
let id = s.start(OperatorMode::Match, &c, 0).unwrap();
|
||||||
|
match change {
|
||||||
|
0 => c.phase = "paused",
|
||||||
|
1 => c.phase = "finished",
|
||||||
|
2 => c.connected = false,
|
||||||
|
3 => c.board_id = Some(9),
|
||||||
|
4 => c.focused = false,
|
||||||
|
_ => c.hp = Some(0),
|
||||||
|
}
|
||||||
|
assert!(!s.packet(&c, 20).unwrap().enabled);
|
||||||
|
assert!(s.input(input(id, 1), &context(), 30).is_err());
|
||||||
|
}
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let c = context();
|
||||||
|
let id = s.start(OperatorMode::Match, &c, 0).unwrap();
|
||||||
|
let mut bad = input(id, 1);
|
||||||
|
bad.yaw = 1001;
|
||||||
|
assert!(s.input(bad, &c, 10).is_err());
|
||||||
|
assert!(!s.view().active);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn debug_stops_at_countdown_and_does_not_return_at_idle() {
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let mut c = context();
|
||||||
|
c.phase = "preparation";
|
||||||
|
let id = s.start(OperatorMode::Debug, &c, 0).unwrap();
|
||||||
|
s.input(input(id, 1), &c, 10).unwrap();
|
||||||
|
assert_eq!(s.packet(&c, 20).unwrap().mode, 1);
|
||||||
|
c.phase = "countdown";
|
||||||
|
assert!(!s.packet(&c, 40).unwrap().enabled);
|
||||||
|
c.phase = "idle";
|
||||||
|
assert!(s.input(input(id, 2), &c, 50).is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn rebinding_cannot_discard_stop_retries_for_the_previous_board() {
|
||||||
|
let mut s = OperatorState::new(8);
|
||||||
|
let mut c = context();
|
||||||
|
let id = s.start(OperatorMode::Match, &c, 0).unwrap();
|
||||||
|
s.input(input(id, 1), &c, 10).unwrap();
|
||||||
|
s.stop("已退出");
|
||||||
|
c.board_id = Some(9);
|
||||||
|
assert!(s.start(OperatorMode::Match, &c, 20).is_err());
|
||||||
|
for n in 0..STOP_PACKETS {
|
||||||
|
let old = s.packet(&c, 20 + n as u64 * 20).unwrap();
|
||||||
|
assert_eq!(old.board_id, 7);
|
||||||
|
assert!(!old.enabled);
|
||||||
|
assert_eq!(old.channels, [0; 4]);
|
||||||
|
assert!(!old.fire);
|
||||||
|
}
|
||||||
|
s.start(OperatorMode::Match, &c, 140).unwrap();
|
||||||
|
assert_eq!(s.packet(&c, 150).unwrap().board_id, 9);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -385,6 +385,7 @@ pub struct SlotsDto {
|
|||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Snapshot {
|
pub struct Snapshot {
|
||||||
|
pub operator_control: crate::operator::OperatorView,
|
||||||
pub match_clock: crate::match_clock::MatchView,
|
pub match_clock: crate::match_clock::MatchView,
|
||||||
pub role: Role,
|
pub role: Role,
|
||||||
pub team: u8,
|
pub team: u8,
|
||||||
|
|||||||
+2
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "rmic-2026",
|
"name": "rmic-2026",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.4.1",
|
"version": "0.5.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
"test:stream": "node --test scripts/test-stream.mjs",
|
"test:stream": "node --test scripts/test-stream.mjs",
|
||||||
"test:latency": "node --test scripts/test-latency-marker.mjs",
|
"test:latency": "node --test scripts/test-latency-marker.mjs",
|
||||||
"test:match": "node --test scripts/test-match-clock.mjs",
|
"test:match": "node --test scripts/test-match-clock.mjs",
|
||||||
|
"test:input": "node --test scripts/test-operator-input.mjs",
|
||||||
"test:video": "node --test scripts/test-video-transform.mjs scripts/test-operator-hud.mjs",
|
"test:video": "node --test scripts/test-video-transform.mjs scripts/test-operator-hud.mjs",
|
||||||
"test:maintenance": "node --test scripts/test-maintenance.mjs"
|
"test:maintenance": "node --test scripts/test-maintenance.mjs"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ const matchModule = load("../src/components/MatchClock.tsx", {
|
|||||||
"../lib/match-time": matchTime,
|
"../lib/match-time": matchTime,
|
||||||
});
|
});
|
||||||
const { TeamPage } = load("../src/pages/TeamPage.tsx", {
|
const { TeamPage } = load("../src/pages/TeamPage.tsx", {
|
||||||
|
"../lib/use-operator-control": { useOperatorControl: () => ({ target: { current: null }, activeMode: null, pending: false }) },
|
||||||
|
"../components/OperatorControls": { OperatorControls: () => null },
|
||||||
"../components/HealthBar": healthModule,
|
"../components/HealthBar": healthModule,
|
||||||
"../components/VideoSurface": videoModule,
|
"../components/VideoSurface": videoModule,
|
||||||
"../components/HitFlash": { HitFlash: () => null },
|
"../components/HitFlash": { HitFlash: () => null },
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import ts from "typescript";
|
||||||
|
|
||||||
|
const exports = {};
|
||||||
|
new Function("exports", ts.transpileModule(readFileSync(new URL("../src/lib/operator-input.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||||
|
}).outputText)(exports);
|
||||||
|
const { OperatorEscapeGate, OperatorInputSampler, LatestInputSender, neutralAxes } = exports;
|
||||||
|
const sampler = () => { const value = new OperatorInputSampler(); value.reset(0); return value; };
|
||||||
|
const hookExports = {};
|
||||||
|
new Function("require", "exports", ts.transpileModule(readFileSync(new URL("../src/lib/use-operator-control.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||||
|
}).outputText)(() => ({}), hookExports);
|
||||||
|
const { operatorGate } = hookExports;
|
||||||
|
const snapshot = { role: "team", team: 0, config: { armorId: 42 }, armorBoards: [{ id: 42, team: 0, online: true, reportsAllPlates: true }],
|
||||||
|
health: [{ team: 0, hp: 100, outcome: null, available: true }], matchClock: { phase: "idle", source: null, connected: false } };
|
||||||
|
|
||||||
|
test("the first Escape releases capture, repeats are consumed, and the next press opens the menu", () => {
|
||||||
|
const gate = new OperatorEscapeGate();
|
||||||
|
assert.equal(gate.consume(true, true, 0), true);
|
||||||
|
assert.equal(gate.consume(true, false, 20), true);
|
||||||
|
assert.equal(gate.consume(false, false, 30), true);
|
||||||
|
assert.equal(gate.consume(true, false, 40), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pointer-lock release before Escape is consumed without swallowing a second physical key press", () => {
|
||||||
|
const gate = new OperatorEscapeGate();
|
||||||
|
gate.pointerReleased(100);
|
||||||
|
assert.equal(gate.consume(true, false, 110), true);
|
||||||
|
gate.consume(false, false, 120);
|
||||||
|
assert.equal(gate.consume(true, false, 130), false);
|
||||||
|
gate.pointerReleased(200);
|
||||||
|
gate.consume(false, false, 210); // Browser may deliver only keyup for the native unlock gesture.
|
||||||
|
assert.equal(gate.consume(true, false, 220), false);
|
||||||
|
gate.pointerReleased(300);
|
||||||
|
assert.equal(gate.consume(true, false, 401), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("debug is explicit before a match and refuses stale referee sessions and later phases", () => {
|
||||||
|
assert.equal(operatorGate(snapshot, true, "debug"), null);
|
||||||
|
assert.notEqual(operatorGate(snapshot, true, "match"), null);
|
||||||
|
for (const phase of ["idle", "preparation", "ready"]) {
|
||||||
|
assert.equal(operatorGate({ ...snapshot, matchClock: { phase, source: "192.0.2.1", connected: true } }, true, "debug"), null);
|
||||||
|
assert.notEqual(operatorGate({ ...snapshot, matchClock: { phase, source: "192.0.2.1", connected: false } }, true, "debug"), null);
|
||||||
|
}
|
||||||
|
for (const phase of ["countdown", "running", "paused", "finished"]) {
|
||||||
|
assert.notEqual(operatorGate({ ...snapshot, matchClock: { phase, source: "192.0.2.1", connected: true } }, true, "debug"), null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("normal operation needs the running clock, live bound team board and backend", () => {
|
||||||
|
const running = { ...snapshot, matchClock: { phase: "running", source: "192.0.2.1", connected: true } };
|
||||||
|
assert.equal(operatorGate(running, true, "match"), null);
|
||||||
|
for (const changed of [{ role: "referee" }, { armorBoards: [] }, { armorBoards: [{ id: 42, team: 1, online: true }] },
|
||||||
|
{ armorBoards: [{ ...snapshot.armorBoards[0], reportsAllPlates: false }] },
|
||||||
|
{ health: [{ team: 0, hp: 100, outcome: null, available: false }] },
|
||||||
|
{ health: [{ team: 0, hp: 0, outcome: "defeat", available: true }] }, { matchClock: { ...running.matchClock, connected: false } }]) {
|
||||||
|
assert.notEqual(operatorGate({ ...running, ...changed }, true, "match"), null);
|
||||||
|
}
|
||||||
|
assert.notEqual(operatorGate(running, false, "match"), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("equal mouse trajectories do not depend on the DOM event rate", () => {
|
||||||
|
const high = sampler(), low = sampler();
|
||||||
|
for (let i = 0; i < 20; i++) high.mouse(0.5, -0.25);
|
||||||
|
low.mouse(10, -5);
|
||||||
|
assert.deepEqual(high.sample(20), low.sample(20));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("velocity and smoothing use elapsed time, independent of sampling rate", () => {
|
||||||
|
const fast = sampler(), slow = sampler();
|
||||||
|
fast.mouse(10, -5); fast.sample(20);
|
||||||
|
fast.mouse(10, -5);
|
||||||
|
slow.mouse(20, -10);
|
||||||
|
assert.deepEqual(fast.sample(40), slow.sample(40));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("stationary mouse returns both channels to zero immediately while a held key remains active", () => {
|
||||||
|
const input = sampler(); input.key("KeyW", true); input.mouse(20, -20);
|
||||||
|
assert.ok(input.sample(20).axes.yaw > 0);
|
||||||
|
assert.deepEqual(input.sample(40).axes, { ...neutralAxes(), forward: 1000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("axis signs, limits, opposing keys and diagonal magnitude are defined", () => {
|
||||||
|
const input = sampler(); input.key("KeyW", true); input.key("KeyD", true);
|
||||||
|
input.mouse(-100000, 100000); input.trigger(true);
|
||||||
|
const { axes } = input.sample(20, 4);
|
||||||
|
assert.equal(axes.forward, 707); assert.equal(axes.strafe, 707);
|
||||||
|
assert.ok(axes.yaw < 0 && axes.yaw >= -1000); assert.ok(axes.pitch < 0 && axes.pitch >= -1000);
|
||||||
|
assert.equal(axes.fire, true);
|
||||||
|
input.key("KeyS", true); input.key("KeyA", true);
|
||||||
|
assert.equal(input.sample(40).axes.forward, 0);
|
||||||
|
assert.equal(input.sample(60).axes.strafe, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a stalled timer discards all buffered movement, keys and fire instead of replaying them", () => {
|
||||||
|
const input = sampler(); input.key("KeyW", true); input.mouse(9000, 9000); input.trigger(true);
|
||||||
|
assert.deepEqual(input.sample(101), { axes: neutralAxes(), stalled: true });
|
||||||
|
assert.deepEqual(input.sample(121), { axes: neutralAxes(), stalled: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reset clears held state and invalid mouse samples do not poison output", () => {
|
||||||
|
const input = sampler(); input.key("KeyA", true); input.trigger(true); input.mouse(10, 10); input.reset(10);
|
||||||
|
input.mouse(NaN, 20); input.mouse(Infinity, 1);
|
||||||
|
assert.deepEqual(input.sample(30).axes, neutralAxes());
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the sender keeps only the latest state behind one in-flight request", async () => {
|
||||||
|
const sent = []; const release = [];
|
||||||
|
const sender = new LatestInputSender(value => { sent.push(value); return new Promise(resolve => release.push(resolve)); }, error => { throw error; });
|
||||||
|
sender.offer(1); sender.offer(2); sender.offer(3);
|
||||||
|
assert.deepEqual(sent, [1]);
|
||||||
|
release.shift()(); await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(sent, [1, 3]);
|
||||||
|
release.shift()();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("stop replaces unsent movement and permanently rejects later offers", async () => {
|
||||||
|
const sent = []; const release = [];
|
||||||
|
const sender = new LatestInputSender(value => { sent.push(value); return new Promise(resolve => release.push(resolve)); }, error => { throw error; });
|
||||||
|
sender.offer("moving"); sender.offer("old movement"); sender.end("neutral"); sender.offer("late movement");
|
||||||
|
release.shift()(); await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(sent, ["moving", "neutral"]);
|
||||||
|
release.shift()();
|
||||||
|
});
|
||||||
@@ -33,6 +33,32 @@ const FALLBACK_INPUT_FPS: f32 = 20.0;
|
|||||||
|
|
||||||
type Shared<'a> = State<'a, Arc<AppState>>;
|
type Shared<'a> = State<'a, Arc<AppState>>;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn operator_start(
|
||||||
|
state: Shared<'_>,
|
||||||
|
window: tauri::Window,
|
||||||
|
maintenance: State<'_, Arc<crate::maintenance::MaintenanceState>>,
|
||||||
|
startup: State<'_, crate::startup::StartupState>,
|
||||||
|
mode: cam_core::operator::OperatorMode,
|
||||||
|
) -> Result<u32, String> {
|
||||||
|
if maintenance.is_busy() || !startup.finished() {
|
||||||
|
return Err("请先完成启动检查或固件维护,再开启操作".into());
|
||||||
|
}
|
||||||
|
let focused = window
|
||||||
|
.is_focused()
|
||||||
|
.map_err(|error| format!("无法检查窗口焦点:{error}"))?;
|
||||||
|
state.operator_focus(focused);
|
||||||
|
state.operator_start(mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn operator_input(
|
||||||
|
state: Shared<'_>,
|
||||||
|
input: cam_core::operator::OperatorInput,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
state.operator_input(input)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn match_action(
|
pub async fn match_action(
|
||||||
state: Shared<'_>,
|
state: Shared<'_>,
|
||||||
|
|||||||
@@ -23,14 +23,14 @@
|
|||||||
|
|
||||||
mod commands;
|
mod commands;
|
||||||
mod demo;
|
mod demo;
|
||||||
mod version;
|
mod firmware_build;
|
||||||
mod latency;
|
mod latency;
|
||||||
mod maintenance;
|
mod maintenance;
|
||||||
mod firmware_build;
|
|
||||||
mod recording;
|
mod recording;
|
||||||
mod server;
|
mod server;
|
||||||
mod state;
|
|
||||||
mod startup;
|
mod startup;
|
||||||
|
mod state;
|
||||||
|
mod version;
|
||||||
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -329,6 +329,8 @@ fn run() -> Result<(), Box<dyn Error>> {
|
|||||||
commands::stream_info,
|
commands::stream_info,
|
||||||
commands::get_snapshot,
|
commands::get_snapshot,
|
||||||
commands::match_action,
|
commands::match_action,
|
||||||
|
commands::operator_start,
|
||||||
|
commands::operator_input,
|
||||||
commands::release_match_source,
|
commands::release_match_source,
|
||||||
commands::get_config,
|
commands::get_config,
|
||||||
commands::list_media_files,
|
commands::list_media_files,
|
||||||
@@ -372,7 +374,11 @@ fn run() -> Result<(), Box<dyn Error>> {
|
|||||||
// 解锁框。拦不住的路径仍然存在——`kill -9`、强退、拔电源——所以它同样是"防
|
// 解锁框。拦不住的路径仍然存在——`kill -9`、强退、拔电源——所以它同样是"防
|
||||||
// 随手误操作",不是安全边界。
|
// 随手误操作",不是安全边界。
|
||||||
.on_window_event(|window, event| {
|
.on_window_event(|window, event| {
|
||||||
|
if let WindowEvent::Focused(focused) = event {
|
||||||
|
window.state::<Arc<AppState>>().operator_focus(*focused);
|
||||||
|
}
|
||||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
window.state::<Arc<AppState>>().stop_operator("窗口正在关闭,操作已停止");
|
||||||
if window.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
if window.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
||||||
api.prevent_close();
|
api.prevent_close();
|
||||||
let _ = window.emit("maintenance-close-blocked", "固件维护正在进行,请等待完成;编译可先取消。请勿在写入或恢复期间关闭客户端。");
|
let _ = window.emit("maintenance-close-blocked", "固件维护正在进行,请等待完成;编译可先取消。请勿在写入或恢复期间关闭客户端。");
|
||||||
@@ -391,15 +397,22 @@ fn run() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
app.run(|app, event| {
|
app.run(|app, event| {
|
||||||
if let RunEvent::ExitRequested { api, .. } = &event {
|
if let RunEvent::ExitRequested { api, .. } = &event {
|
||||||
|
app.state::<Arc<AppState>>()
|
||||||
|
.stop_operator("正在退出,操作已停止");
|
||||||
if app.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
if app.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
||||||
api.prevent_exit();
|
api.prevent_exit();
|
||||||
let _ = app.emit("maintenance-close-blocked", "固件维护正在进行,请等待完成后退出。");
|
let _ = app.emit(
|
||||||
|
"maintenance-close-blocked",
|
||||||
|
"固件维护正在进行,请等待完成后退出。",
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let state = app.state::<Arc<AppState>>();
|
let state = app.state::<Arc<AppState>>();
|
||||||
|
|
||||||
if app.state::<startup::StartupState>().finished()
|
if app.state::<startup::StartupState>().finished()
|
||||||
&& state.config().role.needs_password() && !state.is_unlocked() {
|
&& state.config().role.needs_password()
|
||||||
|
&& !state.is_unlocked()
|
||||||
|
{
|
||||||
api.prevent_exit();
|
api.prevent_exit();
|
||||||
state.push(server::WireMsg::ConfirmQuit);
|
state.push(server::WireMsg::ConfirmQuit);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ use anyhow::{Context, Result};
|
|||||||
use cam_core::armor::{ArmorHealthStore, HealthTracker};
|
use cam_core::armor::{ArmorHealthStore, HealthTracker};
|
||||||
use cam_core::config::{Config, Role};
|
use cam_core::config::{Config, Role};
|
||||||
use cam_core::match_clock::{MatchAction, MatchClock, MatchView};
|
use cam_core::match_clock::{MatchAction, MatchClock, MatchView};
|
||||||
|
use cam_core::operator::{OperatorContext, OperatorInput, OperatorMode, OperatorState};
|
||||||
use cam_core::password;
|
use cam_core::password;
|
||||||
use cam_core::receiver::{Discovery, LatestFrames, Receiver};
|
use cam_core::receiver::{Discovery, LatestFrames, Receiver};
|
||||||
use cam_core::slots::SlotAllocator;
|
use cam_core::slots::SlotAllocator;
|
||||||
@@ -59,6 +60,9 @@ pub struct AppState {
|
|||||||
match_socket: Option<std::net::UdpSocket>,
|
match_socket: Option<std::net::UdpSocket>,
|
||||||
match_error: Mutex<Option<String>>,
|
match_error: Mutex<Option<String>>,
|
||||||
match_changed: tokio::sync::Notify,
|
match_changed: tokio::sync::Notify,
|
||||||
|
operator: Mutex<OperatorState>,
|
||||||
|
operator_socket: Option<std::net::UdpSocket>,
|
||||||
|
operator_focused: AtomicBool,
|
||||||
resetting: AtomicBool,
|
resetting: AtomicBool,
|
||||||
pub demo_reset_epoch: AtomicUsize,
|
pub demo_reset_epoch: AtomicUsize,
|
||||||
discovery: Arc<Discovery>,
|
discovery: Arc<Discovery>,
|
||||||
@@ -86,6 +90,107 @@ pub struct AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
|
fn operator_context(&self) -> OperatorContext {
|
||||||
|
let config = self.config();
|
||||||
|
let clock = self.match_view();
|
||||||
|
let board = config
|
||||||
|
.armor_id
|
||||||
|
.and_then(|id| self.armor.boards().into_iter().find(|b| b.id == id));
|
||||||
|
OperatorContext {
|
||||||
|
role: config.role,
|
||||||
|
role_chosen: config.role_chosen,
|
||||||
|
board_id: config.armor_id,
|
||||||
|
board_ready: board
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|b| b.is_online() && b.team == config.team && b.reports_all_plates()),
|
||||||
|
hp: config
|
||||||
|
.armor_id
|
||||||
|
.and_then(|id| self.armor.health_of_board(id)),
|
||||||
|
phase: clock.phase,
|
||||||
|
connected: clock.connected,
|
||||||
|
has_source: clock.source.is_some(),
|
||||||
|
focused: self.operator_focused.load(Ordering::Acquire),
|
||||||
|
demo: self.demo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn operator_start(&self, mode: OperatorMode) -> Result<u32, String> {
|
||||||
|
if self.operator_socket.is_none() {
|
||||||
|
return Err("操控 UDP 通道不可用,请重启客户端".into());
|
||||||
|
}
|
||||||
|
let context = self.operator_context();
|
||||||
|
let id = self.operator.lock().expect("operator poisoned").start(
|
||||||
|
mode,
|
||||||
|
&context,
|
||||||
|
self.match_now(),
|
||||||
|
)?;
|
||||||
|
self.push_snapshot();
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn operator_input(&self, input: OperatorInput) -> Result<(), String> {
|
||||||
|
let context = self.operator_context();
|
||||||
|
let result = self.operator.lock().expect("operator poisoned").input(
|
||||||
|
input,
|
||||||
|
&context,
|
||||||
|
self.match_now(),
|
||||||
|
);
|
||||||
|
if !input.active || result.is_err() {
|
||||||
|
self.tick_operator();
|
||||||
|
self.push_snapshot();
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn operator_focus(&self, focused: bool) {
|
||||||
|
self.operator_focused.store(focused, Ordering::Release);
|
||||||
|
if !focused {
|
||||||
|
self.stop_operator("窗口失焦,操作已停止");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_operator(&self, reason: &str) {
|
||||||
|
self.operator
|
||||||
|
.lock()
|
||||||
|
.expect("operator poisoned")
|
||||||
|
.stop(reason);
|
||||||
|
self.tick_operator();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tick_operator(&self) {
|
||||||
|
let context = self.operator_context();
|
||||||
|
let packet = self
|
||||||
|
.operator
|
||||||
|
.lock()
|
||||||
|
.expect("operator poisoned")
|
||||||
|
.packet(&context, self.match_now());
|
||||||
|
if self.demo {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(packet) = packet else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// 地址只从显式绑定板的上报取得。禁能帧仍发给原板,不受新绑定替换。
|
||||||
|
let destination = self
|
||||||
|
.armor
|
||||||
|
.boards()
|
||||||
|
.into_iter()
|
||||||
|
.find(|b| b.id == packet.board_id)
|
||||||
|
.map(|b| b.addr);
|
||||||
|
let sent = match (&self.operator_socket, destination, packet.encode()) {
|
||||||
|
(Some(socket), Some(destination), Some(bytes)) => {
|
||||||
|
socket.send_to(&bytes, destination).map(|_| ())
|
||||||
|
}
|
||||||
|
_ => Err(std::io::Error::other("装甲板操控地址不可用")),
|
||||||
|
};
|
||||||
|
if let Err(error) = sent {
|
||||||
|
self.operator
|
||||||
|
.lock()
|
||||||
|
.expect("operator poisoned")
|
||||||
|
.stop(&format!("操控发送失败:{error};请重新开启"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn match_now(&self) -> u64 {
|
fn match_now(&self) -> u64 {
|
||||||
self.started.elapsed().as_millis().min(u64::MAX as u128) as u64
|
self.started.elapsed().as_millis().min(u64::MAX as u128) as u64
|
||||||
}
|
}
|
||||||
@@ -313,6 +418,9 @@ impl AppState {
|
|||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.as_nanos() as u64;
|
.as_nanos() as u64;
|
||||||
|
let operator_socket = std::net::UdpSocket::bind((std::net::Ipv4Addr::UNSPECIFIED, 0))
|
||||||
|
.ok()
|
||||||
|
.filter(|socket| socket.set_nonblocking(true).is_ok());
|
||||||
let state = Arc::new(Self {
|
let state = Arc::new(Self {
|
||||||
config_path,
|
config_path,
|
||||||
config: Mutex::new(config),
|
config: Mutex::new(config),
|
||||||
@@ -324,6 +432,9 @@ impl AppState {
|
|||||||
match_socket,
|
match_socket,
|
||||||
match_error: Mutex::new(match_error),
|
match_error: Mutex::new(match_error),
|
||||||
match_changed: tokio::sync::Notify::new(),
|
match_changed: tokio::sync::Notify::new(),
|
||||||
|
operator: Mutex::new(OperatorState::new(session)),
|
||||||
|
operator_socket,
|
||||||
|
operator_focused: AtomicBool::new(true),
|
||||||
resetting: AtomicBool::new(false),
|
resetting: AtomicBool::new(false),
|
||||||
demo_reset_epoch: AtomicUsize::new(0),
|
demo_reset_epoch: AtomicUsize::new(0),
|
||||||
discovery,
|
discovery,
|
||||||
@@ -457,6 +568,16 @@ impl AppState {
|
|||||||
server::serve(listener, token, tx, video, clients).await;
|
server::serve(listener, token, tx, video, clients).await;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let operator_state = Arc::clone(&state);
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
let mut ticker = tokio::time::interval(Duration::from_millis(20));
|
||||||
|
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
loop {
|
||||||
|
ticker.tick().await;
|
||||||
|
operator_state.tick_operator();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let state_for_loop = Arc::clone(&state);
|
let state_for_loop = Arc::clone(&state);
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
let mut ticker = tokio::time::interval(SNAPSHOT_INTERVAL);
|
let mut ticker = tokio::time::interval(SNAPSHOT_INTERVAL);
|
||||||
@@ -507,6 +628,7 @@ impl AppState {
|
|||||||
/// 每一次可能改变身份、绑定或发现开合的改动之后都要调用它——把这件事收在一个函数
|
/// 每一次可能改变身份、绑定或发现开合的改动之后都要调用它——把这件事收在一个函数
|
||||||
/// 里,是为了不让"某个命令忘了重新套用闸门"这种漏洞有时间长出来。
|
/// 里,是为了不让"某个命令忘了重新套用闸门"这种漏洞有时间长出来。
|
||||||
pub fn apply_gates(&self) {
|
pub fn apply_gates(&self) {
|
||||||
|
self.stop_operator("身份、绑定或设置已改变,请重新开启操作");
|
||||||
let config = self.config();
|
let config = self.config();
|
||||||
self.match_clock
|
self.match_clock
|
||||||
.lock()
|
.lock()
|
||||||
@@ -836,6 +958,7 @@ impl AppState {
|
|||||||
.apply_outcomes(&mut health);
|
.apply_outcomes(&mut health);
|
||||||
|
|
||||||
Snapshot {
|
Snapshot {
|
||||||
|
operator_control: self.operator.lock().expect("operator poisoned").view(),
|
||||||
match_clock: self.match_view(),
|
match_clock: self.match_view(),
|
||||||
role: config.role,
|
role: config.role,
|
||||||
team: config.team,
|
team: config.team,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "RMIC-2026",
|
"productName": "RMIC-2026",
|
||||||
"version": "0.4.1",
|
"version": "0.5.0",
|
||||||
"identifier": "com.simbarobotics.rmic2026",
|
"identifier": "com.simbarobotics.rmic2026",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -422,6 +422,7 @@ export default function App() {
|
|||||||
snapshot={snapshot}
|
snapshot={snapshot}
|
||||||
hud={hud ?? snapshot.config.hud}
|
hud={hud ?? snapshot.config.hud}
|
||||||
calibrating={calibrating}
|
calibrating={calibrating}
|
||||||
|
controlsBlocked={operatorMenu || drawer || drawerClosing || unlockReason !== null || maintenance || !bootGone}
|
||||||
onCalibrate={onCalibrate}
|
onCalibrate={onCalibrate}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { Snapshot } from "../lib/types";
|
||||||
|
import { operatorGate, type useOperatorControl } from "../lib/use-operator-control";
|
||||||
|
|
||||||
|
export function OperatorControls({ control, snapshot, connected, blocked }: {
|
||||||
|
control: ReturnType<typeof useOperatorControl>;
|
||||||
|
snapshot: Snapshot;
|
||||||
|
connected: boolean;
|
||||||
|
blocked: boolean;
|
||||||
|
}) {
|
||||||
|
const matchReason = operatorGate(snapshot, connected, "match");
|
||||||
|
const debugReason = operatorGate(snapshot, connected, "debug");
|
||||||
|
return <section className={`operator-controls${control.activeMode ? " is-active" : ""}${control.activeMode === "debug" ? " is-debug" : ""}`} aria-label="机器人操作" onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()}>
|
||||||
|
{control.activeMode ? <>
|
||||||
|
<strong>{control.activeMode === "debug" ? "赛前调试发送中" : "操作输入发送中"}{snapshot.demo ? " · 合成输入" : ""}</strong>
|
||||||
|
<span>WASD 移动 · 鼠标控制云台 · 左键发射 · ESC 退出</span>
|
||||||
|
<small>{snapshot.demo ? "仅合成预览,无真实发送" : "仅表示客户端发送状态;装甲板及下位机无应答"}</small>
|
||||||
|
</> : <>
|
||||||
|
<div className="operator-controls__actions">
|
||||||
|
<button className="btn btn--primary" disabled={blocked || control.pending || !!matchReason} title={matchReason ?? "锁定鼠标并开始接收键鼠输入"} onClick={() => control.start("match")}>{control.pending ? "正在处理…" : "开启比赛操作"}</button>
|
||||||
|
<button className="btn" disabled={blocked || control.pending || !!debugReason} title={debugReason ?? "未开赛时显式开启调试,开始倒数后自动停止"} onClick={() => control.start("debug")}>开启赛前调试</button>
|
||||||
|
</div>
|
||||||
|
<label className="operator-controls__sensitivity">鼠标灵敏度 <input aria-label="本次鼠标灵敏度" type="range" min="0.25" max="4" step="0.25" value={control.sensitivity} onChange={event => control.setSensitivity(Number(event.target.value))} /><span>×{control.sensitivity.toFixed(2)} · 本次</span></label>
|
||||||
|
<p>{snapshot.demo ? "预览使用合成数据,不向装甲板发送真实操作。" : "WASD 移动 · 鼠标控制云台速度 · 左键发射;ESC 或失焦立即停止。"}</p>
|
||||||
|
{!snapshot.demo && <p>仅确认客户端发送,装甲板及下位机未提供应答。装甲板重启或连接超时后,请退出再开启。</p>}
|
||||||
|
{matchReason && debugReason && <p>{matchReason};{debugReason}</p>}
|
||||||
|
{control.error && <p className="operator-controls__error" role="alert">{control.error}</p>}
|
||||||
|
</>}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
@@ -70,6 +70,8 @@ interface Props {
|
|||||||
onView: (view: ViewTransform) => void;
|
onView: (view: ViewTransform) => void;
|
||||||
/** 校准模式:拖动画面来挪瞄准点。 */
|
/** 校准模式:拖动画面来挪瞄准点。 */
|
||||||
calibrating?: boolean;
|
calibrating?: boolean;
|
||||||
|
/** FPS 操作时停用画面拖动和缩放,输入由选手端捕获。 */
|
||||||
|
inputCaptured?: boolean;
|
||||||
onCalibrate?: (dxFraction: number, dyFraction: number) => void;
|
onCalibrate?: (dxFraction: number, dyFraction: number) => void;
|
||||||
/** 命中脉冲。只有属于这一路的命中才该传进来。 */
|
/** 命中脉冲。只有属于这一路的命中才该传进来。 */
|
||||||
hit?: HitPulse | null;
|
hit?: HitPulse | null;
|
||||||
@@ -107,6 +109,7 @@ export function VideoSurface({
|
|||||||
view,
|
view,
|
||||||
onView,
|
onView,
|
||||||
calibrating = false,
|
calibrating = false,
|
||||||
|
inputCaptured = false,
|
||||||
onCalibrate,
|
onCalibrate,
|
||||||
hit = null,
|
hit = null,
|
||||||
hitFeedback,
|
hitFeedback,
|
||||||
@@ -226,6 +229,7 @@ export function VideoSurface({
|
|||||||
// ---- 输入 ----
|
// ---- 输入 ----
|
||||||
|
|
||||||
const onWheel = (event: React.WheelEvent<HTMLDivElement>) => {
|
const onWheel = (event: React.WheelEvent<HTMLDivElement>) => {
|
||||||
|
if (inputCaptured) return;
|
||||||
const factor = event.deltaY > 0 ? 1 / ZOOM_STEP : ZOOM_STEP;
|
const factor = event.deltaY > 0 ? 1 / ZOOM_STEP : ZOOM_STEP;
|
||||||
const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);
|
const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);
|
||||||
|
|
||||||
@@ -235,6 +239,7 @@ export function VideoSurface({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||||
|
if (inputCaptured || (event.target as HTMLElement).closest("button, input, select, a")) return;
|
||||||
event.currentTarget.setPointerCapture(event.pointerId);
|
event.currentTarget.setPointerCapture(event.pointerId);
|
||||||
dragging.current = true;
|
dragging.current = true;
|
||||||
drag.current = { x: event.clientX, y: event.clientY, originX: view.x, originY: view.y };
|
drag.current = { x: event.clientX, y: event.clientY, originX: view.x, originY: view.y };
|
||||||
@@ -242,6 +247,7 @@ export function VideoSurface({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
|
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||||
|
if (inputCaptured) return;
|
||||||
const start = drag.current;
|
const start = drag.current;
|
||||||
if (!start) return;
|
if (!start) return;
|
||||||
|
|
||||||
@@ -279,7 +285,7 @@ export function VideoSurface({
|
|||||||
drag.current = null;
|
drag.current = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const cursor = calibrating ? "crosshair" : view.zoom > MIN_ZOOM ? "grab" : "default";
|
const cursor = inputCaptured ? "none" : calibrating ? "crosshair" : view.zoom > MIN_ZOOM ? "grab" : "default";
|
||||||
const zoomed = shown.current.zoom > MIN_ZOOM + 0.05;
|
const zoomed = shown.current.zoom > MIN_ZOOM + 0.05;
|
||||||
const moved = view.zoom > MIN_ZOOM + 0.05 || view.x !== 0 || view.y !== 0;
|
const moved = view.zoom > MIN_ZOOM + 0.05 || view.x !== 0 || view.y !== 0;
|
||||||
|
|
||||||
@@ -298,7 +304,7 @@ export function VideoSurface({
|
|||||||
onPointerMove={onPointerMove}
|
onPointerMove={onPointerMove}
|
||||||
onPointerUp={endDrag}
|
onPointerUp={endDrag}
|
||||||
onPointerCancel={endDrag}
|
onPointerCancel={endDrag}
|
||||||
onDoubleClick={() => onView(IDENTITY_VIEW)}
|
onDoubleClick={() => { if (!inputCaptured) onView(IDENTITY_VIEW); }}
|
||||||
>
|
>
|
||||||
<canvas ref={canvasRef} className="vsurface__canvas" />
|
<canvas ref={canvasRef} className="vsurface__canvas" />
|
||||||
{signalLost && <div className="vsurface__signal-mask" aria-hidden="true" />}
|
{signalLost && <div className="vsurface__signal-mask" aria-hidden="true" />}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
import { DEFAULT_TEAM_NAMES } from "./format";
|
import { DEFAULT_TEAM_NAMES } from "./format";
|
||||||
import { previewMatch, previewMatchAction } from "./match-preview";
|
import { previewMatch, previewMatchAction } from "./match-preview";
|
||||||
import type { MatchAction } from "./types";
|
import type { MatchAction, OperatorControlView, OperatorInput } from "./types";
|
||||||
import type { StreamClient } from "./stream";
|
import type { StreamClient } from "./stream";
|
||||||
import type {
|
import type {
|
||||||
ConfigView,
|
ConfigView,
|
||||||
@@ -166,8 +166,28 @@ export async function previewInvoke<T>(command: string, args?: Record<string, un
|
|||||||
return value as T;
|
return value as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let previewCapture = 0;
|
||||||
|
let previewCaptureAt = 0;
|
||||||
|
let previewInputSequence = 0;
|
||||||
|
let previewOperator: OperatorControlView = { active: false, captureId: null, mode: null, reason: "预览 · 未发送真实操作" };
|
||||||
|
|
||||||
function handle(command: string, args: Record<string, unknown>): unknown {
|
function handle(command: string, args: Record<string, unknown>): unknown {
|
||||||
switch (command) {
|
switch (command) {
|
||||||
|
case "operator_start": {
|
||||||
|
if (state.role !== "team") throw new Error("只有选手端可以开启操作");
|
||||||
|
const mode = args.mode === "debug" ? "debug" : "match";
|
||||||
|
previewInputSequence = 0;
|
||||||
|
previewCaptureAt = performance.now();
|
||||||
|
previewOperator = { active: true, captureId: ++previewCapture, mode, reason: "预览 · 合成输入,不发送到装甲板" };
|
||||||
|
return previewCapture;
|
||||||
|
}
|
||||||
|
case "operator_input": {
|
||||||
|
const input = args.input as OperatorInput;
|
||||||
|
if (input.captureId !== previewOperator.captureId || input.sequence <= previewInputSequence) return;
|
||||||
|
previewInputSequence = input.sequence;
|
||||||
|
if (!input.active) previewOperator = { ...previewOperator, active: false, reason: "预览操作已停止" };
|
||||||
|
return;
|
||||||
|
}
|
||||||
case "match_action": {
|
case "match_action": {
|
||||||
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
||||||
const action = args.action as MatchAction;
|
const action = args.action as MatchAction;
|
||||||
@@ -320,6 +340,11 @@ function hex(id: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function snapshot(): Snapshot {
|
function snapshot(): Snapshot {
|
||||||
|
// 合成联动场景:显式开启调试后 3 秒切入倒数,检查自动释放输入。
|
||||||
|
if (params.get("control") === "debug-to-countdown" && previewOperator.active && previewOperator.mode === "debug"
|
||||||
|
&& performance.now() - previewCaptureAt > 3000 && ["idle", "preparation", "ready"].includes(previewMatch().phase)) {
|
||||||
|
previewMatchAction({ type: "countdown", seconds: 10 });
|
||||||
|
}
|
||||||
finishPreviewKnockout();
|
finishPreviewKnockout();
|
||||||
const cameraOffline = videoOffline();
|
const cameraOffline = videoOffline();
|
||||||
const cameras = [
|
const cameras = [
|
||||||
@@ -408,6 +433,7 @@ function snapshot(): Snapshot {
|
|||||||
mirrored: state.mirror,
|
mirrored: state.mirror,
|
||||||
mirroredVertical: state.mirrorVertical,
|
mirroredVertical: state.mirrorVertical,
|
||||||
matchClock: previewMatch(),
|
matchClock: previewMatch(),
|
||||||
|
operatorControl: { ...previewOperator },
|
||||||
demo: true,
|
demo: true,
|
||||||
diagnostics: true,
|
diagnostics: true,
|
||||||
unlocked: state.unlocked || state.role === "referee",
|
unlocked: state.unlocked || state.role === "referee",
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ import type {
|
|||||||
Snapshot,
|
Snapshot,
|
||||||
MatchAction,
|
MatchAction,
|
||||||
StreamInfo,
|
StreamInfo,
|
||||||
|
OperatorInput,
|
||||||
|
OperatorMode,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -44,6 +46,8 @@ async function call<T>(command: string, args?: Record<string, unknown>): Promise
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
|
operatorStart: (mode: OperatorMode) => call<number>("operator_start", { mode }),
|
||||||
|
operatorInput: (input: OperatorInput) => call<void>("operator_input", { input }),
|
||||||
matchAction: (action: MatchAction) => call<void>("match_action", { action }),
|
matchAction: (action: MatchAction) => call<void>("match_action", { action }),
|
||||||
releaseMatchSource: () => call<void>("release_match_source"),
|
releaseMatchSource: () => call<void>("release_match_source"),
|
||||||
// ---- 只读 ----
|
// ---- 只读 ----
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
/** 操作输入按时间窗转换为速度;不依赖 DOM 事件频率或画面帧率。 */
|
||||||
|
export const INPUT_INTERVAL_MS = 20;
|
||||||
|
export const INPUT_STALL_MS = 100;
|
||||||
|
export const MOUSE_FULL_SCALE_PER_SECOND = 1000;
|
||||||
|
const FILTER_MS = 25;
|
||||||
|
|
||||||
|
export interface OperatorAxes {
|
||||||
|
forward: number;
|
||||||
|
strafe: number;
|
||||||
|
yaw: number;
|
||||||
|
pitch: number;
|
||||||
|
fire: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const neutralAxes = (): OperatorAxes => ({ forward: 0, strafe: 0, yaw: 0, pitch: 0, fire: false });
|
||||||
|
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
|
||||||
|
|
||||||
|
/** 将释放 Pointer Lock 的同一次 Esc 与后续打开菜单的 Esc 区分开。 */
|
||||||
|
export class OperatorEscapeGate {
|
||||||
|
private held = false;
|
||||||
|
private releasedAt = -Infinity;
|
||||||
|
|
||||||
|
pointerReleased(now: number) { this.releasedAt = now; }
|
||||||
|
|
||||||
|
consume(down: boolean, capturing: boolean, now: number): boolean {
|
||||||
|
if (!down) {
|
||||||
|
const consumed = this.held;
|
||||||
|
this.held = false;
|
||||||
|
this.releasedAt = -Infinity;
|
||||||
|
return consumed;
|
||||||
|
}
|
||||||
|
if (capturing || this.held || now - this.releasedAt < 100) {
|
||||||
|
this.held = true;
|
||||||
|
this.releasedAt = -Infinity;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OperatorInputSampler {
|
||||||
|
private keys = new Set<string>();
|
||||||
|
private dx = 0;
|
||||||
|
private dy = 0;
|
||||||
|
private yaw = 0;
|
||||||
|
private pitch = 0;
|
||||||
|
private fire = false;
|
||||||
|
private at = 0;
|
||||||
|
|
||||||
|
reset(now: number) {
|
||||||
|
this.keys.clear();
|
||||||
|
this.dx = this.dy = this.yaw = this.pitch = 0;
|
||||||
|
this.fire = false;
|
||||||
|
this.at = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
key(code: string, down: boolean) {
|
||||||
|
if (!["KeyW", "KeyA", "KeyS", "KeyD"].includes(code)) return false;
|
||||||
|
if (down) this.keys.add(code); else this.keys.delete(code);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
mouse(dx: number, dy: number) {
|
||||||
|
if (!Number.isFinite(dx) || !Number.isFinite(dy)) return;
|
||||||
|
this.dx = clamp(this.dx + dx, 100_000);
|
||||||
|
this.dy = clamp(this.dy + dy, 100_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
trigger(down: boolean) { this.fire = down; }
|
||||||
|
|
||||||
|
sample(now: number, sensitivity = 1): { axes: OperatorAxes; stalled: boolean } {
|
||||||
|
const dt = now - this.at;
|
||||||
|
this.at = now;
|
||||||
|
if (!Number.isFinite(dt) || dt <= 0 || dt > INPUT_STALL_MS) {
|
||||||
|
this.reset(now);
|
||||||
|
return { axes: neutralAxes(), stalled: true };
|
||||||
|
}
|
||||||
|
const gain = Number.isFinite(sensitivity) ? Math.max(0.25, Math.min(4, sensitivity)) : 1;
|
||||||
|
const scale = 1000 * 1000 * gain / (dt * MOUSE_FULL_SCALE_PER_SECOND);
|
||||||
|
const alpha = 1 - Math.exp(-dt / FILTER_MS);
|
||||||
|
// 停止移动立即回零,不让低通滤波的尾迹继续驱动云台。
|
||||||
|
this.yaw = this.dx === 0 ? 0 : this.yaw + alpha * (clamp(this.dx * scale, 1000) - this.yaw);
|
||||||
|
this.pitch = this.dy === 0 ? 0 : this.pitch + alpha * (clamp(-this.dy * scale, 1000) - this.pitch);
|
||||||
|
this.dx = this.dy = 0;
|
||||||
|
const forward = Number(this.keys.has("KeyW")) - Number(this.keys.has("KeyS"));
|
||||||
|
const strafe = Number(this.keys.has("KeyD")) - Number(this.keys.has("KeyA"));
|
||||||
|
const length = Math.max(1, Math.hypot(forward, strafe));
|
||||||
|
return { axes: {
|
||||||
|
forward: Math.round(forward * 1000 / length),
|
||||||
|
strafe: Math.round(strafe * 1000 / length),
|
||||||
|
yaw: Math.round(this.yaw), pitch: Math.round(this.pitch), fire: this.fire,
|
||||||
|
}, stalled: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一个在途请求和一个最新状态;结束包会替换未发送的运动状态。 */
|
||||||
|
export class LatestInputSender<T> {
|
||||||
|
private pending: T | null = null;
|
||||||
|
private running = false;
|
||||||
|
private ended = false;
|
||||||
|
private idleWaiters: (() => void)[] = [];
|
||||||
|
|
||||||
|
constructor(private send: (value: T) => Promise<void>, private onError: (error: unknown) => void) {}
|
||||||
|
|
||||||
|
offer(value: T) {
|
||||||
|
if (this.ended) return;
|
||||||
|
this.pending = value;
|
||||||
|
void this.drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
end(value: T) {
|
||||||
|
if (!this.ended) {
|
||||||
|
this.ended = true;
|
||||||
|
this.pending = value;
|
||||||
|
void this.drain();
|
||||||
|
}
|
||||||
|
if (!this.running && this.pending === null) return Promise.resolve();
|
||||||
|
return new Promise<void>(resolve => this.idleWaiters.push(resolve));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async drain() {
|
||||||
|
if (this.running) return;
|
||||||
|
this.running = true;
|
||||||
|
try {
|
||||||
|
while (this.pending !== null) {
|
||||||
|
const value = this.pending;
|
||||||
|
this.pending = null;
|
||||||
|
try { await this.send(value); } catch (error) { this.onError(error); }
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
for (const resolve of this.idleWaiters.splice(0)) resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,26 @@
|
|||||||
|
|
||||||
export type Role = "team" | "referee";
|
export type Role = "team" | "referee";
|
||||||
|
|
||||||
|
export type OperatorMode = "match" | "debug";
|
||||||
|
|
||||||
|
export interface OperatorInput {
|
||||||
|
captureId: number;
|
||||||
|
sequence: number;
|
||||||
|
active: boolean;
|
||||||
|
forward: number;
|
||||||
|
strafe: number;
|
||||||
|
yaw: number;
|
||||||
|
pitch: number;
|
||||||
|
fire: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorControlView {
|
||||||
|
active: boolean;
|
||||||
|
captureId: number | null;
|
||||||
|
mode: OperatorMode | null;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** `cam_core::config::CrosshairStyle` */
|
/** `cam_core::config::CrosshairStyle` */
|
||||||
export type CrosshairStyle = "cross" | "cross-dot" | "circle-dot" | "dot";
|
export type CrosshairStyle = "cross" | "cross-dot" | "circle-dot" | "dot";
|
||||||
|
|
||||||
@@ -207,6 +227,7 @@ export interface MediaFileDto {
|
|||||||
|
|
||||||
/** `cam_core::snapshot::Snapshot` */
|
/** `cam_core::snapshot::Snapshot` */
|
||||||
export interface Snapshot {
|
export interface Snapshot {
|
||||||
|
operatorControl: OperatorControlView;
|
||||||
matchClock: MatchClockView;
|
matchClock: MatchClockView;
|
||||||
role: Role;
|
role: Role;
|
||||||
team: number;
|
team: number;
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { api } from "./ipc";
|
||||||
|
import { INPUT_INTERVAL_MS, INPUT_STALL_MS, LatestInputSender, neutralAxes, OperatorEscapeGate, OperatorInputSampler } from "./operator-input";
|
||||||
|
import type { OperatorInput, OperatorMode, Snapshot } from "./types";
|
||||||
|
|
||||||
|
interface Options { snapshot: Snapshot; connected: boolean; blocked: boolean }
|
||||||
|
interface Capture {
|
||||||
|
id: number; sequence: number; mode: OperatorMode; started: number; observed: boolean;
|
||||||
|
sender: LatestInputSender<{ input: OperatorInput; at: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function operatorGate(snapshot: Snapshot, connected: boolean, mode: OperatorMode): string | null {
|
||||||
|
if (snapshot.role !== "team") return "仅选手端可操作";
|
||||||
|
if (!connected) return "本机服务断开";
|
||||||
|
const board = snapshot.armorBoards.find(board => board.id === snapshot.config.armorId);
|
||||||
|
if (!board?.online) return "请先绑定在线装甲板";
|
||||||
|
if (board.team !== snapshot.team) return "装甲板队伍不符";
|
||||||
|
if (!board.reportsAllPlates) return "等待装甲板四路状态上报";
|
||||||
|
if (!snapshot.health.find(health => health.team === snapshot.team)?.available) return "本方血量状态尚未更新";
|
||||||
|
if (snapshot.health.some(health => health.team === snapshot.team && (health.outcome !== null || health.hp === 0))) return "本局已结束,请由裁判重置";
|
||||||
|
const clock = snapshot.matchClock;
|
||||||
|
if (mode === "match") return clock.phase === "running" && clock.connected ? null : "等待比赛开始并保持裁判连接";
|
||||||
|
if (!["idle", "preparation", "ready"].includes(clock.phase)) return "仅未开始、准备或待开赛时可调试";
|
||||||
|
if (clock.source !== null && !clock.connected) return "裁判连接已中断,暂不能调试";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useOperatorControl(options: Options) {
|
||||||
|
const target = useRef<HTMLDivElement>(null);
|
||||||
|
const current = useRef(options);
|
||||||
|
current.current = options;
|
||||||
|
const sampler = useRef(new OperatorInputSampler());
|
||||||
|
const capture = useRef<Capture | null>(null);
|
||||||
|
const attempt = useRef<{ generation: number; mode: OperatorMode; starting: boolean } | null>(null);
|
||||||
|
const generation = useRef(0);
|
||||||
|
const backendStarting = useRef(false);
|
||||||
|
const ending = useRef(0);
|
||||||
|
const mounted = useRef(true);
|
||||||
|
const sensitivityRef = useRef(1);
|
||||||
|
const [sensitivity, setSensitivityState] = useState(1);
|
||||||
|
const [activeMode, setActiveMode] = useState<OperatorMode | null>(null);
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
const stop = useCallback((reason = "") => {
|
||||||
|
generation.current++;
|
||||||
|
attempt.current = null;
|
||||||
|
sampler.current.reset(performance.now());
|
||||||
|
const session = capture.current;
|
||||||
|
capture.current = null;
|
||||||
|
if (session) {
|
||||||
|
ending.current++;
|
||||||
|
void session.sender.end({ input: { captureId: session.id, sequence: ++session.sequence, active: false, ...neutralAxes() }, at: performance.now() }).finally(() => {
|
||||||
|
ending.current--;
|
||||||
|
if (mounted.current) setPending(backendStarting.current || ending.current > 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (document.pointerLockElement === target.current) document.exitPointerLock();
|
||||||
|
if (mounted.current) {
|
||||||
|
setActiveMode(null);
|
||||||
|
setPending(backendStarting.current || ending.current > 0);
|
||||||
|
if (reason) setError(reason);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const startBackend = useCallback(() => {
|
||||||
|
const requested = attempt.current;
|
||||||
|
if (!requested || requested.starting || document.pointerLockElement !== target.current) return;
|
||||||
|
requested.starting = true;
|
||||||
|
backendStarting.current = true;
|
||||||
|
void api.operatorStart(requested.mode).then(async id => {
|
||||||
|
if (!mounted.current || attempt.current !== requested || generation.current !== requested.generation || document.pointerLockElement !== target.current) {
|
||||||
|
// 失焦/ESC 可能发生在 start 返回前;结束已创建的会话,不能把它重新启用。
|
||||||
|
await api.operatorInput({ captureId: id, sequence: 1, active: false, ...neutralAxes() }).catch(() => undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const sender = new LatestInputSender<{ input: OperatorInput; at: number }>(async packet => {
|
||||||
|
if (packet.input.active && performance.now() - packet.at > INPUT_STALL_MS) {
|
||||||
|
if (capture.current?.id === id) stop("操作输入延迟过大,已停止,请重新开启");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await api.operatorInput(packet.input);
|
||||||
|
}, err => { if (capture.current?.id === id) stop(String(err)); });
|
||||||
|
capture.current = { id, sequence: 0, mode: requested.mode, started: performance.now(), observed: false, sender };
|
||||||
|
attempt.current = null;
|
||||||
|
sampler.current.reset(performance.now());
|
||||||
|
setActiveMode(requested.mode);
|
||||||
|
setPending(false);
|
||||||
|
sender.offer({ input: { captureId: id, sequence: 1, active: true, ...neutralAxes() }, at: performance.now() });
|
||||||
|
capture.current.sequence = 1;
|
||||||
|
}).catch(err => { if (attempt.current === requested) stop(String(err)); }).finally(() => {
|
||||||
|
backendStarting.current = false;
|
||||||
|
if (mounted.current && !attempt.current) setPending(ending.current > 0);
|
||||||
|
});
|
||||||
|
}, [stop]);
|
||||||
|
|
||||||
|
const start = useCallback((mode: OperatorMode) => {
|
||||||
|
if (capture.current || attempt.current || backendStarting.current || ending.current > 0) return;
|
||||||
|
const { snapshot, connected, blocked } = current.current;
|
||||||
|
const reason = blocked ? "请先关闭菜单或设置" : operatorGate(snapshot, connected, mode);
|
||||||
|
if (reason) { setError(reason); return; }
|
||||||
|
const element = target.current;
|
||||||
|
if (!element?.requestPointerLock) { setError("当前窗口不支持鼠标锁定,无法开启操作"); return; }
|
||||||
|
setError("");
|
||||||
|
setPending(true);
|
||||||
|
const requested = { generation: ++generation.current, mode, starting: false };
|
||||||
|
attempt.current = requested;
|
||||||
|
// 必须直接在点击事件中请求锁定,等待 IPC 后再请求会失去用户手势。
|
||||||
|
try {
|
||||||
|
void Promise.resolve(element.requestPointerLock()).then(startBackend).catch(err => {
|
||||||
|
if (attempt.current === requested) stop(`无法锁定鼠标:${String(err)}`);
|
||||||
|
});
|
||||||
|
} catch (err) { stop(`无法锁定鼠标:${String(err)}`); }
|
||||||
|
}, [startBackend, stop]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mounted.current = true;
|
||||||
|
const escape = new OperatorEscapeGate();
|
||||||
|
const isCapturing = () => capture.current !== null && document.pointerLockElement === target.current;
|
||||||
|
const key = (event: KeyboardEvent, down: boolean) => {
|
||||||
|
if (event.code === "Escape") {
|
||||||
|
// WebView 可先报告锁定解除再派发同一次 Esc。该按键只释放操作,
|
||||||
|
// keyup 即撤销抑制,下一次人工 Esc 仍交给 App 打开菜单。
|
||||||
|
if (escape.consume(down, capture.current !== null || attempt.current !== null, performance.now())) {
|
||||||
|
event.preventDefault(); event.stopPropagation();
|
||||||
|
if (down) stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isCapturing()) return;
|
||||||
|
const element = event.target as HTMLElement | null;
|
||||||
|
if (element?.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(element?.tagName ?? "") || event.isComposing) {
|
||||||
|
stop("输入焦点已改变,操作已停止"); return;
|
||||||
|
}
|
||||||
|
if (sampler.current.key(event.code, down)) event.preventDefault();
|
||||||
|
};
|
||||||
|
const down = (event: KeyboardEvent) => key(event, true);
|
||||||
|
const up = (event: KeyboardEvent) => key(event, false);
|
||||||
|
const mouse = (event: MouseEvent) => { if (isCapturing()) sampler.current.mouse(event.movementX, event.movementY); };
|
||||||
|
const button = (event: MouseEvent, down: boolean) => {
|
||||||
|
if (!isCapturing() || event.button !== 0) return;
|
||||||
|
sampler.current.trigger(down);
|
||||||
|
event.preventDefault();
|
||||||
|
};
|
||||||
|
const mouseDown = (event: MouseEvent) => button(event, true);
|
||||||
|
const mouseUp = (event: MouseEvent) => button(event, false);
|
||||||
|
const lock = () => {
|
||||||
|
if (document.pointerLockElement === target.current) startBackend();
|
||||||
|
else if (capture.current || attempt.current) { escape.pointerReleased(performance.now()); stop(); }
|
||||||
|
};
|
||||||
|
const lockError = () => { if (attempt.current) stop("鼠标锁定未成功,请再次点击开启"); };
|
||||||
|
const blur = () => { if (capture.current || attempt.current) stop("窗口失去焦点,操作已停止"); };
|
||||||
|
const hidden = () => { if (document.hidden) blur(); };
|
||||||
|
window.addEventListener("keydown", down, true);
|
||||||
|
window.addEventListener("keyup", up, true);
|
||||||
|
window.addEventListener("blur", blur);
|
||||||
|
document.addEventListener("mousemove", mouse);
|
||||||
|
document.addEventListener("mousedown", mouseDown);
|
||||||
|
document.addEventListener("mouseup", mouseUp);
|
||||||
|
document.addEventListener("pointerlockchange", lock);
|
||||||
|
document.addEventListener("pointerlockerror", lockError);
|
||||||
|
document.addEventListener("visibilitychange", hidden);
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
const session = capture.current;
|
||||||
|
const { snapshot, connected, blocked } = current.current;
|
||||||
|
if (!session) {
|
||||||
|
if (attempt.current && (blocked || !connected)) stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reason = blocked ? "菜单或设置已打开,操作已停止" : operatorGate(snapshot, connected, session.mode);
|
||||||
|
if (reason || !document.hasFocus() || document.pointerLockElement !== target.current) { stop(reason ?? "操作已停止"); return; }
|
||||||
|
const view = snapshot.operatorControl;
|
||||||
|
if (view.captureId === session.id && view.active) session.observed = true;
|
||||||
|
// 新会话返回后可能仍显示前一份 200ms 快照;两帧后必须看到本会话。
|
||||||
|
if ((!view.active || view.captureId !== session.id) && (session.observed || performance.now() - session.started > 400)) {
|
||||||
|
stop(view.reason || "后端已停止操作,请重新开启"); return;
|
||||||
|
}
|
||||||
|
const sampled = sampler.current.sample(performance.now(), sensitivityRef.current);
|
||||||
|
if (sampled.stalled) { stop("界面输入已超时,操作已停止,请重新开启"); return; }
|
||||||
|
session.sender.offer({ input: { captureId: session.id, sequence: ++session.sequence, active: true, ...sampled.axes }, at: performance.now() });
|
||||||
|
}, INPUT_INTERVAL_MS);
|
||||||
|
return () => {
|
||||||
|
mounted.current = false;
|
||||||
|
stop();
|
||||||
|
window.clearInterval(timer);
|
||||||
|
window.removeEventListener("keydown", down, true);
|
||||||
|
window.removeEventListener("keyup", up, true);
|
||||||
|
window.removeEventListener("blur", blur);
|
||||||
|
document.removeEventListener("mousemove", mouse);
|
||||||
|
document.removeEventListener("mousedown", mouseDown);
|
||||||
|
document.removeEventListener("mouseup", mouseUp);
|
||||||
|
document.removeEventListener("pointerlockchange", lock);
|
||||||
|
document.removeEventListener("pointerlockerror", lockError);
|
||||||
|
document.removeEventListener("visibilitychange", hidden);
|
||||||
|
};
|
||||||
|
}, [startBackend, stop]);
|
||||||
|
|
||||||
|
const setSensitivity = (value: number) => {
|
||||||
|
sensitivityRef.current = value;
|
||||||
|
setSensitivityState(value);
|
||||||
|
};
|
||||||
|
return { target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
||||||
|
}
|
||||||
@@ -6,12 +6,12 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export const BUILD = {
|
export const BUILD = {
|
||||||
version: "0.4.1",
|
version: "0.5.0",
|
||||||
major: 0,
|
major: 0,
|
||||||
minor: 4,
|
minor: 5,
|
||||||
patch: 1,
|
patch: 0,
|
||||||
/** git 提交数,单调递增。 */
|
/** git 提交数,单调递增。 */
|
||||||
build: 45,
|
build: 46,
|
||||||
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
||||||
protocol: 1,
|
protocol: 1,
|
||||||
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
||||||
|
|||||||
@@ -9,17 +9,21 @@ import { firmwareLabel, teamName, idText } from "../lib/format";
|
|||||||
import { useAppStore } from "../lib/store";
|
import { useAppStore } from "../lib/store";
|
||||||
import { BUILD } from "../lib/version";
|
import { BUILD } from "../lib/version";
|
||||||
import type { HudView, Snapshot } from "../lib/types";
|
import type { HudView, Snapshot } from "../lib/types";
|
||||||
|
import { useOperatorControl } from "../lib/use-operator-control";
|
||||||
|
import { OperatorControls } from "../components/OperatorControls";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
snapshot: Snapshot;
|
snapshot: Snapshot;
|
||||||
hud: HudView;
|
hud: HudView;
|
||||||
calibrating: boolean;
|
calibrating: boolean;
|
||||||
|
controlsBlocked: boolean;
|
||||||
onCalibrate: (dxFraction: number, dyFraction: number) => void;
|
onCalibrate: (dxFraction: number, dyFraction: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
export function TeamPage({ snapshot, hud, calibrating, controlsBlocked, onCalibrate }: Props) {
|
||||||
const [view, setView] = useState<ViewTransform>(IDENTITY_VIEW);
|
const [view, setView] = useState<ViewTransform>(IDENTITY_VIEW);
|
||||||
const { lastHit, connected } = useAppStore();
|
const { lastHit, connected } = useAppStore();
|
||||||
|
const control = useOperatorControl({ snapshot, connected, blocked: controlsBlocked || calibrating });
|
||||||
const camera = snapshot.config.cameraId;
|
const camera = snapshot.config.cameraId;
|
||||||
const stats = snapshot.stats.find(entry => entry.camera === camera);
|
const stats = snapshot.stats.find(entry => entry.camera === camera);
|
||||||
const boundCamera = snapshot.cameras.find(entry => entry.id === camera);
|
const boundCamera = snapshot.cameras.find(entry => entry.id === camera);
|
||||||
@@ -45,10 +49,10 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
|||||||
: !stats?.hasFrames ? "已连接,等待画面" : "";
|
: !stats?.hasFrames ? "已连接,等待画面" : "";
|
||||||
|
|
||||||
return <div className="op cockpit">
|
return <div className="op cockpit">
|
||||||
<div className="op__stage">
|
<div className="op__stage" ref={control.target}>
|
||||||
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
|
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
|
||||||
mirrored={snapshot.mirrored} mirroredVertical={snapshot.mirroredVertical} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
|
mirrored={snapshot.mirrored} mirroredVertical={snapshot.mirroredVertical} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
|
||||||
calibrating={calibrating} onCalibrate={calibrating ? onCalibrate : undefined} hit={pulse} hitFeedback={hud.hitFeedback} showZoom={hud.showZoom} showResetControl={false}>
|
calibrating={calibrating} inputCaptured={control.activeMode !== null || control.pending} onCalibrate={calibrating ? onCalibrate : undefined} hit={pulse} hitFeedback={hud.hitFeedback} showZoom={hud.showZoom} showResetControl={false}>
|
||||||
<div className="cockpit__overlay">
|
<div className="cockpit__overlay">
|
||||||
<div className="cockpit__health">
|
<div className="cockpit__health">
|
||||||
{hud.health.visible && mine && <div className="cockpit__health-side"><HealthBar health={mine} config={healthConfig} align="left" tag={healthTag(mine, snapshot.team)} /></div>}
|
{hud.health.visible && mine && <div className="cockpit__health-side"><HealthBar health={mine} config={healthConfig} align="left" tag={healthTag(mine, snapshot.team)} /></div>}
|
||||||
@@ -72,6 +76,7 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
|||||||
<MatchBanner outcome={mine?.outcome ?? null} mine={myName} theirs={theirName} detail={mine?.outcome === "defeat" && theirs?.hp != null ? `对手剩余 ${theirs.hp}` : mine?.outcome === "victory" && mine?.hp != null ? `剩余 ${mine.hp}` : undefined} />
|
<MatchBanner outcome={mine?.outcome ?? null} mine={myName} theirs={theirName} detail={mine?.outcome === "defeat" && theirs?.hp != null ? `对手剩余 ${theirs.hp}` : mine?.outcome === "victory" && mine?.hp != null ? `剩余 ${mine.hp}` : undefined} />
|
||||||
<HitFlash hit={lastHit} config={hud.hitFeedback} relevant={hitIsMine} />
|
<HitFlash hit={lastHit} config={hud.hitFeedback} relevant={hitIsMine} />
|
||||||
<TeamMatchCountdown snapshot={snapshot} />
|
<TeamMatchCountdown snapshot={snapshot} />
|
||||||
|
<OperatorControls control={control} snapshot={snapshot} connected={connected} blocked={controlsBlocked || calibrating} />
|
||||||
{boundCamera && !boundCamera.compatible && <div className="fwfault" role="alert"><span className="fwfault__tag label">协议不匹配</span><span className="fwfault__text">图传固件 {firmwareLabel(boundCamera)} · 协议 {boundCamera.protocol} / 客户端 {BUILD.protocol}。按 ESC 进入固件维护。</span></div>}
|
{boundCamera && !boundCamera.compatible && <div className="fwfault" role="alert"><span className="fwfault__tag label">协议不匹配</span><span className="fwfault__text">图传固件 {firmwareLabel(boundCamera)} · 协议 {boundCamera.protocol} / 客户端 {BUILD.protocol}。按 ESC 进入固件维护。</span></div>}
|
||||||
</VideoSurface>
|
</VideoSurface>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -106,3 +106,17 @@
|
|||||||
/* 异常与校准提示避开顶部血条及底部读数。 */
|
/* 异常与校准提示避开顶部血条及底部读数。 */
|
||||||
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
|
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
|
||||||
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
|
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
|
||||||
|
|
||||||
|
.operator-controls { position: absolute; z-index: 16; left: 50%; bottom: clamp(70px, 12vh, 120px); transform: translateX(-50%); width: min(580px, calc(100% - 48px)); padding: 14px 18px; color: var(--ink); background: #07100de8; border: 1px solid #74af8b55; font: 12px/1.5 var(--font-ui); text-align: center; }
|
||||||
|
.operator-controls__actions { display: flex; justify-content: center; gap: 12px; }
|
||||||
|
.operator-controls__sensitivity { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 12px; }
|
||||||
|
.operator-controls__sensitivity input { width: 120px; }
|
||||||
|
.operator-controls__sensitivity span { min-width: 88px; color: var(--ink-2); }
|
||||||
|
.operator-controls p { margin: 8px 0 0; color: var(--ink-2); }
|
||||||
|
.operator-controls .operator-controls__error { color: var(--warn); }
|
||||||
|
.operator-controls.is-active { width: auto; max-width: calc(100% - 48px); padding: 8px 14px; bottom: 58px; display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 16px; pointer-events: none; }
|
||||||
|
.operator-controls.is-active strong { color: var(--hud); white-space: nowrap; }
|
||||||
|
.operator-controls.is-active small { flex-basis: 100%; color: var(--ink-2); font-size: 10px; }
|
||||||
|
.operator-controls.is-debug { border-color: var(--warn-line); }
|
||||||
|
.operator-controls.is-debug strong { color: var(--warn); }
|
||||||
|
@media (max-height: 650px) { .operator-controls { bottom: 68px; padding: 10px 14px; } .operator-controls.is-active { bottom: 42px; } }
|
||||||
@@ -34,7 +34,7 @@ client/
|
|||||||
|
|
||||||
裁判端顶部的比赛控制条提供准备、跳过准备倒计时、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。准备期间点击“跳过准备倒计时”会进入“准备结束 · 等待裁判”;仍需点击“确认开赛”,经过短倒计时后才开始对局。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
裁判端顶部的比赛控制条提供准备、跳过准备倒计时、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。准备期间点击“跳过准备倒计时”会进入“准备结束 · 等待裁判”;仍需点击“确认开赛”,经过短倒计时后才开始对局。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
||||||
|
|
||||||
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时和装甲板扣血,胜负由裁判判定;计时不能控制机器人运动或代替判罚。
|
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时、装甲板扣血及本项目键鼠操控输出,胜负由裁判判定;下位机是否实际停机仍需验证,计时不能代替判罚。
|
||||||
|
|
||||||
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息、胜负结果和最近命中流水,回到等待准备。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
|
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息、胜负结果和最近命中流水,回到等待准备。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
|
||||||
|
|
||||||
@@ -56,6 +56,14 @@ client/
|
|||||||
|
|
||||||
固件维护页用简化线条绘制 C3 装甲板和 S3 图传板,配色沿用界面的冷蓝黑底与状态色。装甲板保留横向比例,S3 的 USB 接线指向右侧接口。图中的状态点表示 USB 识别,进度环表示当前维护任务,不推断实物 Wi-Fi、灯色或传感器状态。
|
固件维护页用简化线条绘制 C3 装甲板和 S3 图传板,配色沿用界面的冷蓝黑底与状态色。装甲板保留横向比例,S3 的 USB 接线指向右侧接口。图中的状态点表示 USB 识别,进度环表示当前维护任务,不推断实物 Wi-Fi、灯色或传感器状态。
|
||||||
|
|
||||||
|
### 选手键鼠操作
|
||||||
|
|
||||||
|
绑定在线 C3 后,可在画面下方开启操作:WASD 平移、鼠标滑动控制云台速度、左键按住发送发射状态。鼠标锁定后不受窗口边缘限制;按 ESC 退出,再按 ESC 打开菜单。比赛模式仅在比赛进行中有效;“赛前调试”单独开启,准备、待开赛或尚未连接裁判时可使用,开始倒计时会退出。失焦、断连、结束或输入超时均回零,恢复后需重新点击。
|
||||||
|
|
||||||
|
默认 1000 像素/秒映射到通道满幅 ±1000,支持本次会话的灵敏度调节。装甲板 TXD/GPIO21 以 115200 8N1 输出项目协议,软件日志改走 USB。客户端与 C3 均需更新,并在下位机接入解析器;当前没有串口操控应答,界面不表示电机已经响应。完整映射、串口帧与 C99 接收示例见[键鼠操作与用户 UART](../protocol/operator-control.md)。
|
||||||
|
|
||||||
|
`pnpm test:input` 检查速度换算、停止与最新输入队列;浏览器预览只模拟本地输入,页面标记“合成输入”,不会发送现场控制。
|
||||||
|
|
||||||
### 配色:墨黑蓝打底,只有一支红
|
### 配色:墨黑蓝打底,只有一支红
|
||||||
|
|
||||||
| 角色 | 值 | 用在哪 |
|
| 角色 | 值 | 用在哪 |
|
||||||
|
|||||||
@@ -32,12 +32,12 @@ armor/
|
|||||||
| 压电片 左 | GPIO3(ADC1_CH3) | |
|
| 压电片 左 | GPIO3(ADC1_CH3) | |
|
||||||
| 压电片 右 | GPIO1(ADC1_CH1) | |
|
| 压电片 右 | GPIO1(ADC1_CH1) | |
|
||||||
| BOOT 键 | GPIO9 | 低有效,内部上拉 |
|
| BOOT 键 | GPIO9 | 低有效,内部上拉 |
|
||||||
| 调试串口 UART0 TXD | GPIO21 | 115200 8N1,日志从这里出来(主控制台) |
|
| 用户 UART TXD | GPIO21 | UART1 路由,115200 8N1,输出键鼠操作协议 |
|
||||||
| 调试串口 UART0 RXD | GPIO20 | 目前空闲,留给以后的命令通道 |
|
| 用户 UART RXD | GPIO20 | UART1 输入,首版不解析反向命令或应答 |
|
||||||
|
|
||||||
引脚与参考实现一致(灯:前 10 / 后 5 / 左 6 / 右 7;压电:前 0 / 后 4 / 左 3 / 右 1)。UART0 作为主控制台,日志从丝印 RXD/TXD 对应的调试口输出。
|
引脚与参考实现一致(灯:前 10 / 后 5 / 左 6 / 右 7;压电:前 0 / 后 4 / 左 3 / 右 1)。丝印 TXD 接下位机 RX,两端共地,使用 3.3 V 逻辑电平。
|
||||||
|
|
||||||
`sdkconfig.defaults` 还将 USB Serial/JTAG 设为次控制台(`CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y`)。未连接 USB-TTL 时,也能从板上原生 USB 口读取应用日志;仅配置 UART0 则只能在原生 USB 上看到 ROM 启动信息。
|
`sdkconfig.defaults` 将 USB Serial/JTAG 设为主控制台,运行日志不再混入用户 UART。ROM 启动时 GPIO21 仍可能出现杂字节,接收端需帧同步和 CRC 校验。协议、时限和 C99 接收示例见[键鼠操作与用户 UART](../protocol/operator-control.md)。
|
||||||
|
|
||||||
## 规则
|
## 规则
|
||||||
|
|
||||||
@@ -229,9 +229,9 @@ C3 只有 2 个 TX 通道,四路灯带无法各占一个。因此只创建一
|
|||||||
|
|
||||||
40 kHz 采样时,一次击打可使连续几十个采样点超过阈值。`Armor::on_sample` 在规则层用冷却窗口合并为一次受击,主机测试 `repeat_samples_inside_the_cooldown_are_one_hit` 覆盖这一行为。
|
40 kHz 采样时,一次击打可使连续几十个采样点超过阈值。`Armor::on_sample` 在规则层用冷却窗口合并为一次受击,主机测试 `repeat_samples_inside_the_cooldown_are_one_hit` 覆盖这一行为。
|
||||||
|
|
||||||
### 4. 控制台放在 UART0
|
### 4. 控制台与用户 UART 分开
|
||||||
|
|
||||||
`sdkconfig.defaults` 显式设置 `CONFIG_ESP_CONSOLE_UART_DEFAULT=y`。C3 的 ROM 默认控制台为 UART0,引脚是 RXD=GPIO20 / TXD=GPIO21,与要求一致。若改为 USB Serial/JTAG 输出,将这一行换成 `CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG`。
|
`sdkconfig.defaults` 显式设置 `CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y`,应用使用 UART1 路由到 RXD=GPIO20 / TXD=GPIO21 输出操作帧。独立线程按 5 ms 周期有界收包、20 ms 周期输出,避免 ADC 最长 200 ms 等待拖住操控租约。FreeRTOS tick 为 1000 Hz;实际周期抖动仍需实测。旧的队伍、许可和复位命令经有界队列转给受击主循环,并保留原接收时间,防止排队后延长旧许可。
|
||||||
|
|
||||||
### 5. 应用分区给 2 MB
|
### 5. 应用分区给 2 MB
|
||||||
|
|
||||||
@@ -269,7 +269,7 @@ status: hp=0 hits=37 dead=true plates[front=37 rear=0 left=0 right=0]
|
|||||||
|
|
||||||
### 9. USB 控制台看不到复位后的头两秒
|
### 9. USB 控制台看不到复位后的头两秒
|
||||||
|
|
||||||
UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也能读取日志。但复位时 USB 会重新枚举,**复位后最初约 1–2 秒的日志会丢**,实测曾漏掉启动横幅。需要完整启动日志时,通过 UART0 连接 USB-TTL。
|
原生 USB Serial/JTAG 现在是软件日志主控制台。早期采用 USB 次控制台时,实测复位重新枚举可能丢失最初约 1–2 秒日志;切换后的启动可见范围仍需实测。用户 TXD 现在输出二进制操控帧,不再作为应用日志口。
|
||||||
|
|
||||||
## 与早期 C 版设计的差异
|
## 与早期 C 版设计的差异
|
||||||
|
|
||||||
@@ -278,7 +278,7 @@ UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也
|
|||||||
| | 参考实现 | 这里 | 为什么 |
|
| | 参考实现 | 这里 | 为什么 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 主从链路 | ESP-NOW 配对,两块板对拷 | 无:三块从板只是直接接线的灯与传感器 | 按实际硬件(只有主板一颗 MCU) |
|
| 主从链路 | ESP-NOW 配对,两块板对拷 | 无:三块从板只是直接接线的灯与传感器 | 按实际硬件(只有主板一颗 MCU) |
|
||||||
| DBUS 透传 | UART0 收发 10 字节 DBUS,USB CDC 打 CSV | 不做 | 这套硬件没有 DBUS 需求;UART0 让给日志 |
|
| 串口操作 | 固定 10 字节盲透传,未定义通道字段 | 项目自定义 20 字节 UART 帧,四轴、使能及发射,CRC 校验 | 明确通道含义与失联行为,不假定兼容 DBUS |
|
||||||
| 受击变暗 | 四条灯带一起全黑 50 ms | 只暗被打的那一路 | 各面灯带独立反馈受击 |
|
| 受击变暗 | 四条灯带一起全黑 50 ms | 只暗被打的那一路 | 各面灯带独立反馈受击 |
|
||||||
| 冷却窗口 | 全局 50 ms | 每板独立 50 ms | 一路受击不应抑制其他板位的检测 |
|
| 冷却窗口 | 全局 50 ms | 每板独立 50 ms | 一路受击不应抑制其他板位的检测 |
|
||||||
| 灯带刷新 | 每 10 ms 无条件刷四遍 | 只在内容变化时刷 + 每秒强制全刷 | 四路独立控制后,省掉四轮 RMT 开销 |
|
| 灯带刷新 | 每 10 ms 无条件刷四遍 | 只在内容变化时刷 + 每秒强制全刷 | 四路独立控制后,省掉四轮 RMT 开销 |
|
||||||
@@ -291,7 +291,7 @@ UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也
|
|||||||
|
|
||||||
- **另外三路(后/左/右)的压电片与灯带还没接**(2026-10-14 实机只有前一路)。
|
- **另外三路(后/左/右)的压电片与灯带还没接**(2026-10-14 实机只有前一路)。
|
||||||
代码支持四路,接线后无需修改;四路同时受击与各路独立变暗仍未完成实板验证。
|
代码支持四路,接线后无需修改;四路同时受击与各路独立变暗仍未完成实板验证。
|
||||||
- **UART0 RX(GPIO20)上的命令通道**:日志输出已可用;反向的 `status` / `reset` 命令尚未接入,当前通过长按 BOOT 复位。
|
- **用户 UART RX(GPIO20)上的反向命令/应答**:当前只输出操控帧,未解析下位机状态。血量复位使用 BOOT 或裁判 UDP 请求。
|
||||||
- **从板加 MCU 的方案**:如果以后从板也装单片机(走 UART 或无线回传),
|
- **从板加 MCU 的方案**:如果以后从板也装单片机(走 UART 或无线回传),
|
||||||
`armor-protocol` 里已经预留了板位枚举与上报格式,加一个 `slave` bin 即可。
|
`armor-protocol` 里已经预留了板位枚举与上报格式,加一个 `slave` bin 即可。
|
||||||
- **双击 / 多击**:`Button` 只实现短按与长按,参考实现里未使用的 OneButton 功能没有移植。
|
- **双击 / 多击**:`Button` 只实现短按与长按,参考实现里未使用的 OneButton 功能没有移植。
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
- [图传板硬件](hardware/camera.md):引脚、PSRAM、分区、故障 Flash 与驱动补丁。
|
- [图传板硬件](hardware/camera.md):引脚、PSRAM、分区、故障 Flash 与驱动补丁。
|
||||||
- [装甲板](hardware/armor.md):接线、受击规则、上报、构建与实现要点。
|
- [装甲板](hardware/armor.md):接线、受击规则、上报、构建与实现要点。
|
||||||
- [UDP 协议](protocol/udp.md):线路格式、版本通告、帧重组与拒收条件。
|
- [UDP 协议](protocol/udp.md):线路格式、版本通告、帧重组与拒收条件。
|
||||||
|
- [键鼠操作与用户 UART](protocol/operator-control.md):FPS 输入映射、赛前调试、串口帧、失联回零及接收端示例。
|
||||||
|
|
||||||
## 测试与排查记录
|
## 测试与排查记录
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 选手键鼠与装甲板用户 UART
|
||||||
|
|
||||||
|
本功能将选手端的键鼠状态经 UDP 定向送到绑定的 C3,再由 C3 的用户 UART 输出给下位机。协议由本项目定义,不兼容 DJI DBUS/SBUS。客户端与 C3 均需更新;图传 S3 无需更新。
|
||||||
|
|
||||||
|
## 使用与通道
|
||||||
|
|
||||||
|
选手端绑定在线装甲板后,点击画面下方的“开启比赛操作”锁定鼠标。比赛模式仅在裁判计时连接有效、比赛进行中且本车血量大于零时发送使能状态。“开启赛前调试”需单独点击,可在未开始、准备和等待开赛阶段使用;未连接过裁判时也可调试,曾连接后失联则不可调试。开始倒计时、暂停和结束会退出操作,恢复阶段后需再次点击。调试状态不保存到配置。
|
||||||
|
|
||||||
|
| 输入 | UART 通道 | 正方向 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| W / S | 0 `forward` | 前 / 后 |
|
||||||
|
| D / A | 1 `strafe` | 右 / 左 |
|
||||||
|
| 鼠标水平滑动 | 2 `yaw` | 向右为正 |
|
||||||
|
| 鼠标垂直滑动 | 3 `pitch` | 向上为正 |
|
||||||
|
| 鼠标左键按住 | `fire` | 按住为 1,松开为 0 |
|
||||||
|
|
||||||
|
四通道均为整数 `-1000..1000`,零表示停止,数值是下位机最大速度的比例,不是角度或位置。WASD 对向抵消,斜向两轴各约 707,避免斜向速度更高。发射位表示持续按键状态;接收端按自身机构实现连续或单发规则。
|
||||||
|
|
||||||
|
每个约 20 ms 窗口累计鼠标相对位移,除以实际经过时间得到像素/秒;默认 1000 像素/秒对应满幅。公式为 `clamp(位移 / dt秒 × 灵敏度, -1000, 1000)`,再使用 `alpha=1-exp(-dt毫秒/25)` 的一阶低通,减少采样抖动。无位移的下一窗口立即回零,不保留滤波尾迹。灵敏度可在本次会话内调为 0.25–4 倍。该比例基于系统提供的鼠标相对位移,不是经过物理标定的厘米/秒;鼠标 DPI、系统设置会影响手感。画面镜像、缩放和准星偏移不改变控制方向或增益。
|
||||||
|
|
||||||
|
鼠标锁定通过 [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) 获取相对移动,指针不会因碰到窗口边缘停止。按 ESC 退出操作,再按 ESC 打开原操作菜单。窗口失焦、页面隐藏、菜单/设置/维护打开、输入间隔超过 100 ms 或本地连接断开都会清空输入并请求禁能。界面表示客户端的发送状态;当前没有 C3/下位机操控应答,不能据此判断电机已经响应。实机没有响应或接收端重启后,先退出再重新开启。
|
||||||
|
|
||||||
|
## 接线与 UART 帧
|
||||||
|
|
||||||
|
原理图丝印 TXD 对应 C3 GPIO21,RXD 对应 GPIO20。应用使用 UART1 经 GPIO Matrix 路由到这两个引脚;设置为 **115200、8N1、无流控、3.3 V 逻辑电平**。C3 TXD 接下位机 RX,两端共地。RXD 已配置为输入,首版不解析反向命令或应答,可以不接下位机 TX。不要按原理图模块的物理脚号 11/12 当作 GPIO 号。
|
||||||
|
|
||||||
|
软件日志改到原生 USB Serial/JTAG 主控制台。C3 ROM 启动时仍可能从 GPIO21 输出杂字节;接收端必须做帧同步与 CRC 校验,启动默认禁能。本功能没有更改 eFuse。UART 路由依据 [ESP-IDF 6.0.1 UART 文档](https://docs.espressif.com/projects/esp-idf/en/v6.0.1/esp32c3/api-reference/peripherals/uart.html)。
|
||||||
|
|
||||||
|
每帧固定 **20 字节**,多字节字段小端:
|
||||||
|
|
||||||
|
| 偏移 | 长度 | 字段 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0 | 2 | 帧头 `A5 5A` |
|
||||||
|
| 2 | 1 | UART 协议版本,固定 1 |
|
||||||
|
| 3 | 1 | 帧长,固定 20(`0x14`) |
|
||||||
|
| 4 | 4 | 序号 `u32`,每帧递增,可自然回绕 |
|
||||||
|
| 8 | 1 | 标志:bit0 使能、bit1 调试、bit2 发射;其余为 0 |
|
||||||
|
| 9 | 1 | 保留,必须为 0 |
|
||||||
|
| 10 | 2 | `forward`,`i16` |
|
||||||
|
| 12 | 2 | `strafe`,`i16` |
|
||||||
|
| 14 | 2 | `yaw`,`i16` |
|
||||||
|
| 16 | 2 | `pitch`,`i16` |
|
||||||
|
| 18 | 2 | CRC16-CCITT-FALSE,覆盖字节 0–17,结果小端 |
|
||||||
|
|
||||||
|
CRC 参数为 poly=`0x1021`、init=`0xFFFF`、refin/refout=false、xorout=0。禁能帧的所有标志、通道和发射均为零。合法帧示例(比赛模式、使能及发射,序号 `0x12345678`,四轴 `[1000,-1000,200,-200]`):
|
||||||
|
|
||||||
|
```text
|
||||||
|
A5 5A 01 14 78 56 34 12 05 00 E8 03 18 FC C8 00 38 FF 78 60
|
||||||
|
```
|
||||||
|
|
||||||
|
## UDP 上游与租约
|
||||||
|
|
||||||
|
`OperatorControl` 使用既有线路版本 1、27 字节共用头,消息类型 **11**,`sender_id=0`,其余头部业务字段为零。数据报共 58 字节,发向绑定主板上报血量的源 IP 和源端口,不广播、不选取发现列表中的其他板。
|
||||||
|
|
||||||
|
| 负载偏移 | 长度 | 字段 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0 | 4 | `board_id`,非零 |
|
||||||
|
| 4 | 8 | `session`,每次显式开启生成的新非零会话 |
|
||||||
|
| 12 | 8 | `sequence`,非零、会话内递增 |
|
||||||
|
| 20 | 1 | `mode`:0 比赛,1 调试 |
|
||||||
|
| 21 | 1 | `enabled`:0/1 |
|
||||||
|
| 22 | 8 | 四个 `i16` 通道,顺序同 UART |
|
||||||
|
| 30 | 1 | `fire`:0/1 |
|
||||||
|
|
||||||
|
禁能数据报必须四通道和发射全零。C3 校验目标板号、长度、版本、字段范围,当前操控会话有效时拒绝其他来源 IP 或 session 抢占;同会话仅接受递增序号。禁能、模式变化、租约过期或门控关闭会结束会话,迟到输入不能重开,需选手显式再次开启。固件保留最近 8 个结束会话用于拒绝常见迟到包;这些约束与 CRC 均不提供发送者身份认证。
|
||||||
|
|
||||||
|
客户端 Rust 核心再次检查角色、显式绑定、四路新鲜血量、阶段和窗口焦点。前端最多保留一个在途 IPC 和一个最新状态,Rust 每 20 ms 定向发送最新状态,输入 150 ms 未更新则结束捕获并重发 5 个禁能数据报。C3 每 5 ms 有界接收,每 20 ms 输出 UART,操控输入 150 ms 未更新则禁能。丢失客户端输入后,两层期限可能叠加;这些数值是软件配置,不能当作实测最大停机时间。
|
||||||
|
|
||||||
|
C3 的接收/UART 线程不等待 ADC 采样。正常模式还要求裁判扣血许可有效,调试遇到比赛许可即结束;完整阶段限制由客户端 Rust 核心执行,因为现有扣血许可不区分未开始与暂停。血量归零、Wi-Fi 断开、BOOT 或远程复位也结束捕获,满血或重连不会自动恢复运动。
|
||||||
|
|
||||||
|
## 接收端示例与验证
|
||||||
|
|
||||||
|
[C99 接收示例](../../armor/examples/uart_receiver/README.md) 可直接接收分段字节,跳过 ROM 杂字节、错误长度与坏 CRC,拒绝重复或旧序号;不依赖平台 HAL,也不直接驱动电机。控制循环应持续调用 `rmic_receiver_poll`,100 ms 没有有效新帧则使用禁能、全零、停止发射的返回值,不能在无数据时继续使用上一次输出。
|
||||||
|
|
||||||
|
接收器启动或超时后先等完整禁能帧再接受使能帧,允许 C3 重启后序号重新开始。C3 启动先发禁能帧,空闲也持续输出禁能帧;如果下位机在操控中单独重启,需选手先退出再开启,使接收器观察到禁能帧。
|
||||||
|
|
||||||
|
自动检查:`client/` 下 `pnpm test:input`;`client/core` 主机操控状态测试;共享协议及 `armor/armor-protocol` 主机测试;示例目录的 C99 编译测试。鼠标换算覆盖事件频率、采样时间、限幅、停止回零和输入队列;Rust/C 使用相同黄金帧验证字节互通。
|
||||||
|
|
||||||
|
实机仍需验证:UART 波形与电平、正常/调试各阶段、WASD/鼠标方向、发射松手、拔网线/断 Wi-Fi、切出窗口、客户端卡顿、C3/下位机单独重启、血量归零和复位。编译及合成预览不代表已经完成上述硬件验证。
|
||||||
@@ -77,6 +77,9 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
|
|||||||
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
||||||
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
||||||
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
|
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
|
||||||
|
| 11 `OperatorControl` | 选手端 → 绑定的装甲板 | 四轴速度和发射状态,定向发送到主板上报端口 |
|
||||||
|
|
||||||
|
类型 11 保持线路版本 1,不改变旧消息布局;旧 C3 会忽略该类型,使用操控功能需更新 C3。载荷、租约及下游 UART 帧见[键鼠操作与用户 UART](operator-control.md)。
|
||||||
|
|
||||||
### 比赛计时快照(类型 7)
|
### 比赛计时快照(类型 7)
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"version": "0.4.1",
|
"version": "0.5.0",
|
||||||
"major": 0,
|
"major": 0,
|
||||||
"minor": 4,
|
"minor": 5,
|
||||||
"patch": 1,
|
"patch": 0,
|
||||||
"build": 45,
|
"build": 46,
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"date": "2026-10-31",
|
"date": "2026-10-31",
|
||||||
"baseline": "v0.4.1",
|
"baseline": "v0.5.0",
|
||||||
"commits": 0,
|
"commits": 0,
|
||||||
"groups": {}
|
"groups": {}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,14 @@
|
|||||||
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
|
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
|
||||||
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
|
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
|
||||||
|
|
||||||
|
## v0.5.0 — 2026-10-31
|
||||||
|
|
||||||
|
1 个提交
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **control** · 添加选手 FPS 键鼠操作与 C3 用户 UART 输出
|
||||||
|
|
||||||
## v0.4.1 — 2026-10-31
|
## v0.4.1 — 2026-10-31
|
||||||
|
|
||||||
1 个提交
|
1 个提交
|
||||||
|
|||||||
+5
-5
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"version": "0.4.1",
|
"version": "0.5.0",
|
||||||
"major": 0,
|
"major": 0,
|
||||||
"minor": 4,
|
"minor": 5,
|
||||||
"patch": 1,
|
"patch": 0,
|
||||||
"build": 45,
|
"build": 46,
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"date": "2026-10-31",
|
"date": "2026-10-31",
|
||||||
"baseline": "v0.4.1",
|
"baseline": "v0.5.0",
|
||||||
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
|
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
|
||||||
}
|
}
|
||||||
@@ -56,6 +56,8 @@ mod armor_damage;
|
|||||||
pub use armor_damage::ArmorDamageControl;
|
pub use armor_damage::ArmorDamageControl;
|
||||||
mod armor_reset;
|
mod armor_reset;
|
||||||
pub use armor_reset::ArmorReset;
|
pub use armor_reset::ArmorReset;
|
||||||
|
mod operator_control;
|
||||||
|
pub use operator_control::OperatorControl;
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 端口
|
// 端口
|
||||||
@@ -132,6 +134,8 @@ pub enum MsgType {
|
|||||||
ArmorReset = 9,
|
ArmorReset = 9,
|
||||||
/// 裁判广播的锁定胜负及结束计时,自包含快照(5601)。
|
/// 裁判广播的锁定胜负及结束计时,自包含快照(5601)。
|
||||||
MatchResult = 10,
|
MatchResult = 10,
|
||||||
|
/// 选手端定向发送给已绑定装甲板的四轴速度与发射状态。
|
||||||
|
OperatorControl = 11,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MsgType {
|
impl MsgType {
|
||||||
@@ -148,6 +152,7 @@ impl MsgType {
|
|||||||
8 => MsgType::ArmorDamageControl,
|
8 => MsgType::ArmorDamageControl,
|
||||||
9 => MsgType::ArmorReset,
|
9 => MsgType::ArmorReset,
|
||||||
10 => MsgType::MatchResult,
|
10 => MsgType::MatchResult,
|
||||||
|
11 => MsgType::OperatorControl,
|
||||||
_ => return None,
|
_ => return None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN, PROTOCOL_VERSION};
|
||||||
|
|
||||||
|
/// 选手端定向发送到已绑定 C3 的操作量;四轴顺序为前后、左右、水平、俯仰。
|
||||||
|
/// 值域 -1000..=1000,表示速度比例,不表示位置或 PWM 脉宽。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct OperatorControl {
|
||||||
|
pub board_id: u32,
|
||||||
|
/// 每次显式开启操控都必须生成新会话,失联后不能沿用。
|
||||||
|
pub session: u64,
|
||||||
|
pub sequence: u64,
|
||||||
|
/// 0:比赛;1:未开赛调试。
|
||||||
|
pub mode: u8,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub channels: [i16; 4],
|
||||||
|
pub fire: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperatorControl {
|
||||||
|
pub fn valid(&self) -> bool {
|
||||||
|
self.board_id != 0
|
||||||
|
&& self.session != 0
|
||||||
|
&& self.sequence != 0
|
||||||
|
&& self.mode <= 1
|
||||||
|
&& self.channels.iter().all(|v| (-1000..=1000).contains(v))
|
||||||
|
&& (self.enabled || (self.channels == [0; 4] && !self.fire))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode(&self) -> Option<Vec<u8>> {
|
||||||
|
if !self.valid() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(HEADER_LEN + 31);
|
||||||
|
encode_header_into(
|
||||||
|
&Header {
|
||||||
|
msg_type: MsgType::OperatorControl,
|
||||||
|
version: PROTOCOL_VERSION,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&mut out,
|
||||||
|
);
|
||||||
|
out.extend(self.board_id.to_le_bytes());
|
||||||
|
out.extend(self.session.to_le_bytes());
|
||||||
|
out.extend(self.sequence.to_le_bytes());
|
||||||
|
out.push(self.mode);
|
||||||
|
out.push(u8::from(self.enabled));
|
||||||
|
for channel in self.channels {
|
||||||
|
out.extend(channel.to_le_bytes());
|
||||||
|
}
|
||||||
|
out.push(u8::from(self.fire));
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||||
|
let h = decode_header(bytes)?;
|
||||||
|
if h.msg_type != MsgType::OperatorControl
|
||||||
|
|| bytes.len() != HEADER_LEN + 31
|
||||||
|
// 本消息不使用视频头字段;非零值不能作为扩展偷偷混入。
|
||||||
|
|| bytes[7..HEADER_LEN].iter().any(|&b| b != 0)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let p = &bytes[HEADER_LEN..];
|
||||||
|
let value = Self {
|
||||||
|
board_id: u32::from_le_bytes(p[0..4].try_into().ok()?),
|
||||||
|
session: u64::from_le_bytes(p[4..12].try_into().ok()?),
|
||||||
|
sequence: u64::from_le_bytes(p[12..20].try_into().ok()?),
|
||||||
|
mode: p[20],
|
||||||
|
enabled: match p[21] {
|
||||||
|
0 => false,
|
||||||
|
1 => true,
|
||||||
|
_ => return None,
|
||||||
|
},
|
||||||
|
channels: [22, 24, 26, 28].map(|at| i16::from_le_bytes([p[at], p[at + 1]])),
|
||||||
|
fire: match p[30] {
|
||||||
|
0 => false,
|
||||||
|
1 => true,
|
||||||
|
_ => return None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
value.valid().then_some(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn packet() -> OperatorControl {
|
||||||
|
OperatorControl {
|
||||||
|
board_id: 0x12345678,
|
||||||
|
session: 0x1234567812345678,
|
||||||
|
sequence: 42,
|
||||||
|
mode: 1,
|
||||||
|
enabled: true,
|
||||||
|
channels: [-1000, 1000, -1, 0],
|
||||||
|
fire: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_layout_roundtrips_both_modes_and_neutral() {
|
||||||
|
for mode in 0..=1 {
|
||||||
|
for enabled in [false, true] {
|
||||||
|
let mut p = packet();
|
||||||
|
p.mode = mode;
|
||||||
|
p.enabled = enabled;
|
||||||
|
if !enabled {
|
||||||
|
p.channels = [0; 4];
|
||||||
|
p.fire = false;
|
||||||
|
}
|
||||||
|
let bytes = p.encode().unwrap();
|
||||||
|
assert_eq!(bytes.len(), HEADER_LEN + 31);
|
||||||
|
assert_eq!(bytes[4], 11);
|
||||||
|
assert_eq!(OperatorControl::decode(&bytes), Some(p));
|
||||||
|
assert!(crate::ArmorControl::decode(&bytes).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let bytes = packet().encode().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
&bytes[HEADER_LEN..HEADER_LEN + 4],
|
||||||
|
&[0x78, 0x56, 0x34, 0x12]
|
||||||
|
);
|
||||||
|
assert_eq!(&bytes[HEADER_LEN + 22..HEADER_LEN + 24], &[0x18, 0xfc]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_truncation_extensions_reserved_fields_and_invalid_values() {
|
||||||
|
let bytes = packet().encode().unwrap();
|
||||||
|
for n in 0..bytes.len() {
|
||||||
|
assert!(OperatorControl::decode(&bytes[..n]).is_none());
|
||||||
|
}
|
||||||
|
let mut extra = bytes.clone();
|
||||||
|
extra.push(0);
|
||||||
|
assert!(OperatorControl::decode(&extra).is_none());
|
||||||
|
for (offset, value) in [
|
||||||
|
(0, 0),
|
||||||
|
(4, 10),
|
||||||
|
(5, 2),
|
||||||
|
(7, 1),
|
||||||
|
(11, 1),
|
||||||
|
(HEADER_LEN + 20, 2),
|
||||||
|
(HEADER_LEN + 21, 2),
|
||||||
|
(HEADER_LEN + 30, 2),
|
||||||
|
] {
|
||||||
|
let mut bad = bytes.clone();
|
||||||
|
bad[offset] = value;
|
||||||
|
assert!(OperatorControl::decode(&bad).is_none(), "offset {offset}");
|
||||||
|
}
|
||||||
|
for channel in [-1001, 1001, i16::MIN, i16::MAX] {
|
||||||
|
let mut p = packet();
|
||||||
|
p.channels[0] = channel;
|
||||||
|
assert!(p.encode().is_none());
|
||||||
|
let mut bad = bytes.clone();
|
||||||
|
bad[HEADER_LEN + 22..HEADER_LEN + 24].copy_from_slice(&channel.to_le_bytes());
|
||||||
|
assert!(OperatorControl::decode(&bad).is_none());
|
||||||
|
}
|
||||||
|
for field in 0..3 {
|
||||||
|
let mut p = packet();
|
||||||
|
match field {
|
||||||
|
0 => p.board_id = 0,
|
||||||
|
1 => p.session = 0,
|
||||||
|
_ => p.sequence = 0,
|
||||||
|
}
|
||||||
|
assert!(p.encode().is_none());
|
||||||
|
}
|
||||||
|
let mut p = packet();
|
||||||
|
p.enabled = false;
|
||||||
|
assert!(p.encode().is_none());
|
||||||
|
p.channels = [0; 4];
|
||||||
|
assert!(p.encode().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,7 @@ MSG_MATCH_STATE = 7
|
|||||||
MSG_ARMOR_DAMAGE_CONTROL = 8
|
MSG_ARMOR_DAMAGE_CONTROL = 8
|
||||||
MSG_ARMOR_RESET = 9
|
MSG_ARMOR_RESET = 9
|
||||||
MSG_MATCH_RESULT = 10
|
MSG_MATCH_RESULT = 10
|
||||||
|
MSG_OPERATOR_CONTROL = 11
|
||||||
|
|
||||||
TYPE_NAMES = {
|
TYPE_NAMES = {
|
||||||
MSG_VIDEO: "video",
|
MSG_VIDEO: "video",
|
||||||
@@ -51,6 +52,7 @@ TYPE_NAMES = {
|
|||||||
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
||||||
MSG_ARMOR_RESET: "armor-reset",
|
MSG_ARMOR_RESET: "armor-reset",
|
||||||
MSG_MATCH_RESULT: "match-result",
|
MSG_MATCH_RESULT: "match-result",
|
||||||
|
MSG_OPERATOR_CONTROL: "operator-control",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user