feat(control): 添加选手 FPS 键鼠操作与 C3 用户 UART 输出
构建客户端 / 检查(类型 + 单元测试) (push) Canceled after 0s
构建客户端 / Linux x64(deb + AppImage) (push) Canceled after 0s
构建客户端 / Windows x64(NSIS 安装包) (push) Canceled after 0s
构建客户端 / macOS 通用(.app + .dmg) (push) Canceled after 0s

This commit is contained in:
sloray committed 2026-10-31 18:34:30 +08:00
1 parent aea1cf60ae
commit 38410bacd4
43 files changed
+2389 -77

No files matched your search

+3
View File
@@ -38,6 +38,9 @@ use std::time::Duration;
pub use protocol::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
pub use protocol::{ArmorControl, ArmorDamageControl, ArmorReset, ARMOR_UNASSIGNED};
pub use protocol::OperatorControl;
mod operator;
pub use operator::{OperatorLink, UartControlFrame, OPERATOR_LEASE_MS, SERIAL_FRAME_LEN};
pub const CLIENT_LEASE: Duration = Duration::from_secs(2);
pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
+336
View File
@@ -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());
}
}