Compare commits
6
Commits
235fb1c73b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a8f7bcf90
|
||
|
|
1b1fa0f35b
|
||
|
|
38410bacd4
|
||
|
|
aea1cf60ae
|
||
|
|
dac763eb3e
|
||
|
|
338efa5c2e
|
No files matched your search
@@ -103,9 +103,10 @@
|
||||
# vt/ 和 armor/ 各自固定 ESP 工具链;client/ 固定 stable。
|
||||
# vt/protocol/ 的主机测试必须显式 +stable,并清空继承自 vt/ 的 build-std。
|
||||
#
|
||||
# ── 没做的事 ────────────────────────────────────────────────────────────────
|
||||
# 不签名、不公证:Windows 的 exe 与 macOS 的 app 在别人机器上会被 SmartScreen /
|
||||
# Gatekeeper 拦一次(右键打开即可)。要做的话给 macOS 那几个 job 加
|
||||
# ── 签名与发布 ──────────────────────────────────────────────────────────────
|
||||
# Windows 发布默认创建或复用 runner 用户的自签名证书,可另设 CA 证书指纹。
|
||||
# PR 仅生成未签名预览包。自签名不建立 SmartScreen 发布者信誉。
|
||||
# macOS 仍不签名、不公证,可能被 Gatekeeper 拦截。要做的话给 macOS 那几个 job 加
|
||||
# APPLE_CERTIFICATE / APPLE_SIGNING_IDENTITY / APPLE_ID / APPLE_PASSWORD /
|
||||
# APPLE_TEAM_ID(tauri 认这些环境变量,构建步骤不用改)。也没有自动发 Release:
|
||||
# 要发的话在最后加一个下载全部 artifact 再创建 release 的 job。
|
||||
@@ -501,9 +502,23 @@ jobs:
|
||||
# nsis 是纯安装包,不需要 WiX;tauri 会自己把 NSIS 下到用户缓存里(这个缓存
|
||||
# 也跟着 LOCALAPPDATA 走,见上面 job env),所以这台 runner 要能访问 GitHub
|
||||
# (离线环境改成 --bundles msi 也一样要下 WiX)。
|
||||
- name: 打包(tauri build)
|
||||
- name: Windows 签名配置回归
|
||||
working-directory: client
|
||||
run: pnpm tauri build --target ${{ env.TARGET }} --bundles nsis
|
||||
shell: pwsh
|
||||
run: ./scripts/test-windows-signing.ps1
|
||||
|
||||
- name: 打包并检查 Authenticode
|
||||
working-directory: client
|
||||
shell: pwsh
|
||||
env:
|
||||
RMIC_WINDOWS_CERT_THUMBPRINT: ${{ vars.WINDOWS_CODE_SIGNING_THUMBPRINT }}
|
||||
RMIC_EVENT_NAME: ${{ github.event_name }}
|
||||
run: |
|
||||
if ($env:RMIC_EVENT_NAME -eq 'pull_request') {
|
||||
./scripts/build-windows-release.ps1 -CertificateThumbprint '' -AllowUnsigned
|
||||
} else {
|
||||
./scripts/build-windows-release.ps1
|
||||
}
|
||||
|
||||
- name: 检查安装包与主程序完整性标签
|
||||
working-directory: client
|
||||
@@ -522,7 +537,10 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
path: |
|
||||
client/src-tauri/target/${{ env.TARGET }}/release/bundle/nsis/*.exe
|
||||
target/releases/**/RMIC-2026*setup.exe
|
||||
target/releases/**/*.exe.sha256
|
||||
target/releases/**/windows-signature-verification.json
|
||||
target/releases/**/RMIC-2026-codesign.cer
|
||||
|
||||
# ───────────────────────────────────────────────────────────────────────────
|
||||
# macOS 通用包:.app + .dmg
|
||||
|
||||
@@ -73,9 +73,10 @@ flowchart LR
|
||||
| 模块 | 已有功能 | 使用条件与边界 |
|
||||
| :--- | :--- | :--- |
|
||||
| 图传固件 | VGA 彩色 JPEG、UDP 分片、多端订阅、Wi-Fi 重连、过期帧放弃 | 当前记录约 30 fps;不同网络、裁判系统与画质下需复测[^performance] |
|
||||
| 用户端 | 全画面 HUD、双方血量、图传与装甲板状态、接收帧率、ESC 设置菜单 | 先绑定图传板与装甲板;改绑、切换模式和退出受密码限制 |
|
||||
| 用户端 | 全画面 HUD、双方血量、图传与装甲板状态、键鼠操作与赛前调试、ESC 设置菜单 | 先绑定图传板与装甲板;改绑、切换模式和退出受密码限制 |
|
||||
| 裁判端 | 双路画面、队名编辑、装甲板发现、槽位分配、截图、录制与回放 | 录制需要 ffmpeg;图传槽位可手动指定 |
|
||||
| 装甲板 | 四路受击检测与灯带、整车血量、UDP 上报 | 初始 100 血,每次受击扣 3 点;通用固件,队伍由客户端选择,断网黄闪、等待客户端绿闪 |
|
||||
| 用户 UART | WASD 平移、鼠标云台速度、左键发射,C3 TX21 输出 | [115200 8N1、四轴协议与接收示例](docs/protocol/operator-control.md);需更新 C3 并接入下位机,实机响应待验证 |
|
||||
| 固件维护 | 图传板 USB 更新、装甲板本机编译与安装、设备/队伍核对、备份和写后回读 | S3 App 写入与回读已有实机记录;S3 完整切换、C3 客户端安装与恢复尚未实机验证 |
|
||||
|
||||
发送端在限定时间内提交当前帧,超时后转向新帧;本地视频通道与 WebView 会放弃滞留超过 100 ms 的旧帧。这个期限只约束本机积压,**不代表相机到屏幕的端到端延迟**。
|
||||
@@ -119,10 +120,10 @@ pnpm app --target x86_64-pc-windows-msvc -- --locked --config 'unstable.build-st
|
||||
生成 NSIS 安装包:
|
||||
|
||||
```powershell
|
||||
pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci -- --locked --config 'unstable.build-std=[]'
|
||||
pnpm bundle:windows
|
||||
```
|
||||
|
||||
安装包位于 `client/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/`。显示名为 **RMIC::2026**,Windows 可执行文件和安装包使用 **RMIC-2026**。
|
||||
交付包位于 `target/releases/v<版本>+<构建号>/`,默认创建或复用本机自签名代码证书,附带公钥证书和签名校验报告;自签名不保证免除 SmartScreen 提示,配置见[Windows 构建说明](docs/client/client.md#windows-x64-构建)。显示名为 **RMIC::2026**,Windows 可执行文件和安装包使用 **RMIC-2026**。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
# CONFIG_IDF_TARGET 必须显式写出来:本机装的是通用 ESP-IDF,默认目标是 ESP32,
|
||||
# 不写这一行会按 ESP32 去配 ADC/RMT 通道,编译期就报"没有这个外设"。
|
||||
#
|
||||
# 串口调试走 UART0(RXD = GPIO20 / TXD = GPIO21,115200 8N1)——这是 C3 的 ROM
|
||||
# 默认控制台引脚,和参考固件里给 DBUS 用的那两个脚是同一对。想改成 USB
|
||||
# Serial/JTAG 输出,把 CONFIG_ESP_CONSOLE_UART_DEFAULT 换成
|
||||
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG 即可。
|
||||
# RXD = GPIO20 / TXD = GPIO21 专用于用户操控协议(115200 8N1)。
|
||||
# 应用与二级引导日志走原生 USB;ROM 启动阶段仍可能从 GPIO21 输出日志,
|
||||
# 外部控制器必须按帧头、长度和 CRC 接收,不得将任意启动字节解释为操控。
|
||||
CONFIG_IDF_TARGET="esp32c3"
|
||||
|
||||
# 4 MB flash;应用分区放到 2 MB(见 partitions.csv),默认的 1 MB 单 app 槽对
|
||||
@@ -14,15 +13,14 @@ CONFIG_IDF_TARGET="esp32c3"
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
|
||||
# 调试口 = UART0(GPIO20 RX / GPIO21 TX)。
|
||||
#
|
||||
# 同时打开 USB Serial/JTAG 作为**次**控制台:日志会同时从板上那个原生 USB 口出来。
|
||||
# 这样现场两种接法都能看到日志 —— 接了 USB-TTL 到 RXD/TXD 的看 UART0,直接插板上
|
||||
# USB 口的看 USB。主控制台仍是 UART0,所以"RXD/TXD 就是调试口"这条成立。
|
||||
#
|
||||
# 只用原生 USB 口烧录(不接 USB-TTL)时,这一条是能看见日志的唯一办法。
|
||||
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
|
||||
# USB Serial/JTAG 是唯一软件控制台;UART1 经 GPIO Matrix 使用用户 RXD/TXD。
|
||||
# CONFIG_ESP_CONSOLE_UART_DEFAULT is not set
|
||||
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||
# CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG is not set
|
||||
CONFIG_ESP_CONSOLE_SECONDARY_NONE=y
|
||||
|
||||
# 1 ms 调度刻度,支持操控任务 5 ms 轮询及 20 ms UART 输出。
|
||||
CONFIG_FREERTOS_HZ=1000
|
||||
|
||||
# Rust 的 main 与规则层在同一个任务栈上跑,另外 log 会用到一些栈;默认 3.5 KB
|
||||
# 在带 WiFi 的固件里容易爆栈。
|
||||
|
||||
@@ -28,17 +28,20 @@
|
||||
//! armor/scripts/flash.sh # 编译 + espflash + 串口日志
|
||||
//! ```
|
||||
//!
|
||||
//! 串口调试走 UART0:RXD = GPIO20 / TXD = GPIO21,115200 8N1(日志从 TX 出来,
|
||||
//! RX 目前空闲,留给以后加命令通道)。USB Serial/JTAG 配成了次控制台,所以插原生
|
||||
//! USB 口也能看到同一份日志。完整接线表、协议与踩坑见 `armor/README.md`。
|
||||
//! 用户 UART:RXD = GPIO20 / TXD = GPIO21,115200 8N1,输出带校验的操控帧。
|
||||
//! 软件日志只走原生 USB Serial/JTAG;UART 接收端须忽略 ROM 启动杂字节。
|
||||
//! 完整接线表、协议与踩坑见 `armor/README.md`。
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use embedded_svc::wifi::{AuthMethod, ClientConfiguration, Configuration, PmfConfiguration};
|
||||
use esp_idf_svc::eventloop::EspSystemEventLoop;
|
||||
use esp_idf_svc::hal::gpio::{PinDriver, Pull};
|
||||
use esp_idf_svc::hal::gpio::{AnyInputPin, AnyOutputPin, PinDriver, Pull};
|
||||
use esp_idf_svc::hal::peripherals::Peripherals;
|
||||
use esp_idf_svc::hal::uart::{config::Config as UartConfig, UartDriver};
|
||||
use esp_idf_svc::hal::units::Hertz;
|
||||
use esp_idf_svc::nvs::EspDefaultNvsPartition;
|
||||
use esp_idf_svc::wifi::EspWifi;
|
||||
use log::{info, warn};
|
||||
@@ -50,6 +53,7 @@ use armor_protocol::{
|
||||
mod esp;
|
||||
mod leds;
|
||||
mod net;
|
||||
mod operator_uart;
|
||||
mod piezo;
|
||||
mod settings;
|
||||
|
||||
@@ -71,7 +75,7 @@ const THRESHOLD_ENV: &str = match option_env!("ARMOR_THRESHOLD") {
|
||||
/// "装甲板未接入"。
|
||||
const REPORT_HEARTBEAT_MS: u64 = 200;
|
||||
|
||||
/// 状态行的打印周期(UART 调试口)。
|
||||
/// 状态行的打印周期(原生 USB 调试口)。
|
||||
const STATUS_INTERVAL_MS: u64 = 1000;
|
||||
|
||||
/// WiFi 断线检查周期。
|
||||
@@ -117,7 +121,7 @@ fn main() -> Result<()> {
|
||||
|
||||
info!("pins: ws2812 front=IO10 rear=IO5 left=IO6 right=IO7");
|
||||
info!("pins: piezo front=GPIO0 rear=GPIO4 left=GPIO3 right=GPIO1");
|
||||
info!("pins: boot=GPIO9 debug uart0 rxd=GPIO20 txd=GPIO21 115200 8N1");
|
||||
info!("pins: boot=GPIO9 operator uart1 rxd=GPIO20 txd=GPIO21 115200 8N1; logs=USB");
|
||||
info!(
|
||||
"armor board: team={team} ({}), {} hp, -{} per hit, {} ms dark on the hit strip",
|
||||
"client-selected",
|
||||
@@ -140,8 +144,19 @@ fn main() -> Result<()> {
|
||||
warn!("Wi-Fi connection attempt failed: {err:#}");
|
||||
}
|
||||
|
||||
let reporter = net::Reporter::new()?;
|
||||
let reporter = Arc::new(net::Reporter::new()?);
|
||||
let sender_id = net::local_id();
|
||||
let uart = UartDriver::new(
|
||||
peripherals.uart1,
|
||||
peripherals.pins.gpio21,
|
||||
peripherals.pins.gpio20,
|
||||
None::<AnyInputPin>,
|
||||
None::<AnyOutputPin>,
|
||||
&UartConfig::default()
|
||||
.baudrate(Hertz(115_200))
|
||||
.tx_fifo_size(0),
|
||||
)?;
|
||||
let (commands, operator_status) = operator_uart::start(Arc::clone(&reporter), sender_id, uart)?;
|
||||
|
||||
let mut hits: Vec<(Plate, u16)> = Vec::with_capacity(16);
|
||||
let mut reports = ReportSchedule::new(Duration::from_millis(REPORT_HEARTBEAT_MS));
|
||||
@@ -167,11 +182,19 @@ fn main() -> Result<()> {
|
||||
client.disconnect();
|
||||
damage.disconnect();
|
||||
} else {
|
||||
for _ in 0..8 {
|
||||
match reporter.receive() {
|
||||
Ok(Some((net::ControlCommand::Team(command), from))) => {
|
||||
for _ in 0..32 {
|
||||
let Ok(message) = commands.try_recv() else {
|
||||
break;
|
||||
};
|
||||
let from = message.source;
|
||||
let received_at = message.received_at;
|
||||
let processed_at = Duration::from_millis(now_ms());
|
||||
let age = processed_at.saturating_sub(received_at);
|
||||
match message.command {
|
||||
net::ControlCommand::Team(command) => {
|
||||
if command.board_id == sender_id
|
||||
&& client.accept(from, now)
|
||||
&& age < armor_protocol::CLIENT_LEASE
|
||||
&& client.accept(from, received_at)
|
||||
&& team != command.team
|
||||
{
|
||||
team = command.team;
|
||||
@@ -183,16 +206,35 @@ fn main() -> Result<()> {
|
||||
force_report = true;
|
||||
}
|
||||
}
|
||||
Ok(Some((net::ControlCommand::Damage(command), from))) => {
|
||||
if command.board_id == sender_id {
|
||||
damage.accept(command, from, now);
|
||||
net::ControlCommand::Damage(command) => {
|
||||
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||
damage.accept(command, from, received_at);
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(err) => {
|
||||
warn!("client control receive failed: {err:#}");
|
||||
break;
|
||||
net::ControlCommand::Reset(mut command) => {
|
||||
if command.board_id == sender_id && age < armor_protocol::DAMAGE_LEASE {
|
||||
if let Some(apply) = damage.accept_reset(command, from, processed_at) {
|
||||
if apply {
|
||||
armor.set_damage_enabled(false);
|
||||
armor.reset();
|
||||
operator_status.reset();
|
||||
warn!(
|
||||
"referee reset: hp={} reset_id={}",
|
||||
armor.hp(),
|
||||
command.reset_id
|
||||
);
|
||||
}
|
||||
command.acknowledged = true;
|
||||
if let Some(bytes) = command.encode() {
|
||||
if let Err(err) = reporter.send_to(&bytes, from) {
|
||||
warn!("reset acknowledgement failed: {err:#}");
|
||||
}
|
||||
}
|
||||
force_report = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
net::ControlCommand::Operator(_) | net::ControlCommand::Ignored => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,6 +253,7 @@ fn main() -> Result<()> {
|
||||
|
||||
for (plate, raw) in hits.iter().copied() {
|
||||
if let Some(event) = armor.on_sample(plate, raw, now) {
|
||||
operator_status.set_alive(event.hp > 0);
|
||||
info!(
|
||||
"hit plate={} raw={} hp={} (hits={}, damage_enabled={})",
|
||||
event.plate.name(),
|
||||
@@ -242,6 +285,7 @@ fn main() -> Result<()> {
|
||||
match button_fsm.tick(button.is_low(), now) {
|
||||
ButtonEvent::LongPress => {
|
||||
armor.reset();
|
||||
operator_status.reset();
|
||||
warn!("BOOT long press: hp reset to {} (new round)", armor.hp());
|
||||
force_report = true;
|
||||
}
|
||||
@@ -329,7 +373,7 @@ fn status_with_link(
|
||||
)
|
||||
}
|
||||
|
||||
/// 一行状态,给 UART 调试口用。
|
||||
/// 一行状态,给原生 USB 调试口用。
|
||||
///
|
||||
/// `peak` 是这一秒里每路 ADC 的峰值。它比"有没有受击"更有用:现场要判断阈值该调到
|
||||
/// 多少,靠的就是"没敲时的底噪"和"敲击时的幅度"这两个数字。
|
||||
|
||||
@@ -21,11 +21,17 @@ use anyhow::{anyhow, Result};
|
||||
use esp_idf_svc::sys as ffi;
|
||||
use log::{info, warn};
|
||||
|
||||
use armor_protocol::{ArmorControl, ArmorDamageControl, ARMOR_PORT, BROADCAST_ADDR};
|
||||
use armor_protocol::{
|
||||
ArmorControl, ArmorDamageControl, ArmorReset, OperatorControl, ARMOR_PORT, BROADCAST_ADDR,
|
||||
};
|
||||
|
||||
pub enum ControlCommand {
|
||||
Team(ArmorControl),
|
||||
Damage(ArmorDamageControl),
|
||||
Reset(ArmorReset),
|
||||
Operator(OperatorControl),
|
||||
/// A consumed datagram which is not a supported control message.
|
||||
Ignored,
|
||||
}
|
||||
|
||||
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
|
||||
@@ -71,7 +77,7 @@ pub struct Reporter {
|
||||
}
|
||||
|
||||
impl Reporter {
|
||||
/// 每轮最多由调用方读取 8 包,避免无关流量占住受击循环。
|
||||
/// 只由操控线程接收,每轮有界读取;未知包也计入本轮额度。
|
||||
pub fn receive(&self) -> Result<Option<(ControlCommand, SocketAddrV4)>> {
|
||||
let mut bytes = [0u8; 256];
|
||||
let mut addr: ffi::sockaddr_in = unsafe { core::mem::zeroed() };
|
||||
@@ -98,8 +104,12 @@ impl Reporter {
|
||||
ControlCommand::Team(control)
|
||||
} else if let Some(control) = ArmorDamageControl::decode(bytes) {
|
||||
ControlCommand::Damage(control)
|
||||
} else if let Some(control) = ArmorReset::decode(bytes) {
|
||||
ControlCommand::Reset(control)
|
||||
} else if let Some(control) = OperatorControl::decode(bytes) {
|
||||
ControlCommand::Operator(control)
|
||||
} else {
|
||||
return Ok(None);
|
||||
ControlCommand::Ignored
|
||||
};
|
||||
let ip = std::net::Ipv4Addr::from(addr.sin_addr.s_addr.to_le_bytes());
|
||||
Ok(Some((
|
||||
@@ -148,7 +158,11 @@ impl Reporter {
|
||||
|
||||
/// 把一个数据报广播到裁判终端。
|
||||
pub fn broadcast(&self, payload: &[u8]) -> Result<()> {
|
||||
let addr = to_sockaddr(SocketAddrV4::new(BROADCAST_ADDR, ARMOR_PORT));
|
||||
self.send_to(payload, SocketAddrV4::new(BROADCAST_ADDR, ARMOR_PORT))
|
||||
}
|
||||
|
||||
pub fn send_to(&self, payload: &[u8], destination: SocketAddrV4) -> Result<()> {
|
||||
let addr = to_sockaddr(destination);
|
||||
|
||||
// SAFETY: 缓冲区与地址在调用期间都有效;sendto 复制数据而不是持有指针。
|
||||
let rc = unsafe {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -37,7 +37,10 @@
|
||||
use std::time::Duration;
|
||||
|
||||
pub use protocol::{id_from_mac, ArmorHealth, MsgType, ARMOR_PORT, BROADCAST_ADDR};
|
||||
pub use protocol::{ArmorControl, ArmorDamageControl, 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 DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
||||
@@ -46,6 +49,7 @@ pub const DAMAGE_LEASE: Duration = Duration::from_secs(1);
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DamageLink {
|
||||
source: Option<(std::net::SocketAddrV4, u64, u64, Duration, bool)>,
|
||||
last_reset: Option<(std::net::SocketAddrV4, u64, u64)>,
|
||||
}
|
||||
impl DamageLink {
|
||||
pub fn disconnect(&mut self) {
|
||||
@@ -83,6 +87,40 @@ impl DamageLink {
|
||||
self.source
|
||||
.is_some_and(|(_, _, _, at, enabled)| enabled && now.saturating_sub(at) < DAMAGE_LEASE)
|
||||
}
|
||||
|
||||
/// Some(true) 执行一次复位;Some(false) 只重发回执;None 拒绝。
|
||||
/// 必须先收到同源、同序号的禁止扣血许可,延迟到达的旧复位不能影响后续阶段。
|
||||
pub fn accept_reset(
|
||||
&mut self,
|
||||
command: ArmorReset,
|
||||
from: std::net::SocketAddrV4,
|
||||
now: Duration,
|
||||
) -> Option<bool> {
|
||||
let (addr, session, sequence, at, enabled) = self.source?;
|
||||
if command.acknowledged
|
||||
|| enabled
|
||||
|| addr != from
|
||||
|| session != command.session
|
||||
|| sequence != command.sequence
|
||||
|| command.reset_id == 0
|
||||
|| command.reset_id > sequence
|
||||
|| now.saturating_sub(at) >= DAMAGE_LEASE
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some((last_addr, last_session, reset_id)) = self.last_reset {
|
||||
if last_addr == from && last_session == session {
|
||||
if command.reset_id < reset_id {
|
||||
return None;
|
||||
}
|
||||
if command.reset_id == reset_id {
|
||||
return Some(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.last_reset = Some((from, session, command.reset_id));
|
||||
Some(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 只接受当前持有者续约;其他客户端需等租约到期,避免裁判与操作手交替改色。
|
||||
@@ -734,6 +772,94 @@ mod tests {
|
||||
assert!(!link.enabled(ms(2003)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_reset_requires_current_disabled_permission_and_only_applies_once() {
|
||||
let mut link = DamageLink::default();
|
||||
let from = "192.168.1.2:5601".parse().unwrap();
|
||||
let other = "192.168.1.3:5601".parse().unwrap();
|
||||
let mut permit = ArmorDamageControl {
|
||||
board_id: 9,
|
||||
session: 11,
|
||||
sequence: 10,
|
||||
enabled: false,
|
||||
};
|
||||
let mut reset = ArmorReset {
|
||||
board_id: 9,
|
||||
session: 11,
|
||||
sequence: 10,
|
||||
reset_id: 10,
|
||||
acknowledged: false,
|
||||
};
|
||||
assert_eq!(link.accept_reset(reset, from, ms(0)), None);
|
||||
assert!(link.accept(permit, from, ms(0)));
|
||||
assert_eq!(link.accept_reset(reset, other, ms(1)), None);
|
||||
assert_eq!(
|
||||
link.accept_reset(
|
||||
ArmorReset {
|
||||
session: 12,
|
||||
..reset
|
||||
},
|
||||
from,
|
||||
ms(1)
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
link.accept_reset(
|
||||
ArmorReset {
|
||||
acknowledged: true,
|
||||
..reset
|
||||
},
|
||||
from,
|
||||
ms(1)
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(link.accept_reset(reset, from, ms(1)), Some(true));
|
||||
assert_eq!(link.accept_reset(reset, from, ms(2)), Some(false));
|
||||
|
||||
let mut a = armor();
|
||||
a.on_sample(Plate::Front, 2500, ms(0)).unwrap();
|
||||
assert_eq!(a.hp(), 97);
|
||||
a.set_damage_enabled(false);
|
||||
a.reset();
|
||||
assert_eq!((a.hp(), a.hits(), a.plate_hits(Plate::Front)), (100, 0, 0));
|
||||
assert!(!a.damage_enabled());
|
||||
assert_eq!(a.color(), Rgb::for_team(0));
|
||||
|
||||
// 重试更新许可序号,但保留复位 id;丢回执也不能重复补血。
|
||||
permit.sequence += 1;
|
||||
assert!(link.accept(permit, from, ms(200)));
|
||||
assert_eq!(link.accept_reset(reset, from, ms(201)), None);
|
||||
reset.sequence = permit.sequence;
|
||||
assert_eq!(link.accept_reset(reset, from, ms(201)), Some(false));
|
||||
assert_eq!(link.accept_reset(reset, from, ms(1200)), None);
|
||||
permit.sequence += 1;
|
||||
permit.enabled = true;
|
||||
assert!(link.accept(permit, from, ms(1201)));
|
||||
reset.sequence = permit.sequence;
|
||||
assert_eq!(link.accept_reset(reset, from, ms(1202)), None);
|
||||
permit.sequence += 1;
|
||||
permit.enabled = false;
|
||||
assert!(link.accept(permit, from, ms(1203)));
|
||||
reset.sequence = permit.sequence;
|
||||
reset.reset_id = permit.sequence;
|
||||
assert_eq!(link.accept_reset(reset, from, ms(1204)), Some(true));
|
||||
assert_eq!(
|
||||
link.accept_reset(
|
||||
ArmorReset {
|
||||
reset_id: 10,
|
||||
..reset
|
||||
},
|
||||
from,
|
||||
ms(1205)
|
||||
),
|
||||
None
|
||||
);
|
||||
link.disconnect();
|
||||
assert_eq!(link.accept_reset(reset, from, ms(1206)), None);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 血量 --
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -39,6 +39,8 @@ MSG_ARMOR_HEALTH = 5 # MsgType::ArmorHealth
|
||||
MSG_ARMOR_CONTROL = 6
|
||||
MSG_MATCH_STATE = 7 # 比赛计时广播;装甲板探测器忽略
|
||||
MSG_ARMOR_DAMAGE_CONTROL = 8 # 扣血许可;装甲板探测器忽略
|
||||
MSG_ARMOR_RESET = 9 # 复位与回执;探测器只解析,不发送
|
||||
MSG_MATCH_RESULT = 10 # 裁判终局快照;探测器忽略
|
||||
PROTOCOL_VERSION = 1
|
||||
TEAM_NAMES = {0: "队伍一", 1: "队伍二", 255: "待分配队伍"}
|
||||
|
||||
@@ -66,6 +68,41 @@ def decode_damage_control(data):
|
||||
return (board, session, sequence, bool(data[47])) if board and session and sequence else None
|
||||
|
||||
|
||||
def decode_match_result(data):
|
||||
"""独立检查裁判终局格式;不产生装甲板控制操作。"""
|
||||
if len(data) != HEADER + 34 or int.from_bytes(data[:4], "little") != MAGIC:
|
||||
return None
|
||||
if data[4] != MSG_MATCH_RESULT or int.from_bytes(data[5:7], "little") != PROTOCOL_VERSION or int.from_bytes(data[7:11], "little") != 0:
|
||||
return None
|
||||
session = int.from_bytes(data[27:35], "little")
|
||||
sequence = int.from_bytes(data[35:43], "little")
|
||||
result_id = int.from_bytes(data[43:51], "little")
|
||||
remaining = int.from_bytes(data[51:55], "little")
|
||||
elapsed = int.from_bytes(data[55:59], "little")
|
||||
outcomes = tuple(data[59:61])
|
||||
if not session or not 0 < result_id <= sequence or max(remaining, elapsed) > 180000 or outcomes not in ((1, 2), (2, 1), (2, 0), (0, 2), (3, 3)):
|
||||
return None
|
||||
return session, sequence, result_id, remaining, elapsed, outcomes
|
||||
|
||||
|
||||
def decode_reset(data):
|
||||
"""独立核对复位及回执的 56 字节格式,不向设备发送复位。"""
|
||||
if len(data) != HEADER + 29 or int.from_bytes(data[:4], "little") != MAGIC:
|
||||
return None
|
||||
if data[4] != MSG_ARMOR_RESET or int.from_bytes(data[5:7], "little") != PROTOCOL_VERSION or data[-1] not in (0, 1):
|
||||
return None
|
||||
board = int.from_bytes(data[27:31], "little")
|
||||
session = int.from_bytes(data[31:39], "little")
|
||||
sequence = int.from_bytes(data[39:47], "little")
|
||||
reset_id = int.from_bytes(data[47:55], "little")
|
||||
acknowledged = bool(data[55])
|
||||
if not board or not session or not 0 < reset_id <= sequence:
|
||||
return None
|
||||
if int.from_bytes(data[7:11], "little") != (board if acknowledged else 0):
|
||||
return None
|
||||
return board, session, sequence, reset_id, acknowledged
|
||||
|
||||
|
||||
def decode(data):
|
||||
"""解析一个数据报,返回 (team, index, hp, sender_id, version) 或 None。"""
|
||||
if len(data) < HEADER + 4:
|
||||
|
||||
@@ -24,5 +24,19 @@ class WireTests(unittest.TestCase):
|
||||
self.assertIsNone(probe.decode(packet))
|
||||
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x02', packet[:31] + bytes(8) + packet[39:]):
|
||||
self.assertIsNone(probe.decode_damage_control(invalid))
|
||||
def test_reset_golden_and_ack_identity(self):
|
||||
packet = bytes.fromhex("3143564d090100" + "00" * 20 + "78563412" + "0807060504030201" + "0300000000000000" + "0200000000000000" + "00")
|
||||
self.assertEqual(probe.decode_reset(packet), (0x12345678, 0x0102030405060708, 3, 2, False))
|
||||
ack = packet[:7] + bytes.fromhex("78563412") + packet[11:-1] + b'\x01'
|
||||
self.assertEqual(probe.decode_reset(ack)[-1], True)
|
||||
self.assertIsNone(probe.decode(packet))
|
||||
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x01', ack[:-1] + b'\x00', packet[:47] + bytes(8) + packet[55:]):
|
||||
self.assertIsNone(probe.decode_reset(invalid))
|
||||
def test_match_result_golden(self):
|
||||
packet = bytes.fromhex("3143564d0a0100" + "00" * 20 + "0900000000000000" + "1400000000000000" + "1200000000000000" + "a0860100" + "80380100" + "0201")
|
||||
self.assertEqual(probe.decode_match_result(packet), (9, 20, 18, 100000, 80000, (2, 1)))
|
||||
self.assertIsNone(probe.decode(packet))
|
||||
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x02', packet[:43] + bytes(8) + packet[51:]):
|
||||
self.assertIsNone(probe.decode_match_result(invalid))
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -113,6 +113,7 @@ pub struct ArmorReport {
|
||||
/// 在接收线程里被调用,所以必须是非阻塞的。Tauri 层在这里做掉血检测并把结果推给界面。
|
||||
pub type ArmorSink = Arc<dyn Fn(ArmorReport) + Send + Sync>;
|
||||
pub type MatchSink = Arc<dyn Fn(protocol::MatchState, Ipv4Addr) + Send + Sync>;
|
||||
pub type MatchResultSink = Arc<dyn Fn(protocol::MatchResult, Ipv4Addr) + Send + Sync>;
|
||||
|
||||
/// 已收到的最新血量。
|
||||
#[derive(Debug, Default)]
|
||||
@@ -199,7 +200,10 @@ pub struct ArmorHealthStore {
|
||||
sink: Mutex<Option<ArmorSink>>,
|
||||
assignments: Mutex<Vec<(u32, u8)>>,
|
||||
match_sink: Mutex<Option<MatchSink>>,
|
||||
mirror_sink: Mutex<Option<Arc<dyn Fn(protocol::CameraMirror) + Send + Sync>>>,
|
||||
match_result_sink: Mutex<Option<MatchResultSink>>,
|
||||
damage_participants: Mutex<HashSet<u32>>,
|
||||
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
|
||||
}
|
||||
|
||||
impl Default for ArmorHealthStore {
|
||||
@@ -216,7 +220,10 @@ impl ArmorHealthStore {
|
||||
sink: Mutex::new(None),
|
||||
assignments: Mutex::new(Vec::new()),
|
||||
match_sink: Mutex::new(None),
|
||||
mirror_sink: Mutex::new(None),
|
||||
match_result_sink: Mutex::new(None),
|
||||
damage_participants: Mutex::new(HashSet::new()),
|
||||
reset: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,6 +280,17 @@ impl ArmorHealthStore {
|
||||
|
||||
/// 处理一条上报。测试从这里喂字节。
|
||||
pub fn datagram(&self, bytes: &[u8], from: SocketAddr) {
|
||||
if let Some(packet) = protocol::CameraMirror::decode(bytes) {
|
||||
if let Some(sink) = self
|
||||
.mirror_sink
|
||||
.lock()
|
||||
.expect("mirror sink poisoned")
|
||||
.clone()
|
||||
{
|
||||
sink(packet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let SocketAddr::V4(addr) = from else {
|
||||
return;
|
||||
};
|
||||
@@ -282,6 +300,23 @@ impl ArmorHealthStore {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(packet) = protocol::MatchResult::decode(bytes) {
|
||||
if let Some(sink) = self
|
||||
.match_result_sink
|
||||
.lock()
|
||||
.expect("match result sink poisoned")
|
||||
.clone()
|
||||
{
|
||||
sink(packet, *addr.ip());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(packet) = protocol::ArmorReset::decode(bytes) {
|
||||
if let Some(reset) = self.reset.lock().expect("armor reset poisoned").as_mut() {
|
||||
reset.acknowledge(packet, addr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 同一个端口上可能有别的东西(图传板的心跳、别的协议),解不出来就当不是给
|
||||
// 我的,安静跳过。
|
||||
@@ -383,6 +418,9 @@ impl ArmorHealthStore {
|
||||
entry.last_seen = Instant::now();
|
||||
}
|
||||
|
||||
if let Some(reset) = self.reset.lock().expect("armor reset poisoned").as_mut() {
|
||||
reset.observe(&report);
|
||||
}
|
||||
let sink = self.sink.lock().expect("armor sink mutex poisoned").clone();
|
||||
if let Some(sink) = sink {
|
||||
sink(report);
|
||||
@@ -393,6 +431,15 @@ impl ArmorHealthStore {
|
||||
pub fn set_match_sink(&self, sink: MatchSink) {
|
||||
*self.match_sink.lock().expect("match sink poisoned") = Some(sink);
|
||||
}
|
||||
pub fn set_mirror_sink(&self, sink: Arc<dyn Fn(protocol::CameraMirror) + Send + Sync>) {
|
||||
*self.mirror_sink.lock().expect("mirror sink poisoned") = Some(sink);
|
||||
}
|
||||
pub fn set_match_result_sink(&self, sink: MatchResultSink) {
|
||||
*self
|
||||
.match_result_sink
|
||||
.lock()
|
||||
.expect("match result sink poisoned") = Some(sink);
|
||||
}
|
||||
|
||||
pub fn set_sink(&self, sink: ArmorSink) {
|
||||
*self.sink.lock().expect("armor sink mutex poisoned") = Some(sink);
|
||||
@@ -474,6 +521,55 @@ impl ArmorHealthStore {
|
||||
first_error.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
pub fn begin_reset(
|
||||
&self,
|
||||
state: &protocol::MatchState,
|
||||
participants: [Option<u32>; 2],
|
||||
) -> Result<(), String> {
|
||||
let tracker =
|
||||
crate::armor_reset::ArmorResetTracker::new(state, participants, &self.boards())?;
|
||||
let mut reset = self.reset.lock().expect("armor reset poisoned");
|
||||
if reset.is_some() {
|
||||
return Err("正在复位装甲板,请等待结果".into());
|
||||
}
|
||||
*reset = Some(tracker);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn reset_waiting(&self) -> Vec<u32> {
|
||||
self.reset
|
||||
.lock()
|
||||
.expect("armor reset poisoned")
|
||||
.as_ref()
|
||||
.map(|reset| reset.waiting())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn finish_reset(&self) {
|
||||
*self.reset.lock().expect("armor reset poisoned") = None;
|
||||
}
|
||||
|
||||
/// 与禁止扣血许可使用同一份序号;每次心跳最多向每块待确认主板发送一次。
|
||||
pub fn send_reset_controls(
|
||||
&self,
|
||||
socket: &UdpSocket,
|
||||
state: &protocol::MatchState,
|
||||
) -> std::io::Result<()> {
|
||||
let packets = {
|
||||
let mut reset = self.reset.lock().expect("armor reset poisoned");
|
||||
reset
|
||||
.as_mut()
|
||||
.map(|reset| reset.packets(state))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
for (packet, addr) in packets {
|
||||
if let Some(bytes) = packet.encode() {
|
||||
socket.send_to(&bytes, addr)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_controls(&self, socket: &UdpSocket) {
|
||||
let selected = self
|
||||
.assignments
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! 一次有界复位事务:固定目标,等待逐板回执及回执后的四路满血上报。
|
||||
use crate::armor::{ArmorBoard, ArmorReport};
|
||||
use protocol::{ArmorReset, MatchState};
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Target {
|
||||
id: u32,
|
||||
addr: SocketAddrV4,
|
||||
acknowledged: bool,
|
||||
full_plates: u8,
|
||||
sent_sequence: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ArmorResetTracker {
|
||||
session: u64,
|
||||
reset_id: u64,
|
||||
targets: Vec<Target>,
|
||||
}
|
||||
|
||||
impl ArmorResetTracker {
|
||||
pub fn new(
|
||||
state: &MatchState,
|
||||
participants: [Option<u32>; 2],
|
||||
boards: &[ArmorBoard],
|
||||
) -> Result<Self, String> {
|
||||
if state.phase != 6 || state.session == 0 || state.sequence == 0 {
|
||||
return Err("请先结束本局,再复位装甲板".into());
|
||||
}
|
||||
if participants[0].is_some() && participants[0] == participants[1] {
|
||||
return Err("两队不能使用同一块装甲板,请检查槽位".into());
|
||||
}
|
||||
let mut targets = Vec::new();
|
||||
for id in participants.into_iter().flatten() {
|
||||
let board = boards
|
||||
.iter()
|
||||
.find(|board| board.id == id && board.is_online())
|
||||
.ok_or_else(|| format!("装甲板 0x{id:08X} 离线,无法复位;请恢复连接后重试"))?;
|
||||
targets.push(Target {
|
||||
id,
|
||||
addr: board.addr,
|
||||
acknowledged: false,
|
||||
full_plates: 0,
|
||||
sent_sequence: 0,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
session: state.session,
|
||||
reset_id: state.sequence,
|
||||
targets,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn packets(&mut self, state: &MatchState) -> Vec<(ArmorReset, SocketAddrV4)> {
|
||||
if state.phase != 6 || state.session != self.session || state.sequence < self.reset_id {
|
||||
return Vec::new();
|
||||
}
|
||||
self.targets
|
||||
.iter_mut()
|
||||
.filter(|target| !target.acknowledged)
|
||||
.map(|target| {
|
||||
target.sent_sequence = state.sequence;
|
||||
(
|
||||
ArmorReset {
|
||||
board_id: target.id,
|
||||
session: self.session,
|
||||
sequence: state.sequence,
|
||||
reset_id: self.reset_id,
|
||||
acknowledged: false,
|
||||
},
|
||||
target.addr,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn acknowledge(&mut self, packet: ArmorReset, from: SocketAddrV4) {
|
||||
if !packet.acknowledged
|
||||
|| packet.session != self.session
|
||||
|| packet.reset_id != self.reset_id
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(target) = self.targets.iter_mut().find(|target| {
|
||||
target.id == packet.board_id
|
||||
&& target.addr == from
|
||||
&& packet.sequence >= self.reset_id
|
||||
&& packet.sequence <= target.sent_sequence
|
||||
}) {
|
||||
target.acknowledged = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn observe(&mut self, report: &ArmorReport) {
|
||||
if let Some(target) = self.targets.iter_mut().find(|target| {
|
||||
target.id == report.board && target.addr == report.addr && target.acknowledged
|
||||
}) {
|
||||
if report.hp == 100 && report.index < 4 {
|
||||
target.full_plates |= 1 << report.index;
|
||||
} else {
|
||||
target.full_plates = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn waiting(&self) -> Vec<u32> {
|
||||
self.targets
|
||||
.iter()
|
||||
.filter(|target| !target.acknowledged || target.full_plates != 0b1111)
|
||||
.map(|target| target.id)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CameraOrientation {
|
||||
pub revision: u64,
|
||||
pub origin: u64,
|
||||
pub mirror: bool,
|
||||
pub mirror_vertical: bool,
|
||||
}
|
||||
pub type CameraMirrors = BTreeMap<String, CameraOrientation>;
|
||||
impl CameraOrientation {
|
||||
pub fn packet(&self, camera_id: u32) -> protocol::CameraMirror {
|
||||
protocol::CameraMirror {
|
||||
camera_id,
|
||||
revision: self.revision,
|
||||
origin: self.origin,
|
||||
mirror: self.mirror,
|
||||
mirror_vertical: self.mirror_vertical,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn merge(entries: &mut CameraMirrors, packet: protocol::CameraMirror) -> bool {
|
||||
if packet.encode().is_none()
|
||||
|| entries
|
||||
.get(&packet.camera_id.to_string())
|
||||
.is_some_and(|old| (old.revision, old.origin) >= (packet.revision, packet.origin))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
entries.insert(
|
||||
packet.camera_id.to_string(),
|
||||
CameraOrientation {
|
||||
revision: packet.revision,
|
||||
origin: packet.origin,
|
||||
mirror: packet.mirror,
|
||||
mirror_vertical: packet.mirror_vertical,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn concurrent_writes_converge_without_echo_or_cross_camera_changes() {
|
||||
let a = protocol::CameraMirror {
|
||||
camera_id: 7,
|
||||
revision: 2,
|
||||
origin: 8,
|
||||
mirror: true,
|
||||
mirror_vertical: false,
|
||||
};
|
||||
let b = protocol::CameraMirror {
|
||||
origin: 9,
|
||||
mirror: false,
|
||||
mirror_vertical: true,
|
||||
..a
|
||||
};
|
||||
let mut left = CameraMirrors::new();
|
||||
let mut right = CameraMirrors::new();
|
||||
merge(&mut left, a);
|
||||
merge(&mut left, b);
|
||||
merge(&mut right, b);
|
||||
assert!(!merge(&mut right, a));
|
||||
assert_eq!(left, right);
|
||||
assert!(!merge(&mut left, b));
|
||||
merge(&mut left, protocol::CameraMirror { camera_id: 9, ..a });
|
||||
assert_eq!(left.len(), 2);
|
||||
let mut config = crate::Config::default();
|
||||
config.camera_mirrors = left;
|
||||
assert_eq!(
|
||||
crate::Config::parse(&toml::to_string(&config).unwrap())
|
||||
.unwrap()
|
||||
.camera_mirrors,
|
||||
config.camera_mirrors
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -438,6 +438,9 @@ pub struct Config {
|
||||
pub armor_id: Option<u32>,
|
||||
/// 左右镜像。摄像头装反了,出图左右颠倒,所以默认翻回来。
|
||||
pub mirror: bool,
|
||||
/// 上下镜像,与左右镜像独立;旧配置默认关闭。
|
||||
pub mirror_vertical: bool,
|
||||
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
||||
///
|
||||
/// 只对用户端有意义([`Role::needs_password`])。
|
||||
@@ -463,6 +466,8 @@ impl Default for Config {
|
||||
camera_id: None,
|
||||
armor_id: None,
|
||||
mirror: true,
|
||||
mirror_vertical: false,
|
||||
camera_mirrors: Default::default(),
|
||||
password: None,
|
||||
hud: HudConfig::default(),
|
||||
referee: RefereeConfig::default(),
|
||||
@@ -607,6 +612,7 @@ const HEADER: &str = "\
|
||||
# cameraId : 图传板 id,由 MAC 派生,重启不变,所以绑定是稳的
|
||||
# armorId : 装甲板主板 id,同上
|
||||
# mirror : true = 左右镜像(摄像头装反了,默认)
|
||||
# mirrorVertical: true = 上下镜像(默认关闭,可与左右镜像组合)
|
||||
# password : Argon2id 哈希(仅 team 端)。这里没有明文,也恢复不出明文;
|
||||
# 忘了密码就删掉这一行,然后第一次启动会要求重新设置。
|
||||
#
|
||||
@@ -867,6 +873,14 @@ mod tests {
|
||||
assert!(!config.needs_password_setup(), "裁判端不设密码");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_configs_keep_their_orientation_without_vertical_mirroring() {
|
||||
let config = Config::parse("mirror = false\nteamNames = [\"红队\", \"蓝队\"]\n").unwrap();
|
||||
assert!(!config.mirror);
|
||||
assert!(!config.mirror_vertical);
|
||||
assert_eq!(config.team_names, ["红队", "蓝队"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_roundtrip_survives_every_field() {
|
||||
let mut config = Config::default();
|
||||
@@ -877,6 +891,7 @@ mod tests {
|
||||
config.camera_id = Some(0x3D4D_8A9A);
|
||||
config.armor_id = Some(0x00AB_CDEF);
|
||||
config.mirror = false;
|
||||
config.mirror_vertical = true;
|
||||
config.password = Some("$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".to_string());
|
||||
config.hud.crosshair.offset_x = -0.125;
|
||||
config.hud.crosshair.style = CrosshairStyle::CircleDot;
|
||||
@@ -894,6 +909,7 @@ mod tests {
|
||||
assert_eq!(back.camera_id, Some(0x3D4D_8A9A));
|
||||
assert_eq!(back.armor_id, Some(0x00AB_CDEF));
|
||||
assert!(!back.mirror);
|
||||
assert!(back.mirror_vertical);
|
||||
assert_eq!(back.password, config.password);
|
||||
assert_eq!(back.hud.crosshair.offset_x, -0.125);
|
||||
assert_eq!(back.hud.crosshair.style, CrosshairStyle::CircleDot);
|
||||
|
||||
@@ -27,8 +27,12 @@
|
||||
//! 那两处要的是当前状态,不是每一帧。
|
||||
|
||||
pub mod armor;
|
||||
pub mod armor_reset;
|
||||
pub mod config;
|
||||
pub mod camera_mirror;
|
||||
pub mod mirror_transport;
|
||||
pub mod match_clock;
|
||||
pub mod operator;
|
||||
pub mod password;
|
||||
pub mod receiver;
|
||||
pub mod slots;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 裁判计时规则与选手端快照跟随。所有时间来自调用方的单调时钟。
|
||||
//! UDP 会话锁定到首次收到的来源;掉线不自动换裁判,需显式重新接收。
|
||||
use crate::snapshot::{resolve_outcomes, MatchOutcome, TeamHealthDto};
|
||||
use protocol::MatchState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::Ipv4Addr;
|
||||
@@ -10,6 +11,7 @@ pub const SYNC_LEASE_MS: u64 = 1500;
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum MatchAction {
|
||||
Prepare,
|
||||
SkipPreparation,
|
||||
Countdown {
|
||||
seconds: u32,
|
||||
},
|
||||
@@ -52,6 +54,7 @@ pub struct MatchClock {
|
||||
at: u64,
|
||||
source: Option<(Ipv4Addr, u64)>,
|
||||
received_at: Option<u64>,
|
||||
result: Option<protocol::MatchResult>,
|
||||
}
|
||||
|
||||
fn idle(session: u64) -> MatchState {
|
||||
@@ -116,6 +119,7 @@ impl MatchClock {
|
||||
at: now,
|
||||
source: None,
|
||||
received_at: None,
|
||||
result: None,
|
||||
}
|
||||
}
|
||||
pub fn set_authority(&mut self, authority: bool, now: u64) {
|
||||
@@ -127,6 +131,7 @@ impl MatchClock {
|
||||
self.at = now;
|
||||
self.source = None;
|
||||
self.received_at = None;
|
||||
self.result = None;
|
||||
}
|
||||
}
|
||||
fn advance(&mut self, now: u64) {
|
||||
@@ -155,13 +160,17 @@ impl MatchClock {
|
||||
}
|
||||
self.advance(now);
|
||||
match action {
|
||||
MatchAction::Prepare if matches!(self.state.phase, 0 | 6) => {
|
||||
MatchAction::Prepare if matches!(self.state.phase, 0 | 6) && self.result.is_none() => {
|
||||
let seq = self.state.sequence;
|
||||
self.state = idle(self.local_session);
|
||||
self.state.sequence = seq;
|
||||
self.state.phase = 1;
|
||||
self.state.remaining_ms = 180_000;
|
||||
}
|
||||
MatchAction::SkipPreparation if matches!(self.state.phase, 1 | 2) => {
|
||||
self.state.phase = 2;
|
||||
self.state.remaining_ms = 0;
|
||||
}
|
||||
MatchAction::Countdown { seconds }
|
||||
if self.state.phase == 2 && (1..=60).contains(&seconds) =>
|
||||
{
|
||||
@@ -194,6 +203,7 @@ impl MatchClock {
|
||||
let seq = self.state.sequence;
|
||||
self.state = idle(self.local_session);
|
||||
self.state.sequence = seq;
|
||||
self.result = None;
|
||||
}
|
||||
_ => {
|
||||
return Err(
|
||||
@@ -204,6 +214,123 @@ impl MatchClock {
|
||||
self.state.sequence = self.state.sequence.saturating_add(1);
|
||||
Ok(())
|
||||
}
|
||||
/// 装甲板复位期间保持结束状态,先停止扣血;确认满血后再 Reset 到未开始。
|
||||
pub fn begin_reset(&mut self, has_outcome: bool, now: u64) -> Result<MatchState, String> {
|
||||
if !self.authority {
|
||||
return Err("只有裁判端可以重置比赛".into());
|
||||
}
|
||||
self.advance(now);
|
||||
if !matches!(self.state.phase, 0 | 6) && !has_outcome {
|
||||
return Err("比赛尚未结束,请先结束本局再重置".into());
|
||||
}
|
||||
self.state.phase = 6;
|
||||
clear_pause(&mut self.state);
|
||||
self.state.sequence = self.state.sequence.saturating_add(1);
|
||||
Ok(self.state.clone())
|
||||
}
|
||||
|
||||
/// 首次归零结束正在进行的对局;后续上报不得重新结算。
|
||||
pub fn finish_on_health(&mut self, hp: [Option<u16>; 2], now: u64) -> bool {
|
||||
if !self.authority || self.result.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.advance(now);
|
||||
let playing =
|
||||
self.state.phase == 4 || (self.state.phase == 5 && self.state.resume_phase == 4);
|
||||
if !playing || !hp.contains(&Some(0)) {
|
||||
return false;
|
||||
}
|
||||
let outcomes = match hp {
|
||||
[Some(0), Some(0)] => [3, 3],
|
||||
[Some(0), Some(hp)] if hp > 0 => [2, 1],
|
||||
[Some(hp), Some(0)] if hp > 0 => [1, 2],
|
||||
[Some(0), _] => [2, 0],
|
||||
_ => [0, 2],
|
||||
};
|
||||
self.state.phase = 6;
|
||||
clear_pause(&mut self.state);
|
||||
self.state.sequence = self.state.sequence.saturating_add(1);
|
||||
self.result = Some(protocol::MatchResult {
|
||||
session: self.state.session,
|
||||
sequence: self.state.sequence,
|
||||
result_id: self.state.sequence,
|
||||
remaining_ms: self.state.remaining_ms,
|
||||
elapsed_ms: self.state.elapsed_ms,
|
||||
outcomes,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
pub fn result_packet(&self) -> Option<protocol::MatchResult> {
|
||||
if !self.authority || self.state.phase != 6 {
|
||||
return None;
|
||||
}
|
||||
self.result.map(|result| protocol::MatchResult {
|
||||
sequence: self.state.sequence,
|
||||
..result
|
||||
})
|
||||
}
|
||||
|
||||
/// 终局只投影锁定结论,不篡改装甲板的真实血量。正式选手端以裁判结论为准。
|
||||
pub fn apply_outcomes(&self, health: &mut [TeamHealthDto]) {
|
||||
for entry in health.iter_mut() {
|
||||
entry.outcome = None;
|
||||
}
|
||||
if let Some(result) = self.result {
|
||||
for entry in health {
|
||||
entry.outcome = match result.outcomes.get(usize::from(entry.team)) {
|
||||
Some(1) => Some(MatchOutcome::Victory),
|
||||
Some(2) => Some(MatchOutcome::Defeat),
|
||||
Some(3) => Some(MatchOutcome::Draw),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
} else if (self.authority && self.state.phase != 6)
|
||||
|| (!self.authority && self.source.is_none())
|
||||
{
|
||||
resolve_outcomes(health);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive_result(
|
||||
&mut self,
|
||||
result: protocol::MatchResult,
|
||||
ip: Ipv4Addr,
|
||||
now: u64,
|
||||
) -> bool {
|
||||
if self.authority || !result.valid() {
|
||||
return false;
|
||||
}
|
||||
if let Some(previous) = self.result {
|
||||
if previous.session == result.session
|
||||
&& (result.result_id < previous.result_id
|
||||
|| (result.result_id == previous.result_id
|
||||
&& (result.outcomes != previous.outcomes
|
||||
|| result.remaining_ms != previous.remaining_ms
|
||||
|| result.elapsed_ms != previous.elapsed_ms)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let same_snapshot = self.source == Some((ip, result.session))
|
||||
&& self.state.sequence == result.sequence
|
||||
&& self.state.phase == 6
|
||||
&& self.state.remaining_ms == result.remaining_ms
|
||||
&& self.state.elapsed_ms == result.elapsed_ms;
|
||||
if !same_snapshot {
|
||||
let mut state = idle(result.session);
|
||||
state.sequence = result.sequence;
|
||||
state.phase = 6;
|
||||
state.remaining_ms = result.remaining_ms;
|
||||
state.elapsed_ms = result.elapsed_ms;
|
||||
if !self.receive(state, ip, now) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let changed = self.result != Some(result);
|
||||
self.result = Some(result);
|
||||
changed
|
||||
}
|
||||
fn pause(&mut self, kind: u8, team: u8, reason: String) -> Result<(), String> {
|
||||
if !(1..=4).contains(&self.state.phase) {
|
||||
return Err("当前阶段不能申请技术暂停".into());
|
||||
@@ -239,6 +366,9 @@ impl MatchClock {
|
||||
}
|
||||
}
|
||||
self.source = Some((ip, packet.session));
|
||||
if packet.phase != 6 {
|
||||
self.result = None;
|
||||
}
|
||||
self.state = packet;
|
||||
self.received_at = Some(now);
|
||||
true
|
||||
@@ -251,6 +381,7 @@ impl MatchClock {
|
||||
self.source = None;
|
||||
self.received_at = None;
|
||||
self.state = idle(self.local_session);
|
||||
self.result = None;
|
||||
Ok(())
|
||||
}
|
||||
pub fn view(&mut self, now: u64) -> MatchView {
|
||||
@@ -296,6 +427,99 @@ mod tests {
|
||||
c.action(MatchAction::Prepare, 0).unwrap();
|
||||
assert_eq!(c.view(180_000).phase, "ready");
|
||||
}
|
||||
fn running(c: &mut MatchClock) {
|
||||
c.action(MatchAction::Prepare, 0).unwrap();
|
||||
c.action(MatchAction::SkipPreparation, 100).unwrap();
|
||||
c.action(MatchAction::Countdown { seconds: 1 }, 100)
|
||||
.unwrap();
|
||||
assert_eq!(c.view(1100).phase, "running");
|
||||
}
|
||||
#[test]
|
||||
fn first_knockout_stops_time_and_locks_result_through_late_health_and_reset_attempts() {
|
||||
let mut c = MatchClock::new(true, 44, 0);
|
||||
assert!(!c.finish_on_health([Some(0), Some(10)], 0));
|
||||
running(&mut c);
|
||||
assert!(c.finish_on_health([Some(0), Some(10)], 2100));
|
||||
let result = c.result_packet().unwrap();
|
||||
assert_eq!(result.outcomes, [2, 1]);
|
||||
assert_eq!(
|
||||
(c.view(10_000).phase, c.view(10_000).elapsed_ms),
|
||||
("finished", 1000)
|
||||
);
|
||||
assert!(!c.finish_on_health([Some(0), Some(0)], 10_000));
|
||||
assert!(!c.finish_on_health([Some(100), Some(0)], 10_000));
|
||||
let names = ["红队".into(), "蓝队".into()];
|
||||
let mut health = [
|
||||
TeamHealthDto::present(0, Some(1), [0; 4], 25, &names),
|
||||
TeamHealthDto::present(1, Some(2), [0; 4], 25, &names),
|
||||
];
|
||||
c.apply_outcomes(&mut health);
|
||||
assert_eq!(health[0].outcome, Some(MatchOutcome::Defeat));
|
||||
assert_eq!(health[1].outcome, Some(MatchOutcome::Victory));
|
||||
assert_eq!(health[1].hp, Some(0), "结论锁定不篡改真实上报");
|
||||
assert!(c.action(MatchAction::Prepare, 10_000).is_err());
|
||||
c.begin_reset(true, 10_000).unwrap();
|
||||
assert_eq!(c.result_packet().unwrap().result_id, result.result_id);
|
||||
c.action(MatchAction::Reset, 10_000).unwrap();
|
||||
assert!(c.result_packet().is_none());
|
||||
c.action(MatchAction::Prepare, 10_000).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn knockout_handles_paused_play_draw_and_missing_opponent_without_inventing_a_win() {
|
||||
for (hp, expected) in [
|
||||
([Some(0), Some(0)], [3, 3]),
|
||||
([Some(0), None], [2, 0]),
|
||||
([None, Some(0)], [0, 2]),
|
||||
] {
|
||||
let mut c = MatchClock::new(true, 44, 0);
|
||||
running(&mut c);
|
||||
c.action(
|
||||
MatchAction::PauseOfficial {
|
||||
reason: "检查".into(),
|
||||
},
|
||||
2100,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(c.finish_on_health(hp, 2200));
|
||||
assert_eq!(c.result_packet().unwrap().outcomes, expected);
|
||||
}
|
||||
assert!(!MatchClock::new(false, 2, 0).finish_on_health([Some(0), Some(10)], 0));
|
||||
}
|
||||
#[test]
|
||||
fn result_sync_is_self_contained_order_independent_and_cannot_revive_after_reset() {
|
||||
let mut referee = MatchClock::new(true, 44, 0);
|
||||
running(&mut referee);
|
||||
referee.finish_on_health([Some(10), Some(0)], 2100);
|
||||
let state = referee.broadcast(2100).unwrap();
|
||||
let result = referee.result_packet().unwrap();
|
||||
for result_first in [false, true] {
|
||||
let mut player = MatchClock::new(false, 2, 0);
|
||||
if result_first {
|
||||
assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 0));
|
||||
assert!(!player.receive(state.clone(), Ipv4Addr::LOCALHOST, 1));
|
||||
} else {
|
||||
assert!(player.receive(state.clone(), Ipv4Addr::LOCALHOST, 0));
|
||||
assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 1));
|
||||
}
|
||||
assert_eq!(player.view(1).phase, "finished");
|
||||
assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1400));
|
||||
assert!(!player.view(1500).connected, "重复回执不能续约");
|
||||
assert!(!player.receive_result(
|
||||
protocol::MatchResult {
|
||||
outcomes: [2, 1],
|
||||
..result
|
||||
},
|
||||
Ipv4Addr::LOCALHOST,
|
||||
1501
|
||||
));
|
||||
assert!(!player.receive_result(result, Ipv4Addr::new(1, 2, 3, 4), 1501));
|
||||
referee.action(MatchAction::Reset, 2200).unwrap();
|
||||
let reset = referee.broadcast(2200).unwrap();
|
||||
assert!(player.receive(reset, Ipv4Addr::LOCALHOST, 1600));
|
||||
assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1601));
|
||||
assert!(player.result.is_none());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn preparation_waits_for_referee_then_countdown_carries_excess_time() {
|
||||
let mut c = MatchClock::new(true, 1, 0);
|
||||
@@ -315,6 +539,71 @@ mod tests {
|
||||
assert_eq!((v.phase, v.elapsed_ms), ("finished", 180_000));
|
||||
}
|
||||
#[test]
|
||||
fn skip_preparation_waits_for_confirmation_and_syncs_without_changing_session() {
|
||||
let mut c = MatchClock::new(true, 44, 0);
|
||||
assert!(c.action(MatchAction::SkipPreparation, 0).is_err());
|
||||
c.action(MatchAction::Prepare, 0).unwrap();
|
||||
c.action(MatchAction::SkipPreparation, 1000).unwrap();
|
||||
let packet = c.broadcast(1000).unwrap();
|
||||
assert_eq!(
|
||||
(packet.phase, packet.remaining_ms, packet.elapsed_ms),
|
||||
(2, 0, 0)
|
||||
);
|
||||
let mut follower = MatchClock::new(false, 2, 0);
|
||||
assert!(follower.receive(packet.clone(), Ipv4Addr::LOCALHOST, 1000));
|
||||
assert_eq!(follower.view(1000).phase, "ready");
|
||||
assert!(follower.action(MatchAction::SkipPreparation, 1000).is_err());
|
||||
assert_eq!(c.view(200_000).phase, "ready");
|
||||
// 重复操作、准备刚好自然结束时均保持待开赛。
|
||||
c.action(MatchAction::SkipPreparation, 200_000).unwrap();
|
||||
c.action(MatchAction::Countdown { seconds: 5 }, 200_000)
|
||||
.unwrap();
|
||||
assert!(c.action(MatchAction::SkipPreparation, 201_000).is_err());
|
||||
assert_eq!(c.view(205_000).phase, "running");
|
||||
assert!(c.action(MatchAction::SkipPreparation, 205_000).is_err());
|
||||
let later = c.broadcast(205_000).unwrap();
|
||||
assert_eq!(later.session, packet.session);
|
||||
assert!(later.sequence > packet.sequence);
|
||||
assert!(follower.receive(later, Ipv4Addr::LOCALHOST, 205_000));
|
||||
assert!(!follower.receive(packet, Ipv4Addr::LOCALHOST, 205_000));
|
||||
assert_eq!(follower.view(205_000).phase, "running");
|
||||
}
|
||||
#[test]
|
||||
fn reset_after_a_verdict_stops_the_match_then_clears_all_round_state() {
|
||||
let mut c = MatchClock::new(true, 44, 0);
|
||||
ready(&mut c);
|
||||
c.action(MatchAction::Countdown { seconds: 1 }, 180_000)
|
||||
.unwrap();
|
||||
assert!(c.begin_reset(false, 185_000).is_err());
|
||||
c.action(
|
||||
MatchAction::PauseOfficial {
|
||||
reason: "检查".into(),
|
||||
},
|
||||
185_000,
|
||||
)
|
||||
.unwrap();
|
||||
let stopped = c.begin_reset(true, 186_000).unwrap();
|
||||
assert_eq!((stopped.phase, stopped.pause_kind), (6, 0));
|
||||
assert_eq!(c.view(190_000).elapsed_ms, 4000);
|
||||
c.action(MatchAction::Reset, 190_000).unwrap();
|
||||
let state = c.broadcast(190_000).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
state.phase,
|
||||
state.remaining_ms,
|
||||
state.elapsed_ms,
|
||||
state.pause_elapsed_ms
|
||||
),
|
||||
(0, 0, 0, 0)
|
||||
);
|
||||
assert_eq!(state.resume_phase, 0);
|
||||
assert!(state.reason.is_empty());
|
||||
assert_eq!(state.session, stopped.session);
|
||||
assert!(state.sequence > stopped.sequence);
|
||||
assert!(state.valid());
|
||||
assert!(MatchClock::new(false, 1, 0).begin_reset(true, 0).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn pause_approval_freezes_time_and_expiry_never_resumes() {
|
||||
let mut c = MatchClock::new(true, 1, 0);
|
||||
c.action(MatchAction::Prepare, 0).unwrap();
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
//! 镜像使用独立的组播监听。同机多实例均可收到消息,不争用装甲板单播回执端口。
|
||||
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
|
||||
use std::time::Duration;
|
||||
pub const GROUP: Ipv4Addr = Ipv4Addr::new(239, 255, 56, 2);
|
||||
pub const PORT: u16 = 5602;
|
||||
pub fn bind() -> std::io::Result<UdpSocket> {
|
||||
let socket = socket2::Socket::new(
|
||||
socket2::Domain::IPV4,
|
||||
socket2::Type::DGRAM,
|
||||
Some(socket2::Protocol::UDP),
|
||||
)?;
|
||||
socket.set_reuse_address(true)?;
|
||||
socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, PORT).into())?;
|
||||
let socket: UdpSocket = socket.into();
|
||||
socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?;
|
||||
socket.set_multicast_loop_v4(true)?;
|
||||
socket.set_multicast_ttl_v4(1)?;
|
||||
socket.set_read_timeout(Some(Duration::from_millis(200)))?;
|
||||
socket.set_write_timeout(Some(Duration::from_millis(10)))?;
|
||||
Ok(socket)
|
||||
}
|
||||
pub fn spawn(
|
||||
socket: UdpSocket,
|
||||
sink: impl Fn(protocol::CameraMirror) + Send + 'static,
|
||||
) -> std::io::Result<()> {
|
||||
std::thread::Builder::new()
|
||||
.name("mirror-reader".into())
|
||||
.spawn(move || {
|
||||
let mut bytes = [0u8; 128];
|
||||
loop {
|
||||
match socket.recv_from(&mut bytes) {
|
||||
Ok((len, _)) => {
|
||||
if let Some(packet) = protocol::CameraMirror::decode(&bytes[..len]) {
|
||||
sink(packet);
|
||||
}
|
||||
}
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
|
||||
) => {}
|
||||
Err(_) => std::thread::sleep(Duration::from_millis(200)),
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -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,10 +385,13 @@ pub struct SlotsDto {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Snapshot {
|
||||
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||
pub operator_control: crate::operator::OperatorView,
|
||||
pub match_clock: crate::match_clock::MatchView,
|
||||
pub role: Role,
|
||||
pub team: u8,
|
||||
pub mirrored: bool,
|
||||
pub mirrored_vertical: bool,
|
||||
/// 演示模式:画面与血量是本地合成的,不是场上的板子。界面必须把它显示出来,
|
||||
/// 否则截图与验收会被误读成真实链路。
|
||||
pub demo: bool,
|
||||
@@ -436,6 +439,7 @@ pub struct ConfigView {
|
||||
pub armor_id: Option<u32>,
|
||||
pub armor_id_text: Option<String>,
|
||||
pub mirror: bool,
|
||||
pub mirror_vertical: bool,
|
||||
pub password_set: bool,
|
||||
pub hud: HudView,
|
||||
pub recording_dir: String,
|
||||
@@ -465,6 +469,7 @@ impl From<&Config> for ConfigView {
|
||||
armor_id: config.armor_id,
|
||||
armor_id_text: config.armor_id.map(id_text),
|
||||
mirror: config.mirror,
|
||||
mirror_vertical: config.mirror_vertical,
|
||||
password_set: config.password.is_some(),
|
||||
hud: HudView {
|
||||
health: config.hud.health.clone(),
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
use cam_core::armor::{ArmorBoard, ArmorHealthStore, ArmorReport};
|
||||
use cam_core::armor_reset::ArmorResetTracker;
|
||||
use cam_core::match_clock::{MatchAction, MatchClock};
|
||||
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn board(id: u32) -> ArmorBoard {
|
||||
ArmorBoard {
|
||||
id,
|
||||
addr: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 41000 + id as u16),
|
||||
team: (id - 1) as u8,
|
||||
hp: 0,
|
||||
plates_seen: 15,
|
||||
last_seen: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_reset_needs_matching_ack_and_four_fresh_full_health_reports() {
|
||||
let mut clock = MatchClock::new(true, 1, 0);
|
||||
let state = clock.begin_reset(true, 0).unwrap();
|
||||
let boards = [board(1), board(2)];
|
||||
let mut reset = ArmorResetTracker::new(&state, [Some(1), Some(2)], &boards).unwrap();
|
||||
let packets = reset.packets(&state);
|
||||
let (request, addr) = packets[0];
|
||||
let ack = protocol::ArmorReset {
|
||||
acknowledged: true,
|
||||
..request
|
||||
};
|
||||
let report = |index, hp| ArmorReport {
|
||||
board: 1,
|
||||
addr,
|
||||
team: 0,
|
||||
index,
|
||||
hp,
|
||||
};
|
||||
for index in 0..4 {
|
||||
reset.observe(&report(index, 100));
|
||||
}
|
||||
assert_eq!(reset.waiting(), [1, 2], "满血本身不能冒充复位回执");
|
||||
reset.acknowledge(ack, boards[1].addr);
|
||||
reset.acknowledge(protocol::ArmorReset { session: 2, ..ack }, addr);
|
||||
reset.acknowledge(protocol::ArmorReset { reset_id: 2, ..ack }, addr);
|
||||
reset.acknowledge(
|
||||
protocol::ArmorReset {
|
||||
sequence: state.sequence + 1,
|
||||
..ack
|
||||
},
|
||||
addr,
|
||||
);
|
||||
assert_eq!(reset.packets(&state).len(), 2);
|
||||
reset.acknowledge(ack, addr);
|
||||
for index in 0..3 {
|
||||
reset.observe(&report(index, 100));
|
||||
}
|
||||
assert_eq!(reset.waiting(), [1, 2]);
|
||||
reset.observe(&report(3, 0));
|
||||
reset.observe(&report(3, 100));
|
||||
assert_eq!(reset.waiting(), [1, 2], "非满血读数会清除这一轮确认");
|
||||
for index in 0..3 {
|
||||
reset.observe(&report(index, 100));
|
||||
}
|
||||
assert_eq!(reset.waiting(), [2], "一块完成不能掩盖另一块失败");
|
||||
assert_eq!(reset.packets(&state).len(), 1, "已回执的主板不再补血");
|
||||
assert!(ArmorResetTracker::new(&state, [Some(1), Some(1)], &boards).is_err());
|
||||
let mut offline = board(1);
|
||||
offline.last_seen -= Duration::from_secs(2);
|
||||
assert!(ArmorResetTracker::new(&state, [Some(1), None], &[offline]).is_err());
|
||||
clock.action(MatchAction::Reset, 0).unwrap();
|
||||
assert!(reset.packets(&clock.broadcast(0).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_reset_retries_lost_request_and_waits_for_real_ack_and_health() {
|
||||
let client = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let board = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
client
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
board
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
let store = ArmorHealthStore::new();
|
||||
store.datagram(
|
||||
&protocol::ArmorHealth {
|
||||
team: 0,
|
||||
index: 0,
|
||||
hp: 0,
|
||||
}
|
||||
.encode_from(17),
|
||||
board.local_addr().unwrap(),
|
||||
);
|
||||
let mut clock = MatchClock::new(true, 88, 0);
|
||||
let state = clock.begin_reset(true, 0).unwrap();
|
||||
store.begin_reset(&state, [Some(17), None]).unwrap();
|
||||
let mut bytes = [0; 128];
|
||||
// 首次请求丢失;下一次心跳使用新序号及相同 reset_id 重试。
|
||||
store.send_reset_controls(&client, &state).unwrap();
|
||||
let (n, _) = board.recv_from(&mut bytes).unwrap();
|
||||
let dropped = protocol::ArmorReset::decode(&bytes[..n]).unwrap();
|
||||
let later = clock.broadcast(200).unwrap();
|
||||
store
|
||||
.send_damage_controls(&client, &later, [Some(17), None])
|
||||
.unwrap();
|
||||
let (n, _) = board.recv_from(&mut bytes).unwrap();
|
||||
assert!(
|
||||
!protocol::ArmorDamageControl::decode(&bytes[..n])
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
store.send_reset_controls(&client, &later).unwrap();
|
||||
let (n, from) = board.recv_from(&mut bytes).unwrap();
|
||||
let request = protocol::ArmorReset::decode(&bytes[..n]).unwrap();
|
||||
assert_eq!(request.reset_id, dropped.reset_id);
|
||||
assert!(request.sequence > dropped.sequence);
|
||||
assert_eq!(store.reset_waiting(), [17]);
|
||||
let ack = protocol::ArmorReset {
|
||||
acknowledged: true,
|
||||
..request
|
||||
}
|
||||
.encode()
|
||||
.unwrap();
|
||||
board.send_to(&ack, from).unwrap();
|
||||
let (n, from) = client.recv_from(&mut bytes).unwrap();
|
||||
store.datagram(&bytes[..n], from);
|
||||
assert_eq!(store.reset_waiting(), [17]);
|
||||
assert_eq!(store.health_of_board(17), Some(0), "回执不能伪造血量");
|
||||
for index in 0..4 {
|
||||
board
|
||||
.send_to(
|
||||
&protocol::ArmorHealth {
|
||||
team: 0,
|
||||
index,
|
||||
hp: 100,
|
||||
}
|
||||
.encode_from(17),
|
||||
client.local_addr().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let (n, from) = client.recv_from(&mut bytes).unwrap();
|
||||
store.datagram(&bytes[..n], from);
|
||||
}
|
||||
assert!(store.reset_waiting().is_empty());
|
||||
assert_eq!(store.health_of_board(17), Some(100));
|
||||
store.finish_reset();
|
||||
}
|
||||
@@ -94,3 +94,102 @@ fn udp_snapshot_routes_to_follower_without_polluting_armor_health() {
|
||||
store.datagram(&packet, from);
|
||||
assert_eq!(follower.lock().unwrap().view(1000).remaining_ms, 160_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knockout_revokes_both_boards_and_result_survives_late_winner_death() {
|
||||
let tx = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let store = ArmorHealthStore::new();
|
||||
let boards: Vec<_> = (1..=2)
|
||||
.map(|id| {
|
||||
let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
store.datagram(
|
||||
&protocol::ArmorHealth {
|
||||
team: id - 1,
|
||||
index: 0,
|
||||
hp: 100,
|
||||
}
|
||||
.encode_from(u32::from(id)),
|
||||
socket.local_addr().unwrap(),
|
||||
);
|
||||
socket
|
||||
})
|
||||
.collect();
|
||||
let mut clock = MatchClock::new(true, 80, 0);
|
||||
clock.action(MatchAction::Prepare, 0).unwrap();
|
||||
clock.action(MatchAction::SkipPreparation, 100).unwrap();
|
||||
clock
|
||||
.action(MatchAction::Countdown { seconds: 1 }, 100)
|
||||
.unwrap();
|
||||
let state = clock.broadcast(1100).unwrap();
|
||||
let mut buf = [0; 512];
|
||||
store
|
||||
.send_damage_controls(&tx, &state, [Some(1), Some(2)])
|
||||
.unwrap();
|
||||
for board in &boards {
|
||||
let (n, _) = board.recv_from(&mut buf).unwrap();
|
||||
assert!(
|
||||
protocol::ArmorDamageControl::decode(&buf[..n])
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
}
|
||||
assert!(clock.finish_on_health([Some(0), Some(10)], 2100));
|
||||
let state = clock.broadcast(2100).unwrap();
|
||||
store
|
||||
.send_damage_controls(&tx, &state, [Some(1), Some(2)])
|
||||
.unwrap();
|
||||
for board in &boards {
|
||||
let (n, _) = board.recv_from(&mut buf).unwrap();
|
||||
assert!(
|
||||
!protocol::ArmorDamageControl::decode(&buf[..n])
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
}
|
||||
assert!(!clock.finish_on_health([Some(0), Some(0)], 2200));
|
||||
let follower = Arc::new(Mutex::new(MatchClock::new(false, 2, 0)));
|
||||
let reader = ArmorHealthStore::new();
|
||||
let follow = follower.clone();
|
||||
reader.set_match_result_sink(Arc::new(move |result, ip| {
|
||||
follow.lock().unwrap().receive_result(result, ip, 2100);
|
||||
}));
|
||||
let rx = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
rx.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||||
tx.send_to(
|
||||
&clock.result_packet().unwrap().encode().unwrap(),
|
||||
rx.local_addr().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let (n, from) = rx.recv_from(&mut buf).unwrap();
|
||||
reader.datagram(&buf[..n], from);
|
||||
assert_eq!(follower.lock().unwrap().view(2100).phase, "finished");
|
||||
assert!(reader.boards().is_empty());
|
||||
for (index, board) in boards.iter().enumerate() {
|
||||
reader.datagram(
|
||||
&protocol::ArmorHealth {
|
||||
team: index as u8,
|
||||
index: 0,
|
||||
hp: 0,
|
||||
}
|
||||
.encode_from(index as u32 + 1),
|
||||
board.local_addr().unwrap(),
|
||||
);
|
||||
}
|
||||
let names = ["红队".into(), "蓝队".into()];
|
||||
let mut health = [
|
||||
cam_core::snapshot::TeamHealthDto::present(0, Some(1), [0; 4], 25, &names),
|
||||
cam_core::snapshot::TeamHealthDto::present(1, Some(2), [0; 4], 25, &names),
|
||||
];
|
||||
follower.lock().unwrap().apply_outcomes(&mut health);
|
||||
assert_eq!(
|
||||
health[0].outcome,
|
||||
Some(cam_core::snapshot::MatchOutcome::Defeat)
|
||||
);
|
||||
assert_eq!(
|
||||
health[1].outcome,
|
||||
Some(cam_core::snapshot::MatchOutcome::Victory)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use cam_core::{armor::ArmorHealthStore, camera_mirror::{merge, CameraMirrors}};
|
||||
use std::{net::UdpSocket, sync::{Arc,Mutex}, time::Duration};
|
||||
#[test]
|
||||
fn bidirectional_udp_mirrors_remain_camera_scoped_and_ignore_stale_echoes() {
|
||||
let left=ArmorHealthStore::new();let right=ArmorHealthStore::new();
|
||||
let a=Arc::new(Mutex::new(CameraMirrors::new()));let b=Arc::new(Mutex::new(CameraMirrors::new()));
|
||||
let copy=a.clone();left.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);}));
|
||||
let copy=b.clone();right.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);}));
|
||||
let tx=UdpSocket::bind("127.0.0.1:0").unwrap();let rx=UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
rx.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
|
||||
let transfer=|packet:protocol::CameraMirror,store:&ArmorHealthStore|{
|
||||
tx.send_to(&packet.encode().unwrap(),rx.local_addr().unwrap()).unwrap();let mut buf=[0;128];let(n,from)=rx.recv_from(&mut buf).unwrap();store.datagram(&buf[..n],from);
|
||||
};
|
||||
let first=protocol::CameraMirror{camera_id:17,revision:1,origin:3,mirror:true,mirror_vertical:true};
|
||||
transfer(first,&right);
|
||||
let second=protocol::CameraMirror{revision:2,origin:4,mirror:false,..first};
|
||||
transfer(second,&left);transfer(second,&right);transfer(first,&left);
|
||||
assert_eq!(*a.lock().unwrap(),*b.lock().unwrap());assert!(!a.lock().unwrap()["17"].mirror);
|
||||
transfer(protocol::CameraMirror{camera_id:18,..first},&right);
|
||||
assert_eq!(a.lock().unwrap().len(),1);assert_eq!(b.lock().unwrap().len(),2);
|
||||
assert!(left.boards().is_empty());assert!(right.boards().is_empty());
|
||||
}
|
||||
+5
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "rmic-2026",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.1",
|
||||
"type": "module",
|
||||
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
||||
"scripts": {
|
||||
@@ -9,6 +9,7 @@
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri",
|
||||
"bundle:windows": "pwsh -NoProfile -File scripts/build-windows-release.ps1",
|
||||
"app": "tauri dev",
|
||||
"check": "tsc --noEmit",
|
||||
"version:write": "node ../scripts/version.mjs --write",
|
||||
@@ -16,6 +17,9 @@
|
||||
"test:stream": "node --test scripts/test-stream.mjs",
|
||||
"test:latency": "node --test scripts/test-latency-marker.mjs",
|
||||
"test:match": "node --test scripts/test-match-clock.mjs",
|
||||
"test:mirror-instances": "node scripts/test-mirror-instances.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:maintenance": "node --test scripts/test-maintenance.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#requires -Version 7.4
|
||||
# Build with Tauri's native Authenticode signing support. No private keys or
|
||||
# personal signing identities are stored in the shared Tauri configuration.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$CertificateThumbprint = $env:RMIC_WINDOWS_CERT_THUMBPRINT,
|
||||
[string]$TimestampUrl = 'http://timestamp.digicert.com',
|
||||
[switch]$AllowUnsigned,
|
||||
[switch]$PreflightOnly,
|
||||
[string]$SigningConfigPath = $env:RMIC_WINDOWS_SIGNING_CONFIG,
|
||||
[string]$OutputDirectory
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$clientRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$repoRoot = Split-Path -Parent $clientRoot
|
||||
if (-not $SigningConfigPath) { $SigningConfigPath = Join-Path $env:LOCALAPPDATA 'RMIC-2026/signing/windows.json' }
|
||||
if (-not $CertificateThumbprint -and -not $AllowUnsigned) {
|
||||
if ($PreflightOnly -and -not (Test-Path -LiteralPath $SigningConfigPath)) {
|
||||
throw 'A code-signing certificate is required. Initialize the local signing identity before a read-only preflight.'
|
||||
}
|
||||
$identity = & (Join-Path $PSScriptRoot 'initialize-windows-signing.ps1') -ConfigPath $SigningConfigPath
|
||||
$CertificateThumbprint = $identity.certificateThumbprint
|
||||
}
|
||||
$thumbprint = ($CertificateThumbprint -replace '\s', '').ToUpperInvariant()
|
||||
$signed = $thumbprint.Length -gt 0
|
||||
$selfSigned = $false
|
||||
if ($signed) {
|
||||
if ($thumbprint -notmatch '^[0-9A-F]{40}$') { throw 'Invalid code-signing certificate thumbprint.' }
|
||||
$certificate = Get-Item -LiteralPath "Cert:\CurrentUser\My\$thumbprint" -ErrorAction SilentlyContinue
|
||||
if (-not $certificate) { throw 'Code-signing certificate was not found in CurrentUser/My.' }
|
||||
$now = Get-Date
|
||||
if (-not $certificate.HasPrivateKey -or $certificate.NotBefore -gt $now -or $certificate.NotAfter -le $now) {
|
||||
throw 'The signing certificate needs an accessible private key and must be currently valid.'
|
||||
}
|
||||
$selfSigned = [Convert]::ToBase64String($certificate.SubjectName.RawData) -eq [Convert]::ToBase64String($certificate.IssuerName.RawData)
|
||||
$usageOids = @($certificate.Extensions |
|
||||
Where-Object { $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } |
|
||||
ForEach-Object { $_.EnhancedKeyUsages } | ForEach-Object { $_.Value })
|
||||
if ('1.3.6.1.5.5.7.3.3' -notin $usageOids) {
|
||||
throw 'The certificate is not authorized for code signing.'
|
||||
}
|
||||
} elseif (-not $AllowUnsigned) {
|
||||
throw 'A code-signing certificate is required. Set RMIC_WINDOWS_CERT_THUMBPRINT or explicitly use -AllowUnsigned for a test package.'
|
||||
}
|
||||
$timestamp = $null
|
||||
if (-not [Uri]::TryCreate($TimestampUrl, [UriKind]::Absolute, [ref]$timestamp) -or
|
||||
$timestamp.Scheme -notin @('http', 'https') -or -not $timestamp.Host -or $timestamp.UserInfo) {
|
||||
throw 'Timestamp URL must be an HTTP(S) server without credentials.'
|
||||
}
|
||||
if ($PreflightOnly) {
|
||||
[pscustomobject]@{ signing = $signed; selfSigned = $selfSigned; certificateThumbprint = $thumbprint;
|
||||
unsignedExplicitlyAllowed = [bool]$AllowUnsigned; digestAlgorithm = $(if ($signed) { 'sha256' } else { $null }); tsp = $signed }
|
||||
return
|
||||
}
|
||||
|
||||
& (Join-Path $PSScriptRoot 'prepare-windows-bundle.ps1') -CheckProcessOnly
|
||||
& node (Join-Path $repoRoot 'scripts/version.mjs') --check
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Regenerate versions before packaging.' }
|
||||
$version = Get-Content -LiteralPath (Join-Path $repoRoot 'version.json') -Raw | ConvertFrom-Json
|
||||
$label = "v$($version.version)+$($version.build)"
|
||||
if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repoRoot "target/releases/$label" }
|
||||
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
|
||||
New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
|
||||
$temporaryConfig = Join-Path $OutputDirectory 'windows-signing.local.json'
|
||||
$windows = if ($signed) {
|
||||
@{ certificateThumbprint = $thumbprint; digestAlgorithm = 'sha256'; timestampUrl = $TimestampUrl; tsp = $true }
|
||||
} else {
|
||||
@{ certificateThumbprint = $null; digestAlgorithm = $null; timestampUrl = $null; tsp = $false; signCommand = $null }
|
||||
}
|
||||
$utf8 = New-Object Text.UTF8Encoding($false)
|
||||
[IO.File]::WriteAllText($temporaryConfig, (@{ bundle = @{ windows = $windows } } | ConvertTo-Json -Depth 6), $utf8)
|
||||
$previousTarget = $env:CARGO_TARGET_DIR
|
||||
$previousToolchain = $env:RUSTUP_TOOLCHAIN
|
||||
try {
|
||||
Remove-Item Env:CARGO_TARGET_DIR -ErrorAction SilentlyContinue
|
||||
$env:RUSTUP_TOOLCHAIN = 'stable'
|
||||
Push-Location $clientRoot
|
||||
try {
|
||||
& pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci --config $temporaryConfig -- --locked --config 'unstable.build-std=[]'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows build or signing failed; no verified installer was delivered.' }
|
||||
& (Join-Path $PSScriptRoot 'prepare-windows-bundle.ps1') -CheckOnly
|
||||
$metadata = (& cargo +stable metadata --no-deps --format-version 1 --manifest-path src-tauri/Cargo.toml | ConvertFrom-Json)
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve Cargo output path.' }
|
||||
} finally { Pop-Location }
|
||||
$release = Join-Path $metadata.target_directory 'x86_64-pc-windows-msvc/release'
|
||||
$main = Join-Path $release 'cam-desktop.exe'
|
||||
$installer = Join-Path $release "bundle/nsis/RMIC-2026_$($version.version)_x64-setup.exe"
|
||||
if ($signed) {
|
||||
# Tauri signs the bundled copy, then can restore the original standalone
|
||||
# executable. Sign that final output too, using the same identity.
|
||||
$signTool = Get-Command signtool.exe -ErrorAction SilentlyContinue
|
||||
$signToolPath = if ($signTool) { $signTool.Source } else { $null }
|
||||
if (-not $signToolPath) {
|
||||
$sdkRoot = (Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots' -Name KitsRoot10).KitsRoot10
|
||||
$sdkVersions = Get-ChildItem -LiteralPath (Join-Path $sdkRoot 'bin') -Directory |
|
||||
Where-Object Name -Match '^\d+\.\d+\.\d+\.\d+$' | Sort-Object { [version]$_.Name } -Descending
|
||||
foreach ($sdk in $sdkVersions) {
|
||||
$candidate = Join-Path $sdk.FullName 'x64/signtool.exe'
|
||||
if (Test-Path -LiteralPath $candidate) { $signToolPath = $candidate; break }
|
||||
}
|
||||
}
|
||||
if (-not $signToolPath) { throw 'Windows SDK signtool.exe is required to sign the final standalone executable.' }
|
||||
& $signToolPath sign /sha1 $thumbprint /s My /fd SHA256 /tr $TimestampUrl /td SHA256 /d RMIC-2026 $main
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Signing the final standalone executable failed.' }
|
||||
}
|
||||
$signatures = @()
|
||||
foreach ($file in @($main, $installer)) {
|
||||
$signature = Get-AuthenticodeSignature -LiteralPath $file
|
||||
if ($signed) {
|
||||
$signatures += & (Join-Path $PSScriptRoot 'verify-windows-signature.ps1') -Path $file -CertificateThumbprint $thumbprint -SelfSigned:$selfSigned
|
||||
} else {
|
||||
if ($signature.Status -ne 'NotSigned') { throw "Unexpected signature on explicitly unsigned output: $file" }
|
||||
$signatures += @{ file = [IO.Path]::GetFileName($file); status = [string]$signature.Status; timestamped = $false }
|
||||
}
|
||||
}
|
||||
$suffix = if ($selfSigned) { '-self-signed' } elseif ($signed) { '' } else { '-unsigned' }
|
||||
$delivery = Join-Path $OutputDirectory "RMIC-2026_${label}_windows-x64${suffix}-setup.exe"
|
||||
Copy-Item -LiteralPath $installer -Destination $delivery
|
||||
& icacls.exe $delivery /setintegritylevel M | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot set installer Medium integrity label.' }
|
||||
$hash = (Get-FileHash -LiteralPath $delivery -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
[IO.File]::WriteAllText("$delivery.sha256", "$hash $([IO.Path]::GetFileName($delivery))`n", $utf8)
|
||||
$publicCertificate = $null
|
||||
if ($signed) {
|
||||
$certPath = Join-Path $OutputDirectory 'RMIC-2026-codesign.cer'
|
||||
[IO.File]::WriteAllBytes($certPath, $certificate.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert))
|
||||
$publicCertificate = @{ file = 'RMIC-2026-codesign.cer'; subject = $certificate.Subject;
|
||||
expiresUtc = $certificate.NotAfter.ToUniversalTime().ToString('o');
|
||||
sha256 = (Get-FileHash -LiteralPath $certPath -Algorithm SHA256).Hash.ToLowerInvariant() }
|
||||
}
|
||||
$report = @{ version = $label; installer = $delivery; sha256 = $hash; signed = $signed;
|
||||
selfSigned = $selfSigned; certificateThumbprint = $thumbprint;
|
||||
publicCertificate = $publicCertificate;
|
||||
signatures = $signatures; smartScreenReputationVerified = $false }
|
||||
[IO.File]::WriteAllText((Join-Path $OutputDirectory 'windows-signature-verification.json'), ($report | ConvertTo-Json -Depth 6), $utf8)
|
||||
$report | ConvertTo-Json -Depth 6
|
||||
} finally {
|
||||
# This config contains a personal public certificate identity, and is local only.
|
||||
Remove-Item -LiteralPath $temporaryConfig -ErrorAction SilentlyContinue
|
||||
if ($null -eq $previousTarget) { Remove-Item Env:CARGO_TARGET_DIR -ErrorAction SilentlyContinue } else { $env:CARGO_TARGET_DIR = $previousTarget }
|
||||
if ($null -eq $previousToolchain) { Remove-Item Env:RUSTUP_TOOLCHAIN -ErrorAction SilentlyContinue } else { $env:RUSTUP_TOOLCHAIN = $previousToolchain }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#requires -Version 7.4
|
||||
# Keep the non-exportable private key in CurrentUser/My. Never install a root.
|
||||
[CmdletBinding()]
|
||||
param([string]$ConfigPath = $env:RMIC_WINDOWS_SIGNING_CONFIG)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
if (-not $ConfigPath) { $ConfigPath = Join-Path $env:LOCALAPPDATA 'RMIC-2026/signing/windows.json' }
|
||||
if (Test-Path -LiteralPath $ConfigPath) {
|
||||
$saved = Get-Content -LiteralPath $ConfigPath -Raw | ConvertFrom-Json
|
||||
if ($saved.schema -ne 1 -or $saved.certificateThumbprint -notmatch '^[0-9A-F]{40}$') {
|
||||
throw 'Invalid saved Windows signing identity. Restore the local signing configuration.'
|
||||
}
|
||||
$cert = Get-Item -LiteralPath "Cert:\CurrentUser\My\$($saved.certificateThumbprint)" -ErrorAction SilentlyContinue
|
||||
if (-not $cert -or -not $cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)) {
|
||||
throw 'Saved signing certificate/key is missing or expired. Restore the original identity or explicitly provision a replacement; it will not be silently rotated.'
|
||||
}
|
||||
$saved
|
||||
return
|
||||
}
|
||||
$existing = @(Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object FriendlyName -eq 'RMIC-2026 self-signed code signing')
|
||||
if ($existing.Count -gt 1) { throw 'Multiple RMIC signing identities exist. Select one explicitly with RMIC_WINDOWS_CERT_THUMBPRINT.' }
|
||||
if ($existing.Count -eq 1) {
|
||||
$cert = $existing[0]
|
||||
if (-not $cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)) { throw 'Existing RMIC signing identity is unusable; provision a replacement explicitly.' }
|
||||
} else {
|
||||
$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject 'CN=RMIC-2026 Self-signed Code Signing' `
|
||||
-FriendlyName 'RMIC-2026 self-signed code signing' -KeyAlgorithm RSA -KeyLength 3072 `
|
||||
-HashAlgorithm SHA256 -KeyUsage DigitalSignature -KeyExportPolicy NonExportable `
|
||||
-Provider 'Microsoft Software Key Storage Provider' -CertStoreLocation 'Cert:\CurrentUser\My' `
|
||||
-NotBefore (Get-Date).AddMinutes(-5) -NotAfter (Get-Date).AddYears(3)
|
||||
}
|
||||
$saved = [ordered]@{ schema = 1; certificateThumbprint = $cert.Thumbprint; kind = 'self-signed';
|
||||
subject = $cert.Subject; expiresUtc = $cert.NotAfter.ToUniversalTime().ToString('o') }
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path -Parent ([IO.Path]::GetFullPath($ConfigPath))) | Out-Null
|
||||
[IO.File]::WriteAllText([IO.Path]::GetFullPath($ConfigPath), ($saved | ConvertTo-Json), [Text.UTF8Encoding]::new($false))
|
||||
[pscustomobject]$saved
|
||||
@@ -0,0 +1,68 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import net from 'node:net';
|
||||
const repo=fileURLToPath(new URL('../../',import.meta.url));
|
||||
const folder=path.join(repo,'target',`mirror-instances-${Date.now()}-${process.pid}`);
|
||||
const exe=process.argv[2] ? path.resolve(process.argv[2]) : path.join(repo,'client/src-tauri/target/x86_64-pc-windows-msvc/debug/cam-desktop.exe');
|
||||
await fs.access(exe);await fs.mkdir(folder,{recursive:true});
|
||||
await fs.writeFile(path.join(folder,'team.toml'),'role = "team"\nroleChosen = false\ncameraId = "0x0DE00001"\nmirror = true\nmirrorVertical = false\n');
|
||||
await fs.writeFile(path.join(folder,'referee.toml'),'role = "referee"\nroleChosen = false\nmirror = true\nmirrorVertical = false\n[referee]\nmanualSlots = true\nslotA = "0x0DE00001"\nslotB = "0x0DE00002"\n');
|
||||
const freePort=()=>new Promise((resolve,reject)=>{const s=net.createServer();s.on('error',reject);s.listen(0,'127.0.0.1',()=>{const port=s.address().port;s.close(()=>resolve(port));});});
|
||||
const ports={team:await freePort(),referee:await freePort()};
|
||||
const pids={};
|
||||
const clients={};const results=[];const pause=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
async function connect(name){
|
||||
const port=ports[name];
|
||||
for(let attempt=0;attempt<80;attempt++)try{
|
||||
const tabs=await(await fetch(`http://127.0.0.1:${port}/json`)).json();
|
||||
const tab=tabs.find(t=>t.type==='page'&&!t.url.startsWith('devtools:'));
|
||||
if(!tab)throw Error('page loading');
|
||||
const ws=new WebSocket(tab.webSocketDebuggerUrl);await new Promise(r=>ws.addEventListener('open',r,{once:true}));
|
||||
let seq=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id){pending.get(m.id)?.(m);pending.delete(m.id);}};
|
||||
const run=expression=>new Promise((resolve,reject)=>{const id=++seq;pending.set(id,m=>{if(m.error||m.result?.exceptionDetails)reject(Error(JSON.stringify(m)));else resolve(m.result.result.value);});ws.send(JSON.stringify({id,method:'Runtime.evaluate',params:{expression,awaitPromise:true,returnByValue:true}}));});
|
||||
clients[name]={ws,run,invoke:(command,args={})=>run(`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(command)},${JSON.stringify(args)})`)};
|
||||
await clients[name].invoke('get_snapshot');return;
|
||||
}catch(e){if(attempt===79)throw e;await pause(250);}
|
||||
}
|
||||
const snap=name=>clients[name].invoke('get_snapshot');
|
||||
const set=(name,camera,mirror,mirrorVertical)=>clients[name].invoke('set_camera_mirror',{camera,mirror,mirrorVertical});
|
||||
const A=0x0de00001,B=0x0de00002;
|
||||
async function waitFor(check,label){for(let n=0;n<60;n++){if(await check()){results.push(label);return;}await pause(100);}throw Error(`Timeout: ${label}`);}
|
||||
async function agree(camera,mirror,vertical){const[a,b]=await Promise.all([snap('team'),snap('referee')]);const x=a.cameraMirrors[camera],y=b.cameraMirrors[camera];return !!x&&!!y&&x.revision===y.revision&&x.origin===y.origin&&x.mirror===y.mirror&&x.mirrorVertical===y.mirrorVertical&&(mirror===undefined||x.mirror===mirror)&&(vertical===undefined||x.mirrorVertical===vertical);}
|
||||
async function stop(name){clients[name]?.ws.close();try{process.kill(pids[name]);}catch{}await pause(800);}
|
||||
async function restart(name){
|
||||
const env={...process.env,WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS:`--remote-debugging-port=${ports[name]}`,WEBVIEW2_USER_DATA_FOLDER:path.join(folder,name+'-webview')};
|
||||
const child=spawn(exe,['--config',path.join(folder,name+'.toml')],{env,windowsHide:true,stdio:'ignore'});pids[name]=child.pid;
|
||||
await fs.writeFile(path.join(folder,'pids.json'),JSON.stringify(pids));await connect(name);
|
||||
}
|
||||
try{
|
||||
await Promise.all([restart('team'),restart('referee')]);
|
||||
for(const name of ['team','referee'])assert.equal((await snap(name)).config.roleChosen,false,'isolated fixtures must never broadcast official match states');
|
||||
assert.equal((await snap('referee')).slots.cameraA,A);assert.equal((await snap('referee')).slots.cameraB,B);
|
||||
await set('team',A,false,true);await waitFor(()=>agree(A,false,true),'player A → referee A');
|
||||
await set('referee',B,false,false);await pause(500);
|
||||
assert.equal((await snap('team')).cameraMirrors[B],undefined);assert.equal((await snap('referee')).cameraMirrors[A].mirrorVertical,true);results.push('B independent of A, player ignores unbound B');
|
||||
await set('referee',A,true,false);await waitFor(()=>agree(A,true,false),'referee A → player A');
|
||||
for(let n=0;n<12;n++){
|
||||
await Promise.all([set('team',A,false,!!(n%2)),set('referee',A,true,!(n%2))]);
|
||||
await waitFor(()=>agree(A),`concurrent edit ${n+1} converges`);
|
||||
}
|
||||
await stop('team');await set('referee',A,false,true);await restart('team');
|
||||
await waitFor(()=>agree(A,false,true),'player restart catches newer referee revision');
|
||||
await stop('referee');await set('team',A,true,false);await restart('referee');
|
||||
await waitFor(()=>agree(A,true,false),'referee restart catches newer player revision');
|
||||
assert.equal((await snap('referee')).cameraMirrors[B].mirror,false);results.push('B persists through referee restart');
|
||||
await stop('team');let config=await fs.readFile(path.join(folder,'team.toml'),'utf8');config=config.replace('cameraId = "0x0DE00001"','cameraId = "0x0DE00002"');await fs.writeFile(path.join(folder,'team.toml'),config);await restart('team');
|
||||
assert.equal((await snap('team')).config.cameraId,B);
|
||||
await set('team',B,true,true);await waitFor(()=>agree(B,true,true),'player rebound to B → referee B');
|
||||
assert.equal((await snap('referee')).cameraMirrors[A].mirror,true);assert.equal((await snap('referee')).cameraMirrors[A].mirrorVertical,false);
|
||||
await set('referee',B,false,true);await waitFor(()=>agree(B,false,true),'referee B → rebound player B');
|
||||
await stop('team');await stop('referee');await Promise.all([restart('team'),restart('referee')]);
|
||||
await waitFor(()=>agree(B,false,true),'both processes restart with consistent persisted state');
|
||||
const final={team:await snap('team'),referee:await snap('referee')};
|
||||
await fs.writeFile(path.join(folder,'report.json'),JSON.stringify({actualNativeProcesses:true,syntheticCameraIds:true,officialClockDisabled:true,results,finalMirrors:{team:final.team.cameraMirrors,referee:final.referee.cameraMirrors}},null,2));
|
||||
console.log(JSON.stringify({passed:results.length,report:path.join(folder,'report.json'),results},null,2));
|
||||
}finally{for(const name of ['team','referee'])await stop(name);}
|
||||
@@ -19,16 +19,19 @@ function load(path, overrides) {
|
||||
}
|
||||
|
||||
const format = { teamColor: team => team === 0 ? "red" : "blue", teamName: team => `队伍${team}`, idText: String, firmwareLabel: () => "测试固件" };
|
||||
const icon = { Icon: () => null };
|
||||
const healthModule = load("../src/components/HealthBar.tsx", { "../lib/format": format });
|
||||
const videoModule = load("../src/components/VideoSurface.tsx", { "../lib/store": {}, "../lib/reticle": {} });
|
||||
const videoModule = load("../src/components/VideoSurface.tsx", { "../lib/store": {}, "../lib/reticle": {}, "./Icon": icon });
|
||||
let connected = true;
|
||||
const matchTime = load("../src/lib/match-time.ts", {});
|
||||
const matchModule = load("../src/components/MatchClock.tsx", {
|
||||
"./Dialog": {}, "../lib/ipc": {},
|
||||
"./Dialog": {}, "./Icon": icon, "../lib/ipc": {},
|
||||
"../lib/store": { useAppStore: () => ({ connected }) },
|
||||
"../lib/match-time": matchTime,
|
||||
});
|
||||
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/VideoSurface": videoModule,
|
||||
"../components/HitFlash": { HitFlash: () => null },
|
||||
@@ -69,6 +72,21 @@ test("the low-health marker uses the exact threshold in the track's mirrored coo
|
||||
}
|
||||
});
|
||||
|
||||
test("critical health preserves each team's color for name, number, fill and border", () => {
|
||||
for (const [team, color] of [[0, "red"], [1, "blue"]]) {
|
||||
for (const hp of [30, 1, 0]) {
|
||||
const html = renderToStaticMarkup(createElement(healthModule.HealthBar, {
|
||||
health: { ...health, team, hp, critical: true }, config: { ...config, pulse: true }, align: "right",
|
||||
}));
|
||||
assert.match(html, /hp--critical/);
|
||||
assert.match(html, /hp--pulsing/);
|
||||
assert.match(html, new RegExp(`hp__fill" style="width:${hp}%;background-color:${color}`));
|
||||
assert.match(html, new RegExp(`hp__value num" style="color:${color}"`));
|
||||
assert.doesNotMatch(html, /var\(--error\)/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function snapshot() {
|
||||
return {
|
||||
config: { cameraId: 1, armorId: 2, teamNames: ["我方", "对手"] },
|
||||
@@ -141,3 +159,35 @@ test("an armor outage alone does not gray the live video", () => {
|
||||
value.armorBoards[0].online = false;
|
||||
assert.doesNotMatch(renderTeam(value), /vsurface--signal-lost|vsurface__signal-mask/);
|
||||
});
|
||||
|
||||
const renderControl = (phase, health = []) => renderToStaticMarkup(createElement(matchModule.RefereeMatchControl, {
|
||||
snapshot: { ...snapshot(), config: { teamNames: ["红队", "蓝队"] }, matchClock: { ...snapshot().matchClock, phase }, health },
|
||||
onError() {},
|
||||
}));
|
||||
|
||||
test("skip preparation is available only while preparing and ready still requires confirmation", () => {
|
||||
assert.match(renderControl("preparation"), /跳过准备倒计时/);
|
||||
for (const phase of ["idle", "ready", "countdown", "running", "paused", "finished"]) {
|
||||
assert.doesNotMatch(renderControl(phase), /跳过准备倒计时/);
|
||||
}
|
||||
assert.match(renderControl("ready"), /确认开赛/);
|
||||
});
|
||||
|
||||
test("a verdict exposes one-click reset even before the clock finishes, while ongoing play cannot reset", () => {
|
||||
assert.doesNotMatch(renderControl("running"), /重置到未开始/);
|
||||
assert.match(renderControl("finished"), /重置到未开始/);
|
||||
const verdict = renderControl("running", [{ outcome: "defeat" }, { outcome: "victory" }]);
|
||||
assert.match(verdict, /重置到未开始/);
|
||||
assert.doesNotMatch(verdict, /开始 3 分钟准备|结束本局/);
|
||||
});
|
||||
|
||||
test("the operator feed reports horizontal and vertical mirroring independently", () => {
|
||||
const value = snapshot();
|
||||
value.mirrored = true;
|
||||
assert.match(renderTeam(value), /左右镜像/);
|
||||
assert.doesNotMatch(renderTeam(value), /上下镜像/);
|
||||
value.mirrored = false;
|
||||
value.mirroredVertical = true;
|
||||
assert.match(renderTeam(value), /上下镜像/);
|
||||
assert.doesNotMatch(renderTeam(value), /左右镜像/);
|
||||
});
|
||||
@@ -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()();
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
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/reticle.ts", import.meta.url), "utf8"), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText)(exports);
|
||||
const { aimPoint, computeLayout } = exports;
|
||||
|
||||
test("calibrated aim follows the same image point through all four mirror combinations", () => {
|
||||
const geometry = computeLayout({ clientWidth: 800, clientHeight: 600 }, 640, 480, { zoom: 2, x: 40, y: -30 });
|
||||
const crosshair = { offsetX: 0.1, offsetY: -0.2 };
|
||||
for (const horizontal of [false, true]) {
|
||||
for (const vertical of [false, true]) {
|
||||
const aim = aimPoint(geometry, crosshair, horizontal, 800, 600, vertical);
|
||||
assert.equal(aim.x, horizontal ? 200 : 600);
|
||||
assert.equal(aim.y, vertical ? 570 : 30);
|
||||
// 校准时向右下拖动 16/12 像素,镜像不改变屏幕上的移动方向。
|
||||
const moved = aimPoint(geometry, {
|
||||
offsetX: crosshair.offsetX + (horizontal ? -16 : 16) / geometry.drawWidth,
|
||||
offsetY: crosshair.offsetY + (vertical ? -12 : 12) / geometry.drawHeight,
|
||||
}, horizontal, 800, 600, vertical);
|
||||
assert.ok(Math.abs(moved.x - aim.x - 16) < 1e-9);
|
||||
assert.ok(Math.abs(moved.y - aim.y - 12) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("missing frames keep the aim centered regardless of mirror or offsets", () => {
|
||||
const empty = computeLayout({ clientWidth: 800, clientHeight: 600 }, 0, 0, { zoom: 2, x: 40, y: -30 });
|
||||
assert.deepEqual(aimPoint(empty, { offsetX: 0.2, offsetY: -0.1 }, true, 800, 600, true), { x: 400, y: 300 });
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
[CmdletBinding()]
|
||||
param([string]$SignedFixture, [string]$CertificateThumbprint, [string]$UntimestampedFixture)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$build = Join-Path $PSScriptRoot 'build-windows-release.ps1'
|
||||
function Must-Reject([scriptblock]$Action, [string]$Expected) {
|
||||
$rejected = $false
|
||||
try { & $Action } catch {
|
||||
if ($_.Exception.Message -notmatch $Expected) { throw }
|
||||
$rejected = $true
|
||||
}
|
||||
if (-not $rejected) { throw 'Signing preflight accepted an invalid configuration.' }
|
||||
}
|
||||
Must-Reject { & $build -CertificateThumbprint '' -SigningConfigPath (Join-Path $PSScriptRoot '../target/no-signing-identity.json') -PreflightOnly } 'certificate is required'
|
||||
Must-Reject { & $build -CertificateThumbprint 'not-a-certificate' -AllowUnsigned -PreflightOnly } 'Invalid.*thumbprint'
|
||||
Must-Reject { & $build -CertificateThumbprint ('0' * 40) -AllowUnsigned -PreflightOnly } 'not found'
|
||||
Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'file:///tmp/timestamp' -PreflightOnly } 'Timestamp URL'
|
||||
Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'https://user:secret@example.invalid' -PreflightOnly } 'Timestamp URL'
|
||||
$result = & $build -CertificateThumbprint '' -AllowUnsigned -PreflightOnly
|
||||
if ($result.signing -or -not $result.unsignedExplicitlyAllowed -or $result.digestAlgorithm -or $result.tsp) {
|
||||
throw 'Explicit unsigned preflight returned inconsistent signing metadata.'
|
||||
}
|
||||
Write-Host 'Windows signing preflight: 6 checks passed; no certificates or system settings were changed.'
|
||||
if ($SignedFixture) {
|
||||
if (-not $CertificateThumbprint) { throw 'Integration checks need a pinned fixture certificate thumbprint.' }
|
||||
$verify = Join-Path $PSScriptRoot 'verify-windows-signature.ps1'
|
||||
$verified = & $verify -Path $SignedFixture -CertificateThumbprint $CertificateThumbprint -SelfSigned
|
||||
if (-not $verified.integrityVerified -or -not $verified.timestampVerified -or -not $verified.selfSigned) { throw 'Signed fixture was not verified.' }
|
||||
Must-Reject { & $verify -Path $SignedFixture -CertificateThumbprint ('0' * 40) -SelfSigned } 'Unexpected signing certificate'
|
||||
Must-Reject { & $verify -Path $SignedFixture -CertificateThumbprint $CertificateThumbprint } 'certificate chain is invalid'
|
||||
$tempDir = Join-Path $PSScriptRoot "../target/signing-tests/tamper-$([guid]::NewGuid().ToString('N'))"
|
||||
New-Item -ItemType Directory -Path $tempDir | Out-Null
|
||||
$tampered = Join-Path $tempDir 'tampered.exe'
|
||||
try {
|
||||
$bytes = [IO.File]::ReadAllBytes([IO.Path]::GetFullPath($SignedFixture))
|
||||
$pe = [BitConverter]::ToInt32($bytes, 0x3c)
|
||||
$section = $pe + 24 + [BitConverter]::ToUInt16($bytes, $pe + 20)
|
||||
$codeOffset = [BitConverter]::ToInt32($bytes, $section + 20)
|
||||
$bytes[$codeOffset + 32] = $bytes[$codeOffset + 32] -bxor 1
|
||||
[IO.File]::WriteAllBytes([IO.Path]::GetFullPath($tampered), $bytes)
|
||||
Must-Reject { & $verify -Path $tampered -CertificateThumbprint $CertificateThumbprint -SelfSigned } 'PE file digest mismatch'
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $tampered -ErrorAction SilentlyContinue
|
||||
Remove-Item -LiteralPath $tempDir
|
||||
}
|
||||
if (Test-Path -LiteralPath "Cert:\CurrentUser\Root\$CertificateThumbprint") { throw 'Project signing identity was imported into Root.' }
|
||||
if (Test-Path -LiteralPath "Cert:\CurrentUser\TrustedPublisher\$CertificateThumbprint") { throw 'Project identity was imported into TrustedPublisher.' }
|
||||
$identity = & (Join-Path $PSScriptRoot 'initialize-windows-signing.ps1')
|
||||
if ($identity.certificateThumbprint -ne $CertificateThumbprint) { throw 'Default signing identity changed between builds.' }
|
||||
Write-Host 'Self-signed integration: valid signature/timestamp, wrong identity, CA trust requirement, PE tampering, trust-store isolation and identity reuse passed.'
|
||||
if ($UntimestampedFixture) {
|
||||
Must-Reject { & $verify -Path $UntimestampedFixture -CertificateThumbprint $CertificateThumbprint -SelfSigned } 'Expected one RFC 3161 timestamp'
|
||||
Write-Host 'Missing RFC 3161 timestamp was rejected.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#requires -Version 7.4
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Path,
|
||||
[Parameter(Mandatory)][string]$CertificateThumbprint,
|
||||
[switch]$SelfSigned
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$signature = Get-AuthenticodeSignature -LiteralPath $Path
|
||||
if ($signature.Status -eq 'NotSigned') { throw "The file has no embedded signature: $Path" }
|
||||
if (-not ('RmicWindowsSignature' -as [type])) {
|
||||
$references = @((Get-ChildItem -LiteralPath (Join-Path $PSHOME 'ref') -Filter '*.dll').FullName) +
|
||||
@([System.Security.Cryptography.Pkcs.SignedCms].Assembly.Location)
|
||||
Add-Type -Path (Join-Path $PSScriptRoot 'windows-signature.cs') -ReferencedAssemblies $references
|
||||
}
|
||||
$timestamp = [RmicWindowsSignature]::Verify([IO.Path]::GetFullPath($Path), $CertificateThumbprint, [bool]$SelfSigned)
|
||||
if (-not $SelfSigned -and $signature.Status -ne 'Valid') { throw "Windows does not trust the CA-signed output: $Path" }
|
||||
[pscustomobject]@{ file = [IO.Path]::GetFileName($Path); status = [string]$signature.Status;
|
||||
verificationStatus = $(if ($SelfSigned) { 'valid-pinned-self-signed' } else { 'valid-trusted-signature' });
|
||||
windowsTrustMessage = $signature.StatusMessage;
|
||||
integrityVerified = $true; timestamped = $true; timestampVerified = $true; timestampUtc = $timestamp.ToString('o');
|
||||
certificateThumbprint = $CertificateThumbprint; selfSigned = [bool]$SelfSigned; windowsTrusted = $signature.Status -eq 'Valid' }
|
||||
@@ -0,0 +1,135 @@
|
||||
// Verify the signed PE digest with Windows SIP, CMS with .NET, and the RFC 3161
|
||||
// binding with .NET. A pinned self-signed root is scoped to this X509Chain only.
|
||||
// No certificate is imported into an operating-system trust store.
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Formats.Asn1;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.Pkcs;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
public static class RmicWindowsSignature {
|
||||
const string Sha256 = "2.16.840.1.101.3.4.2.1";
|
||||
[StructLayout(LayoutKind.Sequential)] struct Blob { public uint Size; public IntPtr Data; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct Algorithm {
|
||||
[MarshalAs(UnmanagedType.LPStr)] public string Oid;
|
||||
public Blob Parameters;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)] struct Attribute {
|
||||
public IntPtr Oid;
|
||||
public Blob Value;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)] struct IndirectData {
|
||||
public Attribute Data;
|
||||
public Algorithm Algorithm;
|
||||
public Blob Digest;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct Subject {
|
||||
public uint Size;
|
||||
public IntPtr Type, File;
|
||||
[MarshalAs(UnmanagedType.LPWStr)] public string FileName;
|
||||
public IntPtr DisplayName;
|
||||
public uint Reserved1, Version;
|
||||
public IntPtr Provider;
|
||||
public Algorithm Algorithm;
|
||||
public uint Flags, Encoding, Reserved2, CapiSettings, SecuritySettings, Index, UnionChoice;
|
||||
public IntPtr AdditionalInfo, ClientData;
|
||||
}
|
||||
[DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
|
||||
static extern bool CryptSIPRetrieveSubjectGuid(string file, IntPtr handle, out Guid type);
|
||||
[DllImport("crypt32.dll", SetLastError = true, ExactSpelling = true)]
|
||||
static extern bool CryptSIPGetSignedDataMsg(ref Subject subject, out uint encoding, uint index, ref uint size, [Out] byte[] data);
|
||||
[DllImport("crypt32.dll", SetLastError = true, ExactSpelling = true)]
|
||||
static extern bool CryptSIPCreateIndirectData(ref Subject subject, ref uint size, IntPtr data);
|
||||
|
||||
static void Require(bool condition, string message) {
|
||||
if (!condition) throw new CryptographicException(message);
|
||||
}
|
||||
static void Native(bool success) {
|
||||
if (!success) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
}
|
||||
public static DateTimeOffset Verify(string file, string thumbprint, bool selfSigned) {
|
||||
Native(CryptSIPRetrieveSubjectGuid(file, IntPtr.Zero, out Guid type));
|
||||
IntPtr guid = Marshal.AllocHGlobal(Marshal.SizeOf<Guid>());
|
||||
IntPtr indirect = IntPtr.Zero;
|
||||
try {
|
||||
Marshal.StructureToPtr(type, guid, false);
|
||||
var subject = new Subject { Size = (uint)Marshal.SizeOf<Subject>(), Type = guid,
|
||||
File = new IntPtr(-1), FileName = Path.GetFullPath(file), Encoding = 0x10001,
|
||||
Algorithm = new Algorithm { Oid = Sha256 } };
|
||||
uint size = 0;
|
||||
Native(CryptSIPGetSignedDataMsg(ref subject, out uint encoding, 0, ref size, null));
|
||||
Require(size > 0 && size <= 16 * 1024 * 1024, "Invalid embedded signature size.");
|
||||
var encoded = new byte[size];
|
||||
Native(CryptSIPGetSignedDataMsg(ref subject, out encoding, 0, ref size, encoded));
|
||||
var cms = new SignedCms();
|
||||
cms.Decode(encoded);
|
||||
Require(cms.ContentInfo.ContentType.Value == "1.3.6.1.4.1.311.2.1.4" && cms.SignerInfos.Count == 1,
|
||||
"Expected one embedded Authenticode signer.");
|
||||
var signer = cms.SignerInfos[0];
|
||||
Require(signer.Certificate != null && signer.Certificate.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase),
|
||||
"Unexpected signing certificate thumbprint.");
|
||||
Require(signer.DigestAlgorithm.Value == Sha256, "Expected SHA-256 CMS signature.");
|
||||
cms.CheckSignature(true);
|
||||
var reader = new AsnReader(cms.ContentInfo.Content, AsnEncodingRules.BER);
|
||||
var content = reader.ReadSequence();
|
||||
content.ReadEncodedValue(); // SpcAttributeTypeAndOptionalValue
|
||||
var digestInfo = content.ReadSequence();
|
||||
var algorithm = digestInfo.ReadSequence();
|
||||
Require(algorithm.ReadObjectIdentifier() == Sha256, "Expected SHA-256 PE digest.");
|
||||
if (algorithm.HasData) algorithm.ReadNull();
|
||||
algorithm.ThrowIfNotEmpty();
|
||||
byte[] digest = digestInfo.ReadOctetString();
|
||||
digestInfo.ThrowIfNotEmpty(); content.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty();
|
||||
|
||||
uint indirectSize = 0;
|
||||
Native(CryptSIPCreateIndirectData(ref subject, ref indirectSize, IntPtr.Zero));
|
||||
Require(indirectSize > 0 && indirectSize <= 1024 * 1024, "Invalid SIP result size.");
|
||||
indirect = Marshal.AllocHGlobal((int)indirectSize);
|
||||
Native(CryptSIPCreateIndirectData(ref subject, ref indirectSize, indirect));
|
||||
var actual = Marshal.PtrToStructure<IndirectData>(indirect);
|
||||
Require(actual.Algorithm.Oid == Sha256 && actual.Digest.Size == 32 && digest.Length == 32,
|
||||
"Invalid SIP digest algorithm or length.");
|
||||
byte[] actualDigest = new byte[32];
|
||||
Marshal.Copy(actual.Digest.Data, actualDigest, 0, actualDigest.Length);
|
||||
Require(CryptographicOperations.FixedTimeEquals(actualDigest, digest), "PE file digest mismatch.");
|
||||
|
||||
var timestampAttributes = signer.UnsignedAttributes.Cast<CryptographicAttributeObject>()
|
||||
.Where(a => a.Oid.Value == "1.3.6.1.4.1.311.3.3.1").ToArray();
|
||||
Require(timestampAttributes.Length == 1 && timestampAttributes[0].Values.Count == 1,
|
||||
"Expected one RFC 3161 timestamp.");
|
||||
var timestampData = timestampAttributes[0].Values[0].RawData;
|
||||
Require(Rfc3161TimestampToken.TryDecode(timestampData, out var token, out int consumed) && consumed == timestampData.Length,
|
||||
"Invalid RFC 3161 timestamp.");
|
||||
Require(token.VerifySignatureForSignerInfo(signer, out var tsa, cms.Certificates),
|
||||
"Timestamp signature or binding is invalid.");
|
||||
using (var tsaChain = new X509Chain()) {
|
||||
tsaChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
tsaChain.ChainPolicy.VerificationTime = token.TokenInfo.Timestamp.UtcDateTime;
|
||||
tsaChain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.8"));
|
||||
tsaChain.ChainPolicy.ExtraStore.AddRange(token.AsSignedCms().Certificates);
|
||||
Require(tsaChain.Build(tsa), "Timestamp authority certificate chain is invalid.");
|
||||
}
|
||||
using (var chain = new X509Chain()) {
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
chain.ChainPolicy.VerificationTime = token.TokenInfo.Timestamp.UtcDateTime;
|
||||
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
|
||||
chain.ChainPolicy.ExtraStore.AddRange(cms.Certificates);
|
||||
if (selfSigned) {
|
||||
Require(signer.Certificate.SubjectName.RawData.SequenceEqual(signer.Certificate.IssuerName.RawData),
|
||||
"Expected a self-signed certificate.");
|
||||
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
chain.ChainPolicy.CustomTrustStore.Add(signer.Certificate);
|
||||
}
|
||||
Require(chain.Build(signer.Certificate), "Signing certificate chain is invalid for the selected identity.");
|
||||
}
|
||||
return token.TokenInfo.Timestamp;
|
||||
} finally {
|
||||
if (indirect != IntPtr.Zero) Marshal.FreeHGlobal(indirect);
|
||||
Marshal.FreeHGlobal(guid);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,42 @@ const FALLBACK_INPUT_FPS: f32 = 20.0;
|
||||
type Shared<'a> = State<'a, Arc<AppState>>;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn match_action(state: Shared<'_>, action: cam_core::match_clock::MatchAction) -> Result<(), String> {
|
||||
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]
|
||||
pub async fn match_action(
|
||||
state: Shared<'_>,
|
||||
action: cam_core::match_clock::MatchAction,
|
||||
) -> Result<(), String> {
|
||||
if matches!(action, cam_core::match_clock::MatchAction::Reset) {
|
||||
state.reset_match().await
|
||||
} else {
|
||||
state.match_action(action)
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn release_match_source(state: Shared<'_>) -> Result<(), String> {
|
||||
@@ -201,13 +234,29 @@ pub fn set_role(
|
||||
/// 左右镜像。摄像头装反了才需要,不是判罚相关的东西,所以不设密码。
|
||||
#[tauri::command]
|
||||
pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
state
|
||||
.update_config(move |config| config.mirror = mirror)
|
||||
.map_err(|err| format!("{err}"))?;
|
||||
state.set_camera_mirror(None, Some(mirror), None)?;
|
||||
|
||||
Ok(ConfigView::from(&state.config()))
|
||||
}
|
||||
|
||||
/// 上下镜像,独立保存,不改动左右镜像。
|
||||
#[tauri::command]
|
||||
pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
state.set_camera_mirror(None, None, Some(mirror_vertical))?;
|
||||
|
||||
Ok(ConfigView::from(&state.config()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_camera_mirror(
|
||||
camera: u32,
|
||||
mirror: bool,
|
||||
mirror_vertical: bool,
|
||||
state: Shared<'_>,
|
||||
) -> Result<(), String> {
|
||||
state.set_camera_mirror(Some(camera), Some(mirror), Some(mirror_vertical))
|
||||
}
|
||||
|
||||
/// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。
|
||||
#[tauri::command]
|
||||
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
|
||||
@@ -122,21 +122,35 @@ fn spawn_armor(state: Arc<AppState>) {
|
||||
let mut ticks = [0u32, 7];
|
||||
let mut hits = [0usize, 1];
|
||||
let mut dead_for = [0u32, 0];
|
||||
let mut reset_epoch = 0;
|
||||
|
||||
loop {
|
||||
let epoch = state
|
||||
.demo_reset_epoch
|
||||
.load(std::sync::atomic::Ordering::Acquire);
|
||||
if epoch != reset_epoch {
|
||||
reset_epoch = epoch;
|
||||
hp = [100; 2];
|
||||
ticks = [0, 7];
|
||||
hits = [0, 1];
|
||||
dead_for = [0; 2];
|
||||
}
|
||||
let scripted = state.demo_damage_enabled();
|
||||
for (slot, (board, team, port)) in boards.iter().enumerate() {
|
||||
if scripted {
|
||||
ticks[slot] += 1;
|
||||
}
|
||||
|
||||
if hp[slot] == 0 {
|
||||
// 打空之后停一会儿再重置:让界面上的胜负横幅真的能被看到。
|
||||
dead_for[slot] += 1;
|
||||
if dead_for[slot] >= 10 {
|
||||
if reset_epoch == 0 && scripted && dead_for[slot] >= 10 {
|
||||
hp[slot] = 100;
|
||||
dead_for[slot] = 0;
|
||||
ticks[slot] = 0;
|
||||
log::info!("demo: 0x{board:08X} 重置为满血(长按 BOOT 的等价动作)");
|
||||
}
|
||||
} else if ticks[slot] % 15 == 0 {
|
||||
} else if scripted && ticks[slot] % 15 == 0 {
|
||||
// 约 3 秒一次。
|
||||
let damage = DAMAGE_CYCLE[hits[slot] % DAMAGE_CYCLE.len()];
|
||||
hits[slot] += 1;
|
||||
|
||||
@@ -23,14 +23,14 @@
|
||||
|
||||
mod commands;
|
||||
mod demo;
|
||||
mod version;
|
||||
mod firmware_build;
|
||||
mod latency;
|
||||
mod maintenance;
|
||||
mod firmware_build;
|
||||
mod recording;
|
||||
mod server;
|
||||
mod state;
|
||||
mod startup;
|
||||
mod state;
|
||||
mod version;
|
||||
|
||||
use std::error::Error;
|
||||
use std::path::PathBuf;
|
||||
@@ -329,6 +329,8 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
commands::stream_info,
|
||||
commands::get_snapshot,
|
||||
commands::match_action,
|
||||
commands::operator_start,
|
||||
commands::operator_input,
|
||||
commands::release_match_source,
|
||||
commands::get_config,
|
||||
commands::list_media_files,
|
||||
@@ -342,6 +344,8 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
commands::set_team,
|
||||
commands::set_role,
|
||||
commands::set_mirror,
|
||||
commands::set_camera_mirror,
|
||||
commands::set_mirror_vertical,
|
||||
commands::save_hud,
|
||||
commands::set_team_name,
|
||||
commands::set_referee_slots,
|
||||
@@ -371,7 +375,11 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
// 解锁框。拦不住的路径仍然存在——`kill -9`、强退、拔电源——所以它同样是"防
|
||||
// 随手误操作",不是安全边界。
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::Focused(focused) = event {
|
||||
window.state::<Arc<AppState>>().operator_focus(*focused);
|
||||
}
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
window.state::<Arc<AppState>>().stop_operator("窗口正在关闭,操作已停止");
|
||||
if window.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
||||
api.prevent_close();
|
||||
let _ = window.emit("maintenance-close-blocked", "固件维护正在进行,请等待完成;编译可先取消。请勿在写入或恢复期间关闭客户端。");
|
||||
@@ -390,15 +398,22 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
app.run(|app, event| {
|
||||
if let RunEvent::ExitRequested { api, .. } = &event {
|
||||
app.state::<Arc<AppState>>()
|
||||
.stop_operator("正在退出,操作已停止");
|
||||
if app.state::<Arc<maintenance::MaintenanceState>>().is_busy() {
|
||||
api.prevent_exit();
|
||||
let _ = app.emit("maintenance-close-blocked", "固件维护正在进行,请等待完成后退出。");
|
||||
let _ = app.emit(
|
||||
"maintenance-close-blocked",
|
||||
"固件维护正在进行,请等待完成后退出。",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let state = app.state::<Arc<AppState>>();
|
||||
|
||||
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();
|
||||
state.push(server::WireMsg::ConfirmQuit);
|
||||
return;
|
||||
|
||||
+479
-11
@@ -23,12 +23,12 @@ use anyhow::{Context, Result};
|
||||
use cam_core::armor::{ArmorHealthStore, HealthTracker};
|
||||
use cam_core::config::{Config, Role};
|
||||
use cam_core::match_clock::{MatchAction, MatchClock, MatchView};
|
||||
use cam_core::operator::{OperatorContext, OperatorInput, OperatorMode, OperatorState};
|
||||
use cam_core::password;
|
||||
use cam_core::receiver::{Discovery, LatestFrames, Receiver};
|
||||
use cam_core::slots::SlotAllocator;
|
||||
use cam_core::snapshot::{
|
||||
resolve_outcomes, ArmorBoardDto, CameraDto, CameraStatsDto, ConfigView, HitDto, SlotsDto,
|
||||
Snapshot, TeamHealthDto,
|
||||
ArmorBoardDto, CameraDto, CameraStatsDto, ConfigView, HitDto, SlotsDto, Snapshot, TeamHealthDto,
|
||||
};
|
||||
use cam_core::stats::{FpsWindow, DEFAULT_WINDOW};
|
||||
use cam_core::ArmorSource;
|
||||
@@ -59,6 +59,15 @@ pub struct AppState {
|
||||
match_clock: Mutex<MatchClock>,
|
||||
match_socket: Option<std::net::UdpSocket>,
|
||||
match_error: Mutex<Option<String>>,
|
||||
match_changed: tokio::sync::Notify,
|
||||
mirror_inbox: Mutex<cam_core::camera_mirror::CameraMirrors>,
|
||||
mirror_origin: u64,
|
||||
mirror_socket: Option<std::net::UdpSocket>,
|
||||
operator: Mutex<OperatorState>,
|
||||
operator_socket: Option<std::net::UdpSocket>,
|
||||
operator_focused: AtomicBool,
|
||||
resetting: AtomicBool,
|
||||
pub demo_reset_epoch: AtomicUsize,
|
||||
discovery: Arc<Discovery>,
|
||||
latest: Arc<LatestFrames>,
|
||||
|
||||
@@ -84,15 +93,269 @@ pub struct AppState {
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn mirror_targets(&self) -> Vec<u32> {
|
||||
let config = self.config();
|
||||
if config.role == Role::Team {
|
||||
config.camera_id.into_iter().collect()
|
||||
} else {
|
||||
self.slots
|
||||
.lock()
|
||||
.expect("slots poisoned")
|
||||
.slots()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_camera_mirror(
|
||||
&self,
|
||||
camera: Option<u32>,
|
||||
horizontal: Option<bool>,
|
||||
vertical: Option<bool>,
|
||||
) -> Result<(), String> {
|
||||
let targets = self.mirror_targets();
|
||||
let ids = match camera {
|
||||
Some(id) if targets.contains(&id) => vec![id],
|
||||
Some(_) => return Err("只能修改已绑定或当前槽位的图传板".into()),
|
||||
None => targets,
|
||||
};
|
||||
// 先观察已收到但尚未应用的远端修订,避免紧接收到包后的本地点击被旧包覆盖。
|
||||
self.tick_mirrors();
|
||||
let mut config = self.config.lock().expect("config poisoned");
|
||||
let revision = config
|
||||
.camera_mirrors
|
||||
.values()
|
||||
.map(|v| v.revision)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.checked_add(1)
|
||||
.ok_or("镜像修订号已用尽")?;
|
||||
for id in ids {
|
||||
let old = config.camera_mirrors.get(&id.to_string());
|
||||
let packet = protocol::CameraMirror {
|
||||
camera_id: id,
|
||||
revision,
|
||||
origin: self.mirror_origin,
|
||||
mirror: horizontal.unwrap_or(old.map_or(config.mirror, |v| v.mirror)),
|
||||
mirror_vertical: vertical
|
||||
.unwrap_or(old.map_or(config.mirror_vertical, |v| v.mirror_vertical)),
|
||||
};
|
||||
cam_core::camera_mirror::merge(&mut config.camera_mirrors, packet);
|
||||
}
|
||||
if camera.is_none() || config.role == Role::Team {
|
||||
if let Some(v) = horizontal {
|
||||
config.mirror = v;
|
||||
}
|
||||
if let Some(v) = vertical {
|
||||
config.mirror_vertical = v;
|
||||
}
|
||||
}
|
||||
config
|
||||
.save(&self.config_path)
|
||||
.map_err(|e| format!("镜像已在本次运行生效,但保存失败:{e}"))?;
|
||||
drop(config);
|
||||
self.tick_mirrors();
|
||||
self.push_snapshot();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tick_mirrors(&self) {
|
||||
let targets = self.mirror_targets();
|
||||
let inbox = std::mem::take(&mut *self.mirror_inbox.lock().expect("mirror inbox poisoned"));
|
||||
let mut config = self.config.lock().expect("config poisoned");
|
||||
let mut changed = false;
|
||||
for (id, value) in inbox {
|
||||
if let Ok(id) = id.parse::<u32>() {
|
||||
if targets.contains(&id) {
|
||||
changed |= cam_core::camera_mirror::merge(
|
||||
&mut config.camera_mirrors,
|
||||
value.packet(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.role == Role::Team {
|
||||
if let Some(value) = config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.cloned()
|
||||
{
|
||||
config.mirror = value.mirror;
|
||||
config.mirror_vertical = value.mirror_vertical;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if let Err(error) = config.save(&self.config_path) {
|
||||
log::warn!("镜像同步保存失败:{error}");
|
||||
}
|
||||
}
|
||||
let packets: Vec<_> = targets
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
config
|
||||
.camera_mirrors
|
||||
.get(&id.to_string())
|
||||
.map(|v| v.packet(id))
|
||||
})
|
||||
.collect();
|
||||
drop(config);
|
||||
if !self.demo {
|
||||
if let Some(socket) = &self.mirror_socket {
|
||||
for packet in &packets {
|
||||
if let Some(bytes) = packet.encode() {
|
||||
let _ = socket.send_to(
|
||||
&bytes,
|
||||
(
|
||||
cam_core::mirror_transport::GROUP,
|
||||
cam_core::mirror_transport::PORT,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(socket) = &self.match_socket {
|
||||
for packet in packets {
|
||||
if let Some(bytes) = packet.encode() {
|
||||
let _ = socket.send_to(
|
||||
&bytes,
|
||||
(std::net::Ipv4Addr::BROADCAST, protocol::ARMOR_PORT),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
self.started.elapsed().as_millis().min(u64::MAX as u128) as u64
|
||||
}
|
||||
|
||||
pub fn demo_damage_enabled(&self) -> bool {
|
||||
let phase = self.match_view().phase;
|
||||
phase == "running"
|
||||
|| (phase == "idle" && self.demo_reset_epoch.load(Ordering::Acquire) == 0)
|
||||
}
|
||||
|
||||
/// 接收路径只更新核心终局并唤醒发送任务,不等待网络、UI 或写盘。
|
||||
fn observe_match_health(&self) -> bool {
|
||||
let health = [self.health_for(0), self.health_for(1)];
|
||||
let hp = health.map(|entry| if entry.available { entry.hp } else { None });
|
||||
self.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.finish_on_health(hp, self.match_now())
|
||||
}
|
||||
|
||||
pub fn match_action(&self, action: MatchAction) -> Result<(), String> {
|
||||
// 闸门留在后端,选手端不能通过 IPC 修改权威计时。
|
||||
if self.config().role != Role::Referee {
|
||||
return Err("只有裁判端可以控制比赛计时".into());
|
||||
}
|
||||
if self.resetting.load(Ordering::Acquire) {
|
||||
return Err("正在重置本局,请等待装甲板确认".into());
|
||||
}
|
||||
self.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
@@ -102,6 +365,89 @@ impl AppState {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reset_match(&self) -> Result<(), String> {
|
||||
if self.config().role != Role::Referee {
|
||||
return Err("只有裁判端可以重置比赛".into());
|
||||
}
|
||||
self.resetting
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.map_err(|_| "正在重置本局,请等待装甲板确认".to_string())?;
|
||||
let _guard = MatchResetGuard {
|
||||
busy: &self.resetting,
|
||||
armor: &self.armor,
|
||||
};
|
||||
let config = self.config();
|
||||
let health = [self.health_for(0), self.health_for(1)];
|
||||
let participants = [
|
||||
self.assigned_armor(&config, 0),
|
||||
self.assigned_armor(&config, 1),
|
||||
];
|
||||
if !self.demo
|
||||
&& health
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(team, health)| health.available && participants[team].is_none())
|
||||
{
|
||||
return Err("有血量上报但未分配对应装甲板,请先检查两队装甲板槽位再重置".into());
|
||||
}
|
||||
let has_outcome = health
|
||||
.iter()
|
||||
.any(|health| health.available && health.hp == Some(0));
|
||||
let packet = self
|
||||
.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.begin_reset(has_outcome, self.match_now())?;
|
||||
self.tick_match();
|
||||
self.push_snapshot();
|
||||
|
||||
if self.demo {
|
||||
self.demo_reset_epoch.fetch_add(1, Ordering::Release);
|
||||
for (board, team) in [(DEMO_ARMOR_A, 0), (DEMO_ARMOR_B, 1)] {
|
||||
for index in 0..4 {
|
||||
let report = protocol::ArmorHealth {
|
||||
team,
|
||||
index,
|
||||
hp: 100,
|
||||
}
|
||||
.encode_from(board);
|
||||
self.armor
|
||||
.datagram(&report, "127.0.0.1:5601".parse().unwrap());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if self.match_socket.is_none() {
|
||||
return Err("装甲板控制通道不可用,请检查 UDP 5601 后重启客户端".into());
|
||||
}
|
||||
self.armor.begin_reset(&packet, participants)?;
|
||||
self.tick_match();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let waiting = self.armor.reset_waiting();
|
||||
if waiting.is_empty() {
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let ids = waiting
|
||||
.iter()
|
||||
.map(|id| format!("0x{id:08X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、");
|
||||
return Err(format!("装甲板 {ids} 未确认复位或未上报四路满血;本局保持结束。请检查连接并更新装甲板固件后重试,也可长按 BOOT 复位"));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
self.armor.finish_reset();
|
||||
self.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.action(MatchAction::Reset, self.match_now())?;
|
||||
self.tick_match();
|
||||
self.push_snapshot();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn release_match_source(&self) -> Result<(), String> {
|
||||
self.match_clock
|
||||
.lock()
|
||||
@@ -209,6 +555,9 @@ impl AppState {
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.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 {
|
||||
config_path,
|
||||
config: Mutex::new(config),
|
||||
@@ -219,6 +568,21 @@ impl AppState {
|
||||
match_clock: Mutex::new(MatchClock::new(role == Role::Referee, session, 0)),
|
||||
match_socket,
|
||||
match_error: Mutex::new(match_error),
|
||||
match_changed: tokio::sync::Notify::new(),
|
||||
mirror_inbox: Mutex::new(Default::default()),
|
||||
mirror_origin: session.max(1),
|
||||
mirror_socket: match cam_core::mirror_transport::bind() {
|
||||
Ok(socket) => Some(socket),
|
||||
Err(error) => {
|
||||
log::warn!("镜像组播不可用,保留 UDP 5601 广播同步:{error}");
|
||||
None
|
||||
}
|
||||
},
|
||||
operator: Mutex::new(OperatorState::new(session)),
|
||||
operator_socket,
|
||||
operator_focused: AtomicBool::new(true),
|
||||
resetting: AtomicBool::new(false),
|
||||
demo_reset_epoch: AtomicUsize::new(0),
|
||||
discovery,
|
||||
latest,
|
||||
fps: Mutex::new(HashMap::new()),
|
||||
@@ -244,6 +608,34 @@ impl AppState {
|
||||
///
|
||||
/// 必须在 `Arc<AppState>` 建好之后调用(sink 里要持有 state 的通道)。
|
||||
pub fn install_sinks(self: &Arc<Self>) {
|
||||
if !self.demo {
|
||||
if let Some(socket) = self.mirror_socket.as_ref().and_then(|s| s.try_clone().ok()) {
|
||||
let weak = Arc::downgrade(self);
|
||||
if let Err(error) = cam_core::mirror_transport::spawn(socket, move |packet| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
if state.mirror_targets().contains(&packet.camera_id) {
|
||||
cam_core::camera_mirror::merge(
|
||||
&mut state.mirror_inbox.lock().expect("mirror inbox poisoned"),
|
||||
packet,
|
||||
);
|
||||
}
|
||||
}
|
||||
}) {
|
||||
log::warn!("无法启动镜像组播接收:{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let weak = Arc::downgrade(self);
|
||||
self.armor.set_mirror_sink(Arc::new(move |packet| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
if !state.demo && state.mirror_targets().contains(&packet.camera_id) {
|
||||
cam_core::camera_mirror::merge(
|
||||
&mut state.mirror_inbox.lock().expect("mirror inbox poisoned"),
|
||||
packet,
|
||||
);
|
||||
}
|
||||
}
|
||||
}));
|
||||
let weak = Arc::downgrade(self);
|
||||
self.armor.set_match_sink(Arc::new(move |packet, ip| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
@@ -257,6 +649,21 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
}));
|
||||
let weak = Arc::downgrade(self);
|
||||
self.armor
|
||||
.set_match_result_sink(Arc::new(move |packet, ip| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
if !state.demo
|
||||
&& state
|
||||
.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.receive_result(packet, ip, state.match_now())
|
||||
{
|
||||
state.match_changed.notify_one();
|
||||
}
|
||||
}
|
||||
}));
|
||||
let video = self.video.clone();
|
||||
let recordings = Arc::clone(&self.recordings);
|
||||
|
||||
@@ -269,9 +676,17 @@ impl AppState {
|
||||
|
||||
let tx = self.tx.clone();
|
||||
let tracker = Arc::new(Mutex::new(HealthTracker::new()));
|
||||
let weak = Arc::downgrade(self);
|
||||
|
||||
// 装甲板的 sink:把"现在多少血"派生为"刚刚掉了几点",立刻推给界面。
|
||||
self.armor.set_sink(Arc::new(move |report| {
|
||||
if report.hp == 0 {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
if state.observe_match_health() {
|
||||
state.match_changed.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit = tracker
|
||||
.lock()
|
||||
.expect("health tracker mutex poisoned")
|
||||
@@ -327,13 +742,25 @@ impl AppState {
|
||||
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);
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(SNAPSHOT_INTERVAL);
|
||||
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
state_for_loop.tick();
|
||||
tokio::select! {
|
||||
_ = ticker.tick() => state_for_loop.tick(),
|
||||
_ = state_for_loop.match_changed.notified() => state_for_loop.tick_match(),
|
||||
}
|
||||
state_for_loop.push_snapshot();
|
||||
}
|
||||
});
|
||||
@@ -349,6 +776,9 @@ impl AppState {
|
||||
|
||||
/// 改配置、落盘、重新套用闸门。
|
||||
pub fn update_config(&self, change: impl FnOnce(&mut Config)) -> Result<Config> {
|
||||
if self.resetting.load(Ordering::Acquire) {
|
||||
anyhow::bail!("正在重置本局,请等待装甲板确认后修改配置");
|
||||
}
|
||||
let updated = {
|
||||
let mut config = self.config.lock().expect("config mutex poisoned");
|
||||
change(&mut config);
|
||||
@@ -372,6 +802,7 @@ impl AppState {
|
||||
/// 每一次可能改变身份、绑定或发现开合的改动之后都要调用它——把这件事收在一个函数
|
||||
/// 里,是为了不让"某个命令忘了重新套用闸门"这种漏洞有时间长出来。
|
||||
pub fn apply_gates(&self) {
|
||||
self.stop_operator("身份、绑定或设置已改变,请重新开启操作");
|
||||
let config = self.config();
|
||||
self.match_clock
|
||||
.lock()
|
||||
@@ -546,12 +977,12 @@ impl AppState {
|
||||
|
||||
/// 推进帧率窗口与槽位分配。
|
||||
fn tick_match(&self) {
|
||||
self.observe_match_health();
|
||||
if !self.demo && self.config().role_chosen {
|
||||
let packet = self
|
||||
.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.broadcast(self.match_now());
|
||||
let (packet, result) = {
|
||||
let mut clock = self.match_clock.lock().expect("match clock poisoned");
|
||||
(clock.broadcast(self.match_now()), clock.result_packet())
|
||||
};
|
||||
if let (Some(socket), Some(packet)) = (&self.match_socket, packet) {
|
||||
if let Some(bytes) = packet.encode() {
|
||||
let config = self.config();
|
||||
@@ -569,8 +1000,20 @@ impl AppState {
|
||||
.armor
|
||||
.send_damage_controls(socket, &packet, participants)
|
||||
.err();
|
||||
let reset_error = self.armor.send_reset_controls(socket, &packet).err();
|
||||
let result_error =
|
||||
result.and_then(|result| result.encode()).and_then(|bytes| {
|
||||
socket
|
||||
.send_to(
|
||||
&bytes,
|
||||
(std::net::Ipv4Addr::BROADCAST, protocol::ARMOR_PORT),
|
||||
)
|
||||
.err()
|
||||
});
|
||||
let error = sync_error
|
||||
.or(damage_error)
|
||||
.or(reset_error)
|
||||
.or(result_error)
|
||||
.map(|err| format!("比赛状态发送失败:{err}。请检查网络和防火墙"));
|
||||
*self.match_error.lock().expect("match error poisoned") = error;
|
||||
}
|
||||
@@ -579,6 +1022,7 @@ impl AppState {
|
||||
}
|
||||
|
||||
pub fn tick(&self) {
|
||||
self.tick_mirrors();
|
||||
self.tick_match();
|
||||
let online: Vec<u32> = self
|
||||
.discovery
|
||||
@@ -683,13 +1127,25 @@ impl AppState {
|
||||
let mut health = vec![self.health_for(0), self.health_for(1)];
|
||||
|
||||
// 胜负是**两边合起来**才能算出来的东西,所以在这里补一步。
|
||||
resolve_outcomes(&mut health);
|
||||
self.match_clock
|
||||
.lock()
|
||||
.expect("match clock poisoned")
|
||||
.apply_outcomes(&mut health);
|
||||
|
||||
Snapshot {
|
||||
camera_mirrors: config.camera_mirrors.clone(),
|
||||
operator_control: self.operator.lock().expect("operator poisoned").view(),
|
||||
match_clock: self.match_view(),
|
||||
role: config.role,
|
||||
team: config.team,
|
||||
mirrored: config.mirror,
|
||||
mirrored: config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.map_or(config.mirror, |v| v.mirror),
|
||||
mirrored_vertical: config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.map_or(config.mirror_vertical, |v| v.mirror_vertical),
|
||||
demo: self.demo,
|
||||
diagnostics,
|
||||
unlocked: self.is_unlocked(),
|
||||
@@ -781,3 +1237,15 @@ pub const DEMO_CAMERA_A: u32 = 0x0DE0_0001;
|
||||
pub const DEMO_CAMERA_B: u32 = 0x0DE0_0002;
|
||||
pub const DEMO_ARMOR_A: u32 = 0x0A20_0001;
|
||||
pub const DEMO_ARMOR_B: u32 = 0x0A20_0002;
|
||||
|
||||
struct MatchResetGuard<'a> {
|
||||
busy: &'a AtomicBool,
|
||||
armor: &'a ArmorHealthStore,
|
||||
}
|
||||
|
||||
impl Drop for MatchResetGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.armor.finish_reset();
|
||||
self.busy.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RMIC-2026",
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.1",
|
||||
"identifier": "com.simbarobotics.rmic2026",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+3
-2
@@ -124,7 +124,7 @@ export default function App() {
|
||||
}, []);
|
||||
|
||||
const milestones = [
|
||||
{ key: "fonts", label: "加载字体", code: "HARMONYOS · JETBRAINS", done: fontsReady },
|
||||
{ key: "fonts", label: "加载字体", code: "HARMONYOS / JETBRAINS", done: fontsReady },
|
||||
{ key: "channel", label: "连接本机服务", code: "LOCAL IPC", done: url !== null },
|
||||
{ key: "snapshot", label: "读取运行状态", code: "SNAPSHOT 200ms", done: snapshot !== null },
|
||||
];
|
||||
@@ -375,7 +375,7 @@ export default function App() {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<div className="splash">
|
||||
<span className="splash__mark label">RMIC · 2026</span>
|
||||
<span className="splash__mark label">RMIC / 2026</span>
|
||||
<h1 className="splash__title">正在读取运行状态</h1>
|
||||
<p className="splash__text">
|
||||
{connected ? "已连接,等待状态数据…" : "正在连接本机服务…"}
|
||||
@@ -422,6 +422,7 @@ export default function App() {
|
||||
snapshot={snapshot}
|
||||
hud={hud ?? snapshot.config.hud}
|
||||
calibrating={calibrating}
|
||||
controlsBlocked={operatorMenu || drawer || drawerClosing || unlockReason !== null || maintenance || !bootGone}
|
||||
onCalibrate={onCalibrate}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// Source: https://github.com/google/material-design-icons/tree/master/symbols/web
|
||||
// License and attribution ship in client/public/licenses/material-symbols/.
|
||||
export const materialPaths = {
|
||||
mirrorHorizontal: ["M450-840h60v720h-60v-720ZM100-240v-480l280 240L100-240Zm80-170 77-70-77-70v140Zm680 170L580-480l280-240v480Zm-80-170v-140l-77 70 77 70Z"],
|
||||
mirrorVertical: ["M120-510h720v60H120v-60Zm120-350 240 280 240-280H240Zm170 80h140l-70 77-70-77ZM240-100l240-280 240 280H240Zm170-80h140l-70-77-70 77Z"],
|
||||
close: ["M480-424 284-228q-11 11-28 11t-28-11q-11-11-11-28t11-28l196-196-196-196q-11-11-11-28t11-28q11-11 28-11t28 11l196 196 196-196q11-11 28-11t28 11q11 11 11 28t-11 28L536-480l196 196q11 11 11 28t-11 28q-11 11-28 11t-28-11L480-424Z"],
|
||||
back: ["m313-440 196 196q12 12 11.5 28T508-188q-12 11-28 11.5T452-188L188-452q-6-6-8.5-13t-2.5-15q0-8 2.5-15t8.5-13l264-264q11-11 27.5-11t28.5 11q12 12 12 28.5T508-715L313-520h447q17 0 28.5 11.5T800-480q0 17-11.5 28.5T760-440H313Z"],
|
||||
next: ["M647-440H200q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520h447L451-716q-12-12-11.5-28t12.5-28q12-11 28-11.5t28 11.5l264 264q6 6 8.5 13t2.5 15q0 8-2.5 15t-8.5 13L508-188q-11 11-27.5 11T452-188q-12-12-12-28.5t12-28.5l195-195Z"],
|
||||
|
||||
@@ -83,9 +83,9 @@ export function ArmorTable({ boards, slots, names, focusTeam = null }: Props) {
|
||||
{shown.map((board) => {
|
||||
const assigned =
|
||||
slots.armorA === board.id
|
||||
? `左 · ${teamName(0, names)}`
|
||||
? `左 / ${teamName(0, names)}`
|
||||
: slots.armorB === board.id
|
||||
? `右 · ${teamName(1, names)}`
|
||||
? `右 / ${teamName(1, names)}`
|
||||
: "未分配";
|
||||
const tone = silenceTone(board.online, board.silenceMs);
|
||||
|
||||
@@ -184,7 +184,7 @@ export function StatsLine({
|
||||
<span className={`dot ${stats.online ? "dot--live" : "dot--dead"}`} />
|
||||
<span className="statsline__status">{stats.status}</span>
|
||||
<span className="statsline__sep" aria-hidden="true" />
|
||||
<span className="statsline__nums num">{parts.join(" · ")}</span>
|
||||
<span className="statsline__nums num">{parts.join(" / ")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export function Boot({ milestones, progress, fatal, leaving = false, onRetry, on
|
||||
|
||||
<div className="boot__frame">
|
||||
<div className="boot__eyebrow label">
|
||||
<span>{preview ? "合成预览 · 启动动画" : "SIMBA ROBOTICS"}</span>
|
||||
<span>{preview ? "合成预览 / 启动动画" : "SIMBA ROBOTICS"}</span>
|
||||
<span className="num">{VERSION_LABEL}</span>
|
||||
{onCancel && <button type="button" className="boot__close" onClick={onCancel} title="退出启动" aria-label="退出启动"><Icon name="close" /></button>}
|
||||
</div>
|
||||
@@ -80,7 +80,7 @@ export function Boot({ milestones, progress, fatal, leaving = false, onRetry, on
|
||||
</div>
|
||||
<div className="boot__meta">
|
||||
<span className="label">
|
||||
{progress >= 1 ? "加载完成 · 正在进入" : "正在加载"}
|
||||
{progress >= 1 ? "加载完成 / 正在进入" : "正在加载"}
|
||||
</span>
|
||||
<span className="num boot__pct">
|
||||
{Math.round(Math.max(0, Math.min(1, progress)) * 100)}
|
||||
|
||||
@@ -12,7 +12,7 @@ export function BootPreview({ failed }: { failed: boolean }) {
|
||||
return <Boot
|
||||
preview
|
||||
milestones={[
|
||||
{ key: "fonts", label: "加载字体", code: "HARMONYOS · JETBRAINS", done: completed >= 1 },
|
||||
{ key: "fonts", label: "加载字体", code: "HARMONYOS / JETBRAINS", done: completed >= 1 },
|
||||
{ key: "channel", label: "连接本机服务", code: "LOCAL IPC", done: completed >= 2 },
|
||||
{ key: "snapshot", label: "读取运行状态", code: "SNAPSHOT 200ms", done: completed >= 3 },
|
||||
]}
|
||||
|
||||
@@ -50,6 +50,6 @@ export function DeviceDiagram({ kind, identified, portAvailable, active, failed,
|
||||
<g className="device-diagram__computer"><rect x="28" y="142" width="82" height="58" rx="4" /><path d="M69 201v14m-24 0h48m-44-45 10 8-10 8m18 0h19" /><circle className="device-diagram__led" cx="98" cy="153" r="3" /></g>
|
||||
<path className={`device-diagram__cable${portAvailable ? " is-present" : ""}`} d={`M112 171h38q20 0 20 20v97q0 20 20 20h${usbX - 208}q18 0 18-18v-4`} />
|
||||
{kind === "armor" ? <ArmorBoard /> : kind === "camera" ? <CameraBoard /> : <g className="device-diagram__board"><rect className="device-diagram__pcb" x="290" y="112" width="130" height="166" rx="8" /><text x="355" y="186" textAnchor="middle">USB</text><text className="device-diagram__sublabel" x="355" y="207" textAnchor="middle">选择维护对象</text><rect className="device-diagram__usb is-connected" x="339" y="267" width="32" height="20" rx="4" /></g>}
|
||||
<text className="device-diagram__caption" x="69" y="245" textAnchor="middle">CLIENT / USB</text><text className="device-diagram__caption" x="355" y="340" textAnchor="middle">{kind === "armor" ? "装甲板 · ESP32-C3" : kind === "camera" ? "图传板 · 右侧 USB 接入" : chip || "选择维护对象"}</text>
|
||||
<text className="device-diagram__caption" x="69" y="245" textAnchor="middle">CLIENT / USB</text><text className="device-diagram__caption" x="355" y="340" textAnchor="middle">{kind === "armor" ? "装甲板 / ESP32-C3" : kind === "camera" ? "图传板 / 右侧 USB 接入" : chip || "选择维护对象"}</text>
|
||||
</svg>;
|
||||
}
|
||||
@@ -74,7 +74,7 @@ export function RolePicker({ onOpenMaintenance }: { onOpenMaintenance?: () => vo
|
||||
<span className="gate__brand">
|
||||
RMIC<span className="gate__slash">::</span>2026
|
||||
</span>
|
||||
<span className="gate__phase label">FIRST RUN · 选择运行模式</span>
|
||||
<span className="gate__phase label">FIRST RUN / 选择运行模式</span>
|
||||
</header>
|
||||
|
||||
<div className="gate__lede">
|
||||
@@ -174,7 +174,7 @@ export function SetupPassword({ onOpenMaintenance }: { onOpenMaintenance?: () =>
|
||||
<span className="gate__brand">
|
||||
RMIC<span className="gate__slash">::</span>2026
|
||||
</span>
|
||||
<span className="gate__phase label">OPERATOR · 现场密码</span>
|
||||
<span className="gate__phase label">OPERATOR / 现场密码</span>
|
||||
</header>
|
||||
|
||||
<div className="gate__lede">
|
||||
|
||||
@@ -15,10 +15,10 @@ interface Props {
|
||||
}
|
||||
|
||||
export function HealthBar({ health, config, align, tag, asleep = false }: Props) {
|
||||
// 脉动交给 CSS,减少动态效果时仍保留低血颜色,停止闪动。
|
||||
// 脉动交给 CSS;减少动态效果时保留低血边框,队伍色始终不变。
|
||||
const pulsing = config.pulse && health.available && health.critical;
|
||||
|
||||
const color = health.critical ? "var(--error)" : teamColor(health.team);
|
||||
const color = teamColor(health.team);
|
||||
const raw = health.available ? Math.max(0, Math.min(100, health.hp ?? 0)) : 0;
|
||||
|
||||
const showThreshold = config.lowThreshold > 0 && config.lowThreshold < 100;
|
||||
@@ -31,7 +31,7 @@ export function HealthBar({ health, config, align, tag, asleep = false }: Props)
|
||||
className={`hp hp--${align}${asleep ? " hp--asleep" : ""}${
|
||||
pulsing ? " hp--pulsing" : ""
|
||||
}${health.critical ? " hp--critical" : ""}`}
|
||||
style={{ width }}
|
||||
style={{ width, color }}
|
||||
title={health.available ? undefined : health.placeholder}
|
||||
>
|
||||
<div className="hp__head">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* # 它一直显示到血量被重置
|
||||
*
|
||||
* 不做 3 秒淡出:淡出之后屏幕上就再没有"这局结束了"的痕迹,截图、回放、现场的争议都
|
||||
* 无从对照。血量被重置(长按 BOOT / 下一局开始)时它自己消失——那个动作本来就是
|
||||
* 无从对照。血量复位(长按 BOOT / 裁判端重置到未开始)时横幅消失——这个动作表示
|
||||
* "这局翻篇了"。
|
||||
*
|
||||
* # 为什么要加电影黑边
|
||||
@@ -39,9 +39,9 @@ const WORD: Record<MatchOutcome, string> = {
|
||||
};
|
||||
|
||||
const CODE: Record<MatchOutcome, string> = {
|
||||
victory: "MATCH · WIN",
|
||||
defeat: "MATCH · LOSS",
|
||||
draw: "MATCH · DRAW",
|
||||
victory: "MATCH / WIN",
|
||||
defeat: "MATCH / LOSS",
|
||||
draw: "MATCH / DRAW",
|
||||
};
|
||||
|
||||
export function MatchBanner({ outcome, mine, theirs, detail }: Props) {
|
||||
|
||||
@@ -17,11 +17,11 @@ function useClock(view: MatchClockView) {
|
||||
function Readout({ clock, names }: { clock: MatchClockView; names: string[] }) {
|
||||
const paused = clock.phase === "paused";
|
||||
const expired = paused && clock.pauseKind === "player" && clock.pauseRemainingMs === 0;
|
||||
const label = !paused ? MATCH_PHASE[clock.phase] : clock.pauseKind === "player" ? `选手技术暂停 · ${names[clock.applicant ?? 0]}` : "官方技术暂停";
|
||||
const label = !paused ? MATCH_PHASE[clock.phase] : clock.pauseKind === "player" ? `选手技术暂停 / ${names[clock.applicant ?? 0]}` : "官方技术暂停";
|
||||
return <div className={`match-readout${paused ? " is-paused" : ""}${!clock.connected ? " is-stale" : ""}`}>
|
||||
<div className="match-readout__phase"><i />{label}</div>
|
||||
<div className="match-readout__digits num">{paused ? matchTime(clock.pauseRemainingMs ?? clock.pauseElapsedMs, clock.pauseKind === "official") : clock.phase === "idle" ? "—:—" : matchTime(clock.remainingMs)}</div>
|
||||
<div className="match-readout__detail">{!clock.connected ? clock.source ? "计时同步中断 · 已冻结" : "等待裁判计时同步" : expired ? "暂停时间已到 · 等待裁判恢复" : paused ? `${clock.pauseKind === "official" ? "暂停已用时" : "暂停剩余"} · 暂停前剩余 ${matchTime(clock.remainingMs)}` : clock.phase === "running" || clock.phase === "finished" ? `对局已用时 ${matchTime(clock.elapsedMs, true)}` : clock.phase === "ready" ? "等待裁判确认开赛" : clock.phase === "countdown" ? "倒计时结束后开始对局" : "准备 3 分钟 / 对局 3 分钟"}</div>
|
||||
<div className="match-readout__detail">{!clock.connected ? clock.source ? "计时同步中断 / 已冻结" : "等待裁判计时同步" : expired ? "暂停时间已到 / 等待裁判恢复" : paused ? `${clock.pauseKind === "official" ? "暂停已用时" : "暂停剩余"} / 暂停前剩余 ${matchTime(clock.remainingMs)}` : clock.phase === "running" || clock.phase === "finished" ? `对局已用时 ${matchTime(clock.elapsedMs, true)}` : clock.phase === "ready" ? "等待裁判确认开赛" : clock.phase === "countdown" ? "倒计时结束后开始对局" : "准备 3 分钟 / 对局 3 分钟"}</div>
|
||||
{paused && <p className="match-readout__reason" title={clock.reason}>{clock.reason}</p>}
|
||||
</div>;
|
||||
}
|
||||
@@ -84,6 +84,7 @@ export function RefereeMatchControl({ snapshot, onError }: { snapshot: Snapshot;
|
||||
const [approved, setApproved] = useState(false);
|
||||
const [seconds, setSeconds] = useState(5);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const canReset = clock.phase === "finished" || snapshot.health.some(health => health.outcome != null);
|
||||
const active = ["preparation", "ready", "countdown", "running"].includes(clock.phase);
|
||||
const run = async (action: MatchAction, close?: () => void) => {
|
||||
if (busy) return;
|
||||
@@ -94,11 +95,24 @@ export function RefereeMatchControl({ snapshot, onError }: { snapshot: Snapshot;
|
||||
const openPause = (kind: "player" | "official") => { setReason(""); setApproved(false); setDialog(kind); };
|
||||
const reasonValid = reason.trim().length > 0 && new TextEncoder().encode(reason.trim()).length <= 192 && !/[\u0000-\u001f\u007f]/.test(reason);
|
||||
return <section className="match-control" aria-label="裁判比赛计时控制">
|
||||
<div className="match-control__identity"><span className="label">MATCH CONTROL</span><span>{snapshot.demo ? "本机演示 · 合成计时" : "裁判计时 / 局域网同步"}</span>{!snapshot.demo && <small className={snapshot.matchClock.syncError ? "is-error" : ""}>{snapshot.matchClock.syncError ?? "仅对局进行中扣血;准备与暂停时只闪灯"}</small>}</div>
|
||||
<div className="match-control__identity"><span className="label">MATCH CONTROL</span><span>{snapshot.demo ? "本机演示 / 合成计时" : "裁判计时 / 局域网同步"}</span>{!snapshot.demo && <small className={snapshot.matchClock.syncError ? "is-error" : ""}>{snapshot.matchClock.syncError ?? "仅对局进行中扣血;准备与暂停时只闪灯"}</small>}</div>
|
||||
<Readout clock={clock} names={snapshot.config.teamNames} />
|
||||
<div className="match-control__actions">
|
||||
{clock.phase === "idle" || clock.phase === "finished" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "prepare" })}><Icon name="timer" />开始 3 分钟准备</button> : clock.phase === "ready" ? <div className="match-control__start"><label>开赛倒计时 <input aria-label="开赛倒计时秒数" type="number" min="1" max="60" step="1" value={seconds} onChange={e => setSeconds(Number(e.target.value))} /> 秒</label><button className="btn btn--primary" disabled={busy || !Number.isInteger(seconds) || seconds < 1 || seconds > 60} onClick={() => void run({ type: "countdown", seconds })}><Icon name="play" />确认开赛</button></div> : clock.phase === "paused" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "resume" })}><Icon name="play" />恢复{clock.resumePhase === "preparation" ? "准备" : clock.resumePhase === "ready" ? "待开赛阶段" : clock.resumePhase === "countdown" ? "倒计时" : "对局"}</button> : <span className="match-control__hint">{clock.phase === "preparation" ? "准备结束后等待裁判确认开赛" : clock.phase === "countdown" ? "请选手就位" : "计时到零结束本局"}</span>}
|
||||
<div className="match-control__buttons"><button className="btn" disabled={busy || !active} onClick={() => openPause("player")}><Icon name="pause" />选手暂停</button><button className="btn" disabled={busy || !active} onClick={() => openPause("official")}><Icon name="pause" />官方暂停</button>{active || clock.phase === "paused" ? <button className="btn btn--quiet" disabled={busy} onClick={() => setDialog("end")}><Icon name="stop" />结束本局</button> : clock.phase === "finished" && <button className="btn btn--quiet" disabled={busy} onClick={() => void run({ type: "reset" })}><Icon name="reset" />清除计时</button>}</div>
|
||||
{canReset ? <>
|
||||
<span className="match-control__hint">{busy ? "等待装甲板回执与满血上报" : "重置后恢复满血,保留设备槽位和设置"}</span>
|
||||
<button className="btn btn--primary" disabled={busy} title="恢复装甲板满血,清除本局计时和结果,保留设备槽位与设置" onClick={() => void run({ type: "reset" })}><Icon name="reset" />{busy ? "正在重置本局…" : "重置到未开始"}</button>
|
||||
</> : <>
|
||||
{clock.phase === "idle" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "prepare" })}><Icon name="timer" />开始 3 分钟准备</button>
|
||||
: clock.phase === "preparation" ? <button className="btn" disabled={busy} title="结束准备,进入等待裁判确认开赛" onClick={() => void run({ type: "skipPreparation" })}><Icon name="play" />跳过准备倒计时</button>
|
||||
: clock.phase === "ready" ? <div className="match-control__start"><label>开赛倒计时 <input aria-label="开赛倒计时秒数" type="number" min="1" max="60" step="1" value={seconds} onChange={e => setSeconds(Number(e.target.value))} /> 秒</label><button className="btn btn--primary" disabled={busy || !Number.isInteger(seconds) || seconds < 1 || seconds > 60} onClick={() => void run({ type: "countdown", seconds })}><Icon name="play" />确认开赛</button></div>
|
||||
: clock.phase === "paused" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "resume" })}><Icon name="play" />恢复{clock.resumePhase === "preparation" ? "准备" : clock.resumePhase === "ready" ? "待开赛阶段" : clock.resumePhase === "countdown" ? "倒计时" : "对局"}</button>
|
||||
: <span className="match-control__hint">{clock.phase === "countdown" ? "请选手就位" : "计时到零结束本局"}</span>}
|
||||
<div className="match-control__buttons">
|
||||
<button className="btn" disabled={busy || !active} onClick={() => openPause("player")}><Icon name="pause" />选手暂停</button>
|
||||
<button className="btn" disabled={busy || !active} onClick={() => openPause("official")}><Icon name="pause" />官方暂停</button>
|
||||
{(active || clock.phase === "paused") && <button className="btn btn--quiet" disabled={busy} onClick={() => setDialog("end")}><Icon name="stop" />结束本局</button>}
|
||||
</div>
|
||||
</>}
|
||||
</div>
|
||||
{dialog && <Dialog title={dialog === "end" ? "结束本局计时" : dialog === "player" ? "选手技术暂停" : "官方技术暂停"} closeDisabled={busy} onClose={() => setDialog(null)} className="match-dialog">
|
||||
{close => <div className="match-dialog__body">{dialog === "end" ? <><p>结束当前计时并同步到选手端,同时停止装甲板扣血。比赛结果由裁判判定。</p><button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "end" }, close)}><Icon name="stop" />确认结束本局</button></> : <>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Snapshot } from "../lib/types";
|
||||
import { operatorGate, type useOperatorControl } from "../lib/use-operator-control";
|
||||
import { Icon } from "./Icon";
|
||||
import { Slider } from "./controls";
|
||||
import { OperatorMapping } from "./OperatorMapping";
|
||||
|
||||
export function OperatorControls({ control, snapshot, connected, blocked }: {
|
||||
control: ReturnType<typeof useOperatorControl>; snapshot: Snapshot; connected: boolean; blocked: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const root = useRef<HTMLElement>(null);
|
||||
const matchReason = operatorGate(snapshot, connected, "match");
|
||||
const debugReason = operatorGate(snapshot, connected, "debug");
|
||||
useEffect(() => { if (blocked || control.activeMode) setOpen(false); }, [blocked, control.activeMode]);
|
||||
useEffect(() => {
|
||||
const dismiss = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); };
|
||||
document.addEventListener("pointerdown", dismiss);
|
||||
return () => document.removeEventListener("pointerdown", dismiss);
|
||||
}, []);
|
||||
return <>
|
||||
<section ref={root} className="operator-controls" aria-label="机器人操作" onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()} onKeyDown={event => { if (open && event.key === "Escape") {event.stopPropagation();setOpen(false);} }}>
|
||||
<button className="btn operator-controls__toggle" role="switch" aria-checked={control.activeMode !== null} aria-expanded={open} aria-controls="operator-submenu" disabled={blocked || control.pending} onClick={() => control.activeMode ? control.stop() : setOpen(!open)}>
|
||||
<Icon name="gamepad" />{control.activeMode === "debug" ? "调试发送" : control.activeMode ? "操控发送" : "操控"}{control.activeMode ? <kbd>ESC</kbd> : <Icon name="chevron" className={open ? "is-open" : ""} />}
|
||||
</button>
|
||||
{open && <div className="operator-controls__menu" id="operator-submenu">
|
||||
<div className="operator-controls__actions">
|
||||
<button className="btn" disabled={!!matchReason} title={matchReason ?? "WASD / 鼠标 / 左键"} onClick={() => {setOpen(false);control.start("match");}}><Icon name="play" />比赛操作</button>
|
||||
<button className="btn" disabled={!!debugReason} title={debugReason ?? "未开赛时发送调试输入"} onClick={() => {setOpen(false);control.start("debug");}}><Icon name="build" />赛前调试</button>
|
||||
</div>
|
||||
<label className="operator-controls__sensitivity"><span>鼠标灵敏度(本次)</span><Slider min={0.25} max={4} step={0.25} value={control.sensitivity} onChange={control.setSensitivity} format={value => `×${value.toFixed(2)}`} /></label>
|
||||
{matchReason && debugReason && <small>{debugReason}</small>}
|
||||
{snapshot.demo && <small>合成预览</small>}
|
||||
{control.error && <small role="alert">{control.error}</small>}
|
||||
</div>}
|
||||
{!open && control.error && <span className="operator-controls__fault" role="alert" title={control.error}>操作已停止</span>}
|
||||
</section>
|
||||
{control.activeMode === "debug" && <OperatorMapping source={control.mapping} synthetic={snapshot.demo} />}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEffect, useState, type RefObject, type CSSProperties } from "react";
|
||||
import { neutralAxes, type OperatorAxes } from "../lib/operator-input";
|
||||
|
||||
/** 显示已提交的客户端通道值;不把它描述为串口回执或真实机构速度。 */
|
||||
export function OperatorMapping({ source, synthetic }: { source: RefObject<OperatorAxes>; synthetic: boolean }) {
|
||||
const [axes, setAxes] = useState(neutralAxes);
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setAxes({ ...source.current }), 40);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [source]);
|
||||
const channels = [["CH0", "W / S", "前后", axes.forward], ["CH1", "A / D", "左右", axes.strafe], ["CH2", "MOUSE X", "水平", axes.yaw], ["CH3", "MOUSE Y", "俯仰", axes.pitch]] as const;
|
||||
return <div className="operator-mapping" aria-label="调试协议映射">
|
||||
<header><span>CONTROL / MAPPING</span><b>{synthetic ? "合成输入" : "客户端输入"}</b></header>
|
||||
<div className="operator-mapping__flow"><span>键鼠</span><i>→</i><span>UDP</span><i>→</i><span>C3 / UART</span></div>
|
||||
<div className="operator-mapping__channels">{channels.map(([id, input, label, value]) => <div className="operator-mapping__channel" key={id}>
|
||||
<span>{input}</span><span>{id} / {label}</span><strong className="num">{value > 0 ? "+" : ""}{value}</strong>
|
||||
<div className="operator-mapping__track"><i style={{left: `${50 + Math.min(0, value / 20)}%`, width: `${Math.abs(value) / 20}%`} as CSSProperties} /><b /></div>
|
||||
</div>)}</div>
|
||||
<footer><span className={axes.fire ? "is-firing" : ""}>LMB → FIRE <b>{Number(axes.fire)}</b></span><span>±1000 速度比例</span><span>ESC 退出</span></footer>
|
||||
</div>;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function OperatorMenu({ snapshot, fullscreen, onClose, onSettings, onMain
|
||||
<div className="operator-menu__identity"><span className="label">RMIC :: 2026 / OPERATOR</span><h1>操作菜单<span>MENU</span></h1><p>打开菜单后,图传和受击上报仍会继续。</p>{snapshot.demo && <span className="tag tag--warn">预览 / 合成数据</span>}</div>
|
||||
<nav className="operator-menu__actions" aria-label="操作菜单">
|
||||
<button data-initial-focus onClick={close}><span><Icon name="play" />继续操作</span><kbd>ESC</kbd></button>
|
||||
<button onClick={onSettings}><span><Icon name="settings" />画面与设备设置</span><small>准星 · 图传绑定 · 装甲板</small></button>
|
||||
<button onClick={onSettings}><span><Icon name="settings" />画面与设备设置</span><small>准星 / 图传绑定 / 装甲板</small></button>
|
||||
<button onClick={onMaintenance}><span><Icon name="firmware" />固件维护</span><small>编译与 USB 烧录</small></button>
|
||||
<button onClick={() => { setError(""); setReconnect(true); }}><span><Icon name="reconnect" />重新接收裁判计时</span><small>{snapshot.matchClock.source ?? "等待裁判广播"}</small></button>
|
||||
<button onClick={onFullscreen}><span><Icon name={fullscreen ? "fullscreenExit" : "fullscreen"} />{fullscreen ? "退出全屏" : "全屏显示"}</span><kbd>F11</kbd></button>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent }
|
||||
import { api } from "../lib/ipc";
|
||||
import { BUILD, VERSION_LABEL } from "../lib/version";
|
||||
import { firmwareLabel, teamName } from "../lib/format";
|
||||
import { paintCrosshair, paintGrid, type Geometry } from "../lib/reticle";
|
||||
import { aimPoint, paintCrosshair, paintGrid, type Geometry } from "../lib/reticle";
|
||||
import type { ConfigView, CrosshairConfig, HudView, Snapshot, TeamHealthDto } from "../lib/types";
|
||||
import { Button, Field, Select, Slider, Switch } from "./controls";
|
||||
import { HealthBar } from "./HealthBar";
|
||||
@@ -101,11 +101,11 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
|
||||
const cameraOptions = useMemo(() => snapshot.cameras.map(camera => ({
|
||||
value: camera.id, label: camera.idText,
|
||||
hint: `${camera.addr} · ${camera.online ? "在线" : "离线"} · 固件 ${firmwareLabel(camera)}${camera.compatible ? "" : ` · 协议 ${camera.protocol} 不匹配`}`,
|
||||
hint: `${camera.addr} / ${camera.online ? "在线" : "离线"} / 固件 ${firmwareLabel(camera)}${camera.compatible ? "" : ` / 协议 ${camera.protocol} 不匹配`}`,
|
||||
})), [snapshot.cameras]);
|
||||
const armorOptions = useMemo(() => snapshot.armorBoards.map(board => ({
|
||||
value: board.id, label: board.idText,
|
||||
hint: `${board.addr} · ${teamName(board.team, config.teamNames)} · ${board.hp} 血 · ${board.online ? "在线" : "离线"}`,
|
||||
hint: `${board.addr} / ${teamName(board.team, config.teamNames)} / ${board.hp} 血 / ${board.online ? "在线" : "离线"}`,
|
||||
})), [snapshot.armorBoards, config.teamNames]);
|
||||
|
||||
const categories = useMemo<Category[]>(() => [
|
||||
@@ -154,8 +154,12 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
const camera = snapshot.cameras.find(item => item.id === config.cameraId);
|
||||
const cameraStats = snapshot.stats.find(item => item.camera === config.cameraId);
|
||||
const board = snapshot.armorBoards.find(item => item.id === config.armorId);
|
||||
const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 · 等待画面";
|
||||
const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 / 等待画面";
|
||||
const armorState = !connected ? "本地通道断开" : config.armorId === null ? "未绑定" : !board?.online ? "离线" : board.team === 255 ? "等待队伍设置" : board.team !== config.team ? "队伍不匹配" : "在线";
|
||||
const mirrorControls = <>
|
||||
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
|
||||
<Switch checked={config.mirrorVertical} label="上下镜像画面" onChange={mirror => void run(() => api.setMirrorVertical(mirror))} />
|
||||
</>;
|
||||
|
||||
const content = () => {
|
||||
switch (current.id) {
|
||||
@@ -185,7 +189,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
{ value: 1, label: `${teamName(1, config.teamNames)}(蓝)` },
|
||||
]} onChange={team => void run(() => api.setTeam(team))} />
|
||||
</Field>
|
||||
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
|
||||
{mirrorControls}
|
||||
<div className="settings__device-state settings__span" aria-live="polite">
|
||||
<span><b>图传</b><strong>{config.cameraIdText ?? "—"}</strong><em>{cameraState}</em></span>
|
||||
<span><b>装甲板</b><strong>{config.armorIdText ?? "—"}</strong><em>{armorState}</em></span>
|
||||
@@ -228,11 +232,12 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
{snapshot.diagnostics && <Switch checked={hud.showStats} label="显示丢包率(诊断模式)" onChange={showStats => update(draft => { draft.showStats = showStats; })} />}
|
||||
</>;
|
||||
case "slots": return <>
|
||||
{mirrorControls}
|
||||
<div className="settings__span"><Switch checked={snapshot.slots.manual} label="手动指定槽位" onChange={manual => void run(() => api.setRefereeSlots({ ...snapshot.slots, manual }))} /></div>
|
||||
<Field label={`左格 · ${teamName(0, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraA} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraA => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /></Field>
|
||||
<Field label={`右格 · ${teamName(1, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraB} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraB => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraB, manual: true }))} /></Field>
|
||||
<Field label={`左格 · ${teamName(0, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorA} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorA => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorA, manual: true }))} /></Field>
|
||||
<Field label={`右格 · ${teamName(1, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorB} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorB => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorB, manual: true }))} /></Field>
|
||||
<Field label={`左格 / ${teamName(0, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraA} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraA => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /></Field>
|
||||
<Field label={`右格 / ${teamName(1, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraB} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraB => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraB, manual: true }))} /></Field>
|
||||
<Field label={`左格 / ${teamName(0, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorA} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorA => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorA, manual: true }))} /></Field>
|
||||
<Field label={`右格 / ${teamName(1, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorB} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorB => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorB, manual: true }))} /></Field>
|
||||
</>;
|
||||
case "media": return <>
|
||||
<div className="settings__span"><Field label="输出目录"><input className="input" type="text" defaultValue={config.recordingDir} onBlur={event => {
|
||||
@@ -288,12 +293,12 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
<div className="settings__page-head"><span className="label">{current.en}</span><h2>{current.label}</h2><p>{current.hint}</p></div>
|
||||
<div className="settings__workspace">
|
||||
<fieldset className="settings__form" disabled={locked || closing}>{content()}</fieldset>
|
||||
{current.preview && <Preview hud={hud} team={snapshot.team} />}
|
||||
{current.preview && <Preview hud={hud} team={snapshot.team} mirrored={config.mirror} mirroredVertical={config.mirrorVertical} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<footer className="settings__foot"><span>{pending ? "等待保存…" : "修改自动保存"}<span className="settings__save-note"> · 停止拖动滑杆 350 ms 后自动保存</span></span><span className="num">{VERSION_LABEL} · 线路协议 {BUILD.protocol}</span></footer>
|
||||
<footer className="settings__foot"><span>{pending ? "等待保存…" : "修改自动保存"}<span className="settings__save-note"> / 停止拖动滑杆 350 ms 后自动保存</span></span><span className="num">{VERSION_LABEL} / 线路协议 {BUILD.protocol}</span></footer>
|
||||
</aside>;
|
||||
}
|
||||
|
||||
@@ -307,7 +312,7 @@ export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating
|
||||
*
|
||||
* 血量那根滑杆是刻意加的:低血阈值与脉动只有真的把血拖下去才看得见。
|
||||
*/
|
||||
function Preview({ hud, team }: { hud: HudView; team: number }) {
|
||||
function Preview({ hud, team, mirrored, mirroredVertical }: { hud: HudView; team: number; mirrored: boolean; mirroredVertical: boolean }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const [demoHp, setDemoHp] = useState(68);
|
||||
|
||||
@@ -329,6 +334,9 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
||||
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
ctx.save();
|
||||
ctx.translate(mirrored ? width : 0, mirroredVertical ? height : 0);
|
||||
ctx.scale(mirrored ? -1 : 1, mirroredVertical ? -1 : 1);
|
||||
|
||||
// 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景
|
||||
// 之上"的参照,而不是浮在一片纯黑里看不出对比。
|
||||
@@ -354,12 +362,12 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
||||
};
|
||||
|
||||
if (hud.grid.visible) paintGrid(ctx, geometry, hud.grid);
|
||||
ctx.restore();
|
||||
|
||||
if (hud.crosshair.visible) {
|
||||
// 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。
|
||||
const cx = width * (0.5 + hud.crosshair.offsetX);
|
||||
const cy = height * (0.5 + hud.crosshair.offsetY);
|
||||
paintCrosshair(ctx, cx, cy, Math.min(width, height), hud.crosshair);
|
||||
const aim = aimPoint(geometry, hud.crosshair, mirrored, width, height, mirroredVertical);
|
||||
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), hud.crosshair);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -374,7 +382,7 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
||||
cancelAnimationFrame(raf);
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [hud]);
|
||||
}, [hud, mirrored, mirroredVertical]);
|
||||
|
||||
// 预览用的血量。`available` 恒为 true:占位符的形态在真画面上看更清楚。
|
||||
const mock: TeamHealthDto = {
|
||||
@@ -394,7 +402,7 @@ function Preview({ hud, team }: { hud: HudView; team: number }) {
|
||||
<div className="preview">
|
||||
<div className="preview__head">
|
||||
<span className="label">HUD PREVIEW</span>
|
||||
<span className="preview__note">合成画面 · 非设备图传</span>
|
||||
<span className="preview__note">合成画面 / 非设备图传</span>
|
||||
</div>
|
||||
|
||||
<div className="preview__frame corners">
|
||||
|
||||
@@ -49,7 +49,7 @@ export function TopBar({
|
||||
<div className="topbar__cluster">
|
||||
{/* 队标只以"字标"的形态出现在顶栏:它的笔画在 17px 上只剩 1px,缩到这么小
|
||||
会糊成一团反而更难看。完整的队标留给启动页(在那里它有 30px)。 */}
|
||||
<span className="topbar__brand" title="RMIC::2026 · Simba Robotics">
|
||||
<span className="topbar__brand" title="RMIC::2026 / Simba Robotics">
|
||||
<span className="topbar__wordmark">
|
||||
RMIC<span className="topbar__slash">::</span>2026
|
||||
</span>
|
||||
@@ -71,7 +71,7 @@ export function TopBar({
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="info" />演示 · 合成数据
|
||||
<Icon name="info" />演示 / 合成数据
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -80,7 +80,7 @@ export function TopBar({
|
||||
{!connected && (
|
||||
<span className="tag tag--warn">
|
||||
<span className="dot dot--warn" />
|
||||
通道断开 · 重连中
|
||||
通道断开 / 重连中
|
||||
</span>
|
||||
)}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* - **网格**画在图像矩形里,跟着缩放走:它标的是画面里的比例,用来估距离。
|
||||
* - **瞄准器**的**位置**跟着图像走,**大小**不跟着:像真瞄具一样,放大之后准星不会
|
||||
* 跟着变粗,而是覆盖画面里更小的一块——那正是放大有用武之地的原因。
|
||||
* - 镜像靠 `scale(-1, 1)`,同时把拖动方向也翻过来,否则向右拖画面会往左走。
|
||||
* - 左右、上下镜像分别反转对应轴,同时反转拖动输入,让画面跟随鼠标移动。
|
||||
*
|
||||
* # 缩放是"追"上去的,平移是"贴"着手的
|
||||
*
|
||||
@@ -63,12 +63,15 @@ interface Props {
|
||||
camera: number | null;
|
||||
emptyText: string;
|
||||
mirrored: boolean;
|
||||
mirroredVertical?: boolean;
|
||||
crosshair: CrosshairConfig | null;
|
||||
grid: GridConfig | null;
|
||||
view: ViewTransform;
|
||||
onView: (view: ViewTransform) => void;
|
||||
/** 校准模式:拖动画面来挪瞄准点。 */
|
||||
calibrating?: boolean;
|
||||
/** FPS 操作时停用画面拖动和缩放,输入由选手端捕获。 */
|
||||
inputCaptured?: boolean;
|
||||
onCalibrate?: (dxFraction: number, dyFraction: number) => void;
|
||||
/** 命中脉冲。只有属于这一路的命中才该传进来。 */
|
||||
hit?: HitPulse | null;
|
||||
@@ -80,7 +83,7 @@ interface Props {
|
||||
children?: ReactNode;
|
||||
/** Only used by the opt-in screen/camera calibration page. */
|
||||
onFramePainted?: (canvas: HTMLCanvasElement, frame: FrameInfo, drawMs: number) => void;
|
||||
/** 左上角的代号(`CAM · A`、队名)。缺省时不画。 */
|
||||
/** 左上角的代号(`CAM / A`、队名)。缺省时不画。 */
|
||||
label?: string;
|
||||
/** 这一路被"选中"了(裁判端的 scope)。视觉上给一圈亮框。 */
|
||||
focused?: boolean;
|
||||
@@ -100,11 +103,13 @@ export function VideoSurface({
|
||||
camera,
|
||||
emptyText,
|
||||
mirrored,
|
||||
mirroredVertical = false,
|
||||
crosshair,
|
||||
grid,
|
||||
view,
|
||||
onView,
|
||||
calibrating = false,
|
||||
inputCaptured = false,
|
||||
onCalibrate,
|
||||
hit = null,
|
||||
hitFeedback,
|
||||
@@ -120,8 +125,8 @@ export function VideoSurface({
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
// 绘制循环不随 props 重建,所以最新一份 props 放在 ref 里给它读。
|
||||
const props = useRef({ camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted });
|
||||
props.current = { camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted };
|
||||
const props = useRef({ camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback, onFramePainted });
|
||||
props.current = { camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback, onFramePainted };
|
||||
|
||||
/** 屏幕上**当前**的视图。它追着 `view` 走,但有自己的惯性。 */
|
||||
const shown = useRef<ViewTransform>({ ...view });
|
||||
@@ -132,7 +137,7 @@ export function VideoSurface({
|
||||
|
||||
useEffect(() => {
|
||||
dirty.current = true;
|
||||
}, [camera, mirrored, crosshair, grid, view, hit, hitFeedback]);
|
||||
}, [camera, mirrored, mirroredVertical, crosshair, grid, view, hit, hitFeedback]);
|
||||
|
||||
// canvas 的像素尺寸跟着 CSS 尺寸与 DPR 走。不这么做的话在 Retina 上会糊。
|
||||
useEffect(() => {
|
||||
@@ -224,6 +229,7 @@ export function VideoSurface({
|
||||
// ---- 输入 ----
|
||||
|
||||
const onWheel = (event: React.WheelEvent<HTMLDivElement>) => {
|
||||
if (inputCaptured) return;
|
||||
const factor = event.deltaY > 0 ? 1 / ZOOM_STEP : ZOOM_STEP;
|
||||
const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);
|
||||
|
||||
@@ -233,6 +239,7 @@ export function VideoSurface({
|
||||
};
|
||||
|
||||
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (inputCaptured || (event.target as HTMLElement).closest("button, input, select, a")) return;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
dragging.current = true;
|
||||
drag.current = { x: event.clientX, y: event.clientY, originX: view.x, originY: view.y };
|
||||
@@ -240,6 +247,7 @@ export function VideoSurface({
|
||||
};
|
||||
|
||||
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (inputCaptured) return;
|
||||
const start = drag.current;
|
||||
if (!start) return;
|
||||
|
||||
@@ -261,15 +269,15 @@ export function VideoSurface({
|
||||
// 一次移动一小步,然后把起点挪过来。
|
||||
drag.current = { ...start, x: event.clientX, y: event.clientY };
|
||||
const sign = mirrored ? -1 : 1;
|
||||
onCalibrate((sign * dx) / drawWidth, dy / drawHeight);
|
||||
onCalibrate((sign * dx) / drawWidth, ((mirroredVertical ? -1 : 1) * dy) / drawHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
if (view.zoom <= MIN_ZOOM) return;
|
||||
|
||||
// 镜像时把横向拖动也翻过来:否则向右拖,画面往左走,看起来像拖动坏了。
|
||||
// 镜像时反转对应轴的输入,保持画面跟随鼠标移动。
|
||||
const sign = mirrored ? -1 : 1;
|
||||
onView({ ...view, x: start.originX + sign * dx, y: start.originY + dy });
|
||||
onView({ ...view, x: start.originX + sign * dx, y: start.originY + (mirroredVertical ? -dy : dy) });
|
||||
};
|
||||
|
||||
const endDrag = () => {
|
||||
@@ -277,7 +285,7 @@ export function VideoSurface({
|
||||
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 moved = view.zoom > MIN_ZOOM + 0.05 || view.x !== 0 || view.y !== 0;
|
||||
|
||||
@@ -296,7 +304,7 @@ export function VideoSurface({
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={endDrag}
|
||||
onPointerCancel={endDrag}
|
||||
onDoubleClick={() => onView(IDENTITY_VIEW)}
|
||||
onDoubleClick={() => { if (!inputCaptured) onView(IDENTITY_VIEW); }}
|
||||
>
|
||||
<canvas ref={canvasRef} className="vsurface__canvas" />
|
||||
{signalLost && <div className="vsurface__signal-mask" aria-hidden="true" />}
|
||||
@@ -343,7 +351,7 @@ export function VideoSurface({
|
||||
{calibrating && (
|
||||
<div className="vsurface__calibrating">
|
||||
<span className="dot dot--live" />
|
||||
校准中 · 拖动画面调整瞄准点
|
||||
校准中 / 拖动画面调整瞄准点
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -359,6 +367,7 @@ export function VideoSurface({
|
||||
interface CanvasProps {
|
||||
camera: number | null;
|
||||
mirrored: boolean;
|
||||
mirroredVertical: boolean;
|
||||
crosshair: CrosshairConfig | null;
|
||||
grid: GridConfig | null;
|
||||
hit: HitPulse | null;
|
||||
@@ -392,21 +401,18 @@ function draw(
|
||||
if (frame) {
|
||||
ctx.save();
|
||||
|
||||
if (current.mirrored) {
|
||||
ctx.translate(width, 0);
|
||||
ctx.scale(-1, 1);
|
||||
}
|
||||
ctx.translate(current.mirrored ? width : 0, current.mirroredVertical ? height : 0);
|
||||
ctx.scale(current.mirrored ? -1 : 1, current.mirroredVertical ? -1 : 1);
|
||||
|
||||
// 放大超过 3 倍时关掉插值:这时候要看的是像素本身,双线性插值只会把它糊掉。
|
||||
ctx.imageSmoothingEnabled = view.zoom < 3;
|
||||
ctx.drawImage(frame.bitmap, geometry.left, geometry.top, geometry.drawWidth, geometry.drawHeight);
|
||||
ctx.restore();
|
||||
|
||||
if (current.grid?.visible) paintGrid(ctx, geometry, current.grid);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
const crosshair = current.crosshair;
|
||||
const aim = aimPoint(geometry, crosshair, current.mirrored, width, height);
|
||||
const aim = aimPoint(geometry, crosshair, current.mirrored, width, height, current.mirroredVertical);
|
||||
|
||||
if (crosshair?.visible) {
|
||||
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), crosshair);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
const previewMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }> = {};
|
||||
/**
|
||||
* 仅开发用的浏览器预览。
|
||||
*
|
||||
@@ -28,7 +29,7 @@
|
||||
|
||||
import { DEFAULT_TEAM_NAMES } from "./format";
|
||||
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 {
|
||||
ConfigView,
|
||||
@@ -113,11 +114,14 @@ interface PreviewState {
|
||||
/** 两边显示的名字,与后端配置里的 `teamNames` 对应。 */
|
||||
teamNames: [string, string];
|
||||
mirror: boolean;
|
||||
mirrorVertical: boolean;
|
||||
unlocked: boolean;
|
||||
password: string | null;
|
||||
calibrating: boolean;
|
||||
recordings: { camera: number; frames: number; startedMs: number }[];
|
||||
hp: [number, number];
|
||||
matchControlled: boolean;
|
||||
finalOutcomes: ["victory" | "defeat" | "draw" | null, "victory" | "defeat" | "draw" | null] | null;
|
||||
}
|
||||
|
||||
const state: PreviewState = {
|
||||
@@ -128,13 +132,30 @@ const state: PreviewState = {
|
||||
team: 0,
|
||||
teamNames: wideLayoutPreview ? ["用户端长队名布局验证一队", "用户端长队名布局验证二队"] : ["队伍一", "队伍二"],
|
||||
mirror: true,
|
||||
mirrorVertical: false,
|
||||
// 预览里直接是已解锁状态,免得每次刷新都要输密码。
|
||||
unlocked: false,
|
||||
password: "1234",
|
||||
calibrating: false,
|
||||
recordings: [],
|
||||
hp: [100, 100],
|
||||
matchControlled: new URLSearchParams(location.search).has("match"),
|
||||
finalOutcomes: null,
|
||||
};
|
||||
if (new URLSearchParams(location.search).get("match") === "finished") {
|
||||
state.hp = [0, 76]; state.finalOutcomes = ["defeat", "victory"];
|
||||
}
|
||||
if (new URLSearchParams(location.search).get("health") === "blue-low") {
|
||||
state.hp = [73, 10]; state.matchControlled = true;
|
||||
}
|
||||
|
||||
function finishPreviewKnockout() {
|
||||
const clock = previewMatch();
|
||||
if (state.finalOutcomes || !state.matchControlled || (clock.phase !== "running" && !(clock.phase === "paused" && clock.resumePhase === "running")) || !state.hp.includes(0)) return;
|
||||
state.finalOutcomes = state.hp[0] === 0 && state.hp[1] === 0 ? ["draw", "draw"]
|
||||
: state.hp[0] === 0 ? ["defeat", "victory"] : ["victory", "defeat"];
|
||||
previewMatchAction({ type: "end" });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 假的命令实现
|
||||
@@ -146,12 +167,37 @@ export async function previewInvoke<T>(command: string, args?: Record<string, un
|
||||
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 {
|
||||
switch (command) {
|
||||
case "match_action":
|
||||
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
||||
previewMatchAction(args.action as MatchAction);
|
||||
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": {
|
||||
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
||||
const action = args.action as MatchAction;
|
||||
if (action.type === "prepare" && state.finalOutcomes) throw new Error("请先重置本局");
|
||||
previewMatchAction(action);
|
||||
state.matchControlled = true;
|
||||
if (action.type === "reset") { state.hp = [100, 100]; state.finalOutcomes = null; }
|
||||
return;
|
||||
}
|
||||
case "release_match_source": return;
|
||||
case "stream_info":
|
||||
return { url: "preview://", port: 0, clients: 1 };
|
||||
@@ -198,9 +244,15 @@ function handle(command: string, args: Record<string, unknown>): unknown {
|
||||
case "set_role":
|
||||
state.role = args.role as "team" | "referee";
|
||||
return configView();
|
||||
case "set_camera_mirror":
|
||||
previewMirrors[String(args.camera)] = { mirror: Boolean(args.mirror), mirrorVertical: Boolean(args.mirrorVertical) };
|
||||
return;
|
||||
case "set_mirror":
|
||||
state.mirror = Boolean(args.mirror);
|
||||
return configView();
|
||||
case "set_mirror_vertical":
|
||||
state.mirrorVertical = Boolean(args.mirrorVertical);
|
||||
return configView();
|
||||
case "save_hud":
|
||||
state.hud = args.hud as HudView;
|
||||
return configView();
|
||||
@@ -258,6 +310,7 @@ function configView(): ConfigView {
|
||||
armorId: state.armorId,
|
||||
armorIdText: state.armorId === null ? null : hex(state.armorId),
|
||||
mirror: state.mirror,
|
||||
mirrorVertical: state.mirrorVertical,
|
||||
passwordSet: needsPassword ? false : state.password !== null,
|
||||
hud: structuredClone(state.hud),
|
||||
recordingDir: "/预览模式/recordings",
|
||||
@@ -291,6 +344,12 @@ function hex(id: number): string {
|
||||
}
|
||||
|
||||
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();
|
||||
const cameraOffline = videoOffline();
|
||||
const cameras = [
|
||||
{ id: CAMERA_A, team: 0 },
|
||||
@@ -343,6 +402,8 @@ function snapshot(): Snapshot {
|
||||
// 与后端 `cam_core::snapshot::resolve_outcomes` 同一套规则,包括那条不对称:
|
||||
// 输只看自己,赢要看对手归零**且**自己还活着。
|
||||
const outcomeFor = (team: number) => {
|
||||
if (state.finalOutcomes) return state.finalOutcomes[team];
|
||||
if (state.matchControlled && previewMatch().phase === "finished") return null;
|
||||
const mine = state.hp[team];
|
||||
const theirs = state.hp[team === 0 ? 1 : 0];
|
||||
|
||||
@@ -374,7 +435,10 @@ function snapshot(): Snapshot {
|
||||
role: state.role,
|
||||
team: state.team,
|
||||
mirrored: state.mirror,
|
||||
mirroredVertical: state.mirrorVertical,
|
||||
cameraMirrors: previewMirrors,
|
||||
matchClock: previewMatch(),
|
||||
operatorControl: { ...previewOperator },
|
||||
demo: true,
|
||||
diagnostics: true,
|
||||
unlocked: state.unlocked || state.role === "referee",
|
||||
@@ -453,11 +517,12 @@ export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void)
|
||||
let tick = 0;
|
||||
const hitTimer = window.setInterval(() => {
|
||||
if (offlinePreview) return;
|
||||
if (state.matchControlled && previewMatch().phase !== "running") return;
|
||||
tick += 1;
|
||||
const team = tick % 2;
|
||||
|
||||
if (state.hp[team] === 0) {
|
||||
state.hp[team] = 100;
|
||||
if (!state.matchControlled) state.hp[team] = 100;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -465,6 +530,7 @@ export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void)
|
||||
const damage = 3 + ((tick * 7) % 20);
|
||||
const to = Math.max(0, from - damage);
|
||||
state.hp[team] = to;
|
||||
finishPreviewKnockout();
|
||||
|
||||
emit({
|
||||
t: "hit",
|
||||
@@ -568,7 +634,7 @@ function draw(canvas: HTMLCanvasElement, team: number, frameId: number) {
|
||||
|
||||
ctx.font = "600 20px ui-monospace, monospace";
|
||||
ctx.fillStyle = "#e8e8ec";
|
||||
ctx.fillText(team === 0 ? "PREVIEW · TEAM 1" : "PREVIEW · TEAM 2", 14, height - 40);
|
||||
ctx.fillText(team === 0 ? "PREVIEW / TEAM 1" : "PREVIEW / TEAM 2", 14, height - 40);
|
||||
ctx.font = "500 16px ui-monospace, monospace";
|
||||
ctx.fillStyle = "#8a8a95";
|
||||
ctx.fillText(`frame ${frameId}`, 14, height - 16);
|
||||
|
||||
@@ -75,7 +75,7 @@ export function teamColor(team: number): string {
|
||||
return team === 0 ? "var(--team-0)" : "var(--team-1)";
|
||||
}
|
||||
/**
|
||||
* 固件版本的一行标签:`v0.2.0 · 34`。
|
||||
* 固件版本的一行标签:`v0.2.0 / 34`。
|
||||
*
|
||||
* 板子太老、没带版本字段时返回"版本未知"——不要拼出一个 `v0.0.0`,那是假信息。
|
||||
*/
|
||||
@@ -87,6 +87,6 @@ export function firmwareLabel(camera: {
|
||||
return camera.firmwareBuild > 0 ? `构建 ${camera.firmwareBuild}` : "版本未知";
|
||||
}
|
||||
return camera.firmwareBuild > 0
|
||||
? `v${camera.firmwareVersion} · ${camera.firmwareBuild}`
|
||||
? `v${camera.firmwareVersion} / ${camera.firmwareBuild}`
|
||||
: `v${camera.firmwareVersion}`;
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import type {
|
||||
Snapshot,
|
||||
MatchAction,
|
||||
StreamInfo,
|
||||
OperatorInput,
|
||||
OperatorMode,
|
||||
} from "./types";
|
||||
|
||||
/**
|
||||
@@ -44,6 +46,8 @@ async function call<T>(command: string, args?: Record<string, unknown>): Promise
|
||||
}
|
||||
|
||||
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 }),
|
||||
releaseMatchSource: () => call<void>("release_match_source"),
|
||||
// ---- 只读 ----
|
||||
@@ -69,7 +73,9 @@ export const api = {
|
||||
call<ConfigView>("set_team", { team, password: password ?? null }),
|
||||
setRole: (role: Role, password?: string) =>
|
||||
call<ConfigView>("set_role", { role, password: password ?? null }),
|
||||
setCameraMirror: (camera: number, mirror: boolean, mirrorVertical: boolean) => call<void>("set_camera_mirror", { camera, mirror, mirrorVertical }),
|
||||
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
||||
setMirrorVertical: (mirrorVertical: boolean) => call<ConfigView>("set_mirror_vertical", { mirrorVertical }),
|
||||
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
||||
/** 改一边的队名(0 = 队伍一,1 = 队伍二)。一次只改一边,避免覆盖另一边的改动。 */
|
||||
setTeamName: (team: number, name: string, password?: string) =>
|
||||
|
||||
@@ -31,6 +31,9 @@ export function previewMatchAction(action: MatchAction) {
|
||||
previewMatch();
|
||||
switch (action.type) {
|
||||
case "prepare": view = { ...blank(), phase: "preparation", remainingMs: 180_000 }; break;
|
||||
case "skipPreparation":
|
||||
if (view.phase !== "preparation" && view.phase !== "ready") throw new Error("当前阶段不能跳过准备");
|
||||
view.phase = "ready"; view.remainingMs = 0; break;
|
||||
case "countdown": view.phase = "countdown"; view.remainingMs = action.seconds * 1000; break;
|
||||
case "pausePlayer":
|
||||
if (!action.approved) throw new Error("选手技术暂停须经主裁判批准");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { MatchClockView, MatchPhase } from "./types";
|
||||
|
||||
export const MATCH_PHASE: Record<MatchPhase, string> = {
|
||||
idle: "等待准备", preparation: "赛前准备", ready: "准备结束 · 等待裁判", countdown: "开赛倒计时",
|
||||
idle: "等待准备", preparation: "赛前准备", ready: "准备结束 / 等待裁判", countdown: "开赛倒计时",
|
||||
running: "对局进行中", paused: "技术暂停", finished: "本局计时结束",
|
||||
};
|
||||
export function matchTime(ms: number, countingUp = false): string {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ export function computeLayout(
|
||||
/**
|
||||
* 瞄准点的屏幕位置。
|
||||
*
|
||||
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时横向要翻过来,
|
||||
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时对应轴要翻过来,
|
||||
* 否则准星会站在画面的另一边——偏移量是相对**摄像头光轴**定的,光轴在镜像之后换了位置。
|
||||
*/
|
||||
export function aimPoint(
|
||||
@@ -67,15 +67,17 @@ export function aimPoint(
|
||||
mirrored: boolean,
|
||||
canvasWidth: number,
|
||||
canvasHeight: number,
|
||||
mirroredVertical = false,
|
||||
): { x: number; y: number } {
|
||||
if (!crosshair || geometry.drawWidth <= 0) {
|
||||
return { x: canvasWidth / 2, y: canvasHeight / 2 };
|
||||
}
|
||||
|
||||
const rawX = geometry.left + (0.5 + crosshair.offsetX) * geometry.drawWidth;
|
||||
const rawY = geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight;
|
||||
return {
|
||||
x: mirrored ? canvasWidth - rawX : rawX,
|
||||
y: geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight,
|
||||
y: mirroredVertical ? canvasHeight - rawY : rawY,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,9 @@ function handleMessage(msg: WireMsg) {
|
||||
return; // Consumed by StreamClient before reaching application state.
|
||||
case "snapshot": {
|
||||
const { t: _tag, ...snapshot } = msg;
|
||||
emit({ snapshot: snapshot as Snapshot });
|
||||
const reset = snapshot.matchClock.phase === "idle" && (store.snapshot?.matchClock.phase !== "idle"
|
||||
|| store.snapshot?.health.some(health => health.outcome != null));
|
||||
emit({ snapshot: snapshot as Snapshot, ...(reset ? { lastHit: null } : {}) });
|
||||
return;
|
||||
}
|
||||
case "hit":
|
||||
|
||||
+25
-1
@@ -10,6 +10,26 @@
|
||||
|
||||
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` */
|
||||
export type CrosshairStyle = "cross" | "cross-dot" | "circle-dot" | "dot";
|
||||
|
||||
@@ -89,6 +109,7 @@ export interface ConfigView {
|
||||
armorId: number | null;
|
||||
armorIdText: string | null;
|
||||
mirror: boolean;
|
||||
mirrorVertical: boolean;
|
||||
passwordSet: boolean;
|
||||
hud: HudView;
|
||||
recordingDir: string;
|
||||
@@ -206,10 +227,13 @@ export interface MediaFileDto {
|
||||
|
||||
/** `cam_core::snapshot::Snapshot` */
|
||||
export interface Snapshot {
|
||||
cameraMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }>;
|
||||
operatorControl: OperatorControlView;
|
||||
matchClock: MatchClockView;
|
||||
role: Role;
|
||||
team: number;
|
||||
mirrored: boolean;
|
||||
mirroredVertical: boolean;
|
||||
demo: boolean;
|
||||
diagnostics: boolean;
|
||||
unlocked: boolean;
|
||||
@@ -242,7 +266,7 @@ export interface MatchClockView {
|
||||
source: string | null;
|
||||
syncError: string | null;
|
||||
}
|
||||
export type MatchAction = { type: "prepare" | "resume" | "end" | "reset" }
|
||||
export type MatchAction = { type: "prepare" | "skipPreparation" | "resume" | "end" | "reset" }
|
||||
| { type: "countdown"; seconds: number }
|
||||
| { type: "pausePlayer"; team: number; reason: string; approved: boolean }
|
||||
| { type: "pauseOfficial"; reason: string };
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
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 mapping = useRef(neutralAxes());
|
||||
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 = "") => {
|
||||
mapping.current = neutralAxes();
|
||||
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; }
|
||||
mapping.current = sampled.axes;
|
||||
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 { mapping, target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
||||
}
|
||||
@@ -6,16 +6,16 @@
|
||||
*/
|
||||
|
||||
export const BUILD = {
|
||||
version: "0.3.0",
|
||||
version: "0.6.1",
|
||||
major: 0,
|
||||
minor: 3,
|
||||
patch: 0,
|
||||
minor: 6,
|
||||
patch: 1,
|
||||
/** git 提交数,单调递增。 */
|
||||
build: 42,
|
||||
build: 48,
|
||||
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
||||
protocol: 1,
|
||||
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
||||
date: "2026-10-24",
|
||||
date: "2026-11-01",
|
||||
} as const;
|
||||
|
||||
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
|
||||
|
||||
@@ -94,8 +94,8 @@ export function LatencyPage() {
|
||||
<div style={{position:'relative',minHeight:0}}><VideoSurface camera={camera} emptyText="等待真实摄像头" mirrored={false}
|
||||
crosshair={null} grid={null} view={IDENTITY_VIEW} onView={()=>{}} hitFeedback={feedback} showZoom={false} onFramePainted={painted}/></div>
|
||||
</div>
|
||||
<p>{connected?'已连接':'连接中'} · {status}</p>
|
||||
<p style={{fontSize:22}}>样本 {summary.samples} · P50 {summary.p50.toFixed(1)} ms · P95 {summary.p95.toFixed(1)} ms</p>
|
||||
<p>{connected?'已连接':'连接中'} / {status}</p>
|
||||
<p style={{fontSize:22}}>样本 {summary.samples} / P50 {summary.p50.toFixed(1)} ms / P95 {summary.p95.toFixed(1)} ms</p>
|
||||
<p>每 50 ms 更新标记,记录首次可解码回显,包含相机取样等待、曝光、采集、传输和绘制;混合曝光帧不计入。相邻 rAF 夹定绘制时间,刷新间隔约 {summary.refresh.toFixed(1)} ms;面板像素响应需高速相机复核。</p>
|
||||
</main>;
|
||||
}
|
||||
@@ -92,7 +92,7 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
setDevice(snapshot);
|
||||
setViewStep("bundle");
|
||||
appendLog(
|
||||
`设备:${snapshot.chip} ${snapshot.mac ?? "MAC 未知"} · ${snapshot.flashSizeText} · ` +
|
||||
`设备:${snapshot.chip} ${snapshot.mac ?? "MAC 未知"} / ${snapshot.flashSizeText} / ` +
|
||||
`${snapshot.app ? `App ${snapshot.app.version}` : "未识别 App"}`,
|
||||
);
|
||||
} catch (err) {
|
||||
@@ -357,7 +357,7 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
<header className="mnt-head">
|
||||
<div><span className="label mnt-kicker">RMIC / DEVICE SERVICE</span><h1>固件维护</h1></div>
|
||||
<div className="mnt-head__actions">
|
||||
{preview && <span className="tag tag--warn">预览 · 合成数据 / 无 USB 操作</span>}
|
||||
{preview && <span className="tag tag--warn">预览 / 合成数据 / 无 USB 操作</span>}
|
||||
<Button icon={fullscreen ? "fullscreenExit" : "fullscreen"} variant="ghost" onClick={onToggleFullscreen}>{fullscreen ? "退出全屏" : "全屏"}</Button>
|
||||
<Button icon="back" variant="ghost" disabled={anyBusy} onClick={onClose}>返回 <kbd>ESC</kbd></Button>
|
||||
</div>
|
||||
@@ -365,12 +365,12 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
|
||||
<div className="mnt-workspace">
|
||||
<section className="mnt-visual" aria-label="设备与任务状态">
|
||||
<div className="mnt-visual__head"><span className="label">USB / {firmwareKind === "armor" ? "ARMOR" : firmwareKind === "camera" ? "VIDEO" : "DEVICE"}</span><span className={`mnt-link${device ? " is-live" : ""}`}><i />{device ? "已读取" : portAvailable ? "端口可用 · 待读取" : "未发现目标串口"}</span></div>
|
||||
<div className="mnt-visual__head"><span className="label">USB / {firmwareKind === "armor" ? "ARMOR" : firmwareKind === "camera" ? "VIDEO" : "DEVICE"}</span><span className={`mnt-link${device ? " is-live" : ""}`}><i />{device ? "已读取" : portAvailable ? "端口可用 / 待读取" : "未发现目标串口"}</span></div>
|
||||
<DeviceDiagram kind={firmwareKind} identified={!!device} portAvailable={portAvailable} active={anyBusy} failed={!!error || !!report && !report.ok} complete={!!report?.ok} ratio={ratio} chip={device?.chip ?? (firmwareKind === "armor" ? "ESP32-C3" : firmwareKind === "camera" ? "ESP32-S3" : "MCU")} />
|
||||
<div key={visualState} className="mnt-visual__status" role="status">
|
||||
<span className="label">{report ? "RESULT" : busy ? "CURRENT PHASE" : "DEVICE STATUS"}</span>
|
||||
<h2>{busy ? BUSY_TEXT[busy] : report ? report.ok ? "写入与回读完成" : "烧录未完成" : device ? "设备已识别" : "等待读取设备"}{busy && ratio !== null && <span className="num"> {Math.round(ratio * 100)}%</span>}</h2>
|
||||
<p>{anyBusy ? progress?.message ?? (busy === "build" ? "构建日志可在诊断中查看" : "请保持 USB 连接") : report ? "上次操作结果 · 仍需检查板上运行情况" : device ? `${device.chip.toUpperCase()} · ${device.flashSizeText}` : portAvailable ? `${port} · 点击读取设备` : "连接 USB 后刷新串口"}</p>
|
||||
<p>{anyBusy ? progress?.message ?? (busy === "build" ? "构建日志可在诊断中查看" : "请保持 USB 连接") : report ? "上次操作结果 / 仍需检查板上运行情况" : device ? `${device.chip.toUpperCase()} / ${device.flashSizeText}` : portAvailable ? `${port} / 点击读取设备` : "连接 USB 后刷新串口"}</p>
|
||||
</div>
|
||||
<dl className="mnt-identity"><div><dt>串口</dt><dd>{port || "—"}</dd></div><div><dt>MAC</dt><dd>{device?.mac ?? report?.mac ?? "—"}</dd></div><div><dt>队伍设置</dt><dd>{firmwareKind === "armor" ? bundle?.armorTeam != null ? `旧版 / ${expectedTeam === "" ? "待核对" : expectedTeam === "0" ? "红" : "蓝"}` : "客户端选择" : "—"}</dd></div></dl>
|
||||
</section>
|
||||
@@ -389,7 +389,7 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
</div>
|
||||
<div className={`mnt-connection-fields${firmwareKind === "armor" && bundle?.armorTeam != null ? " has-team" : ""}`}>
|
||||
{firmwareKind === "armor" && bundle?.armorTeam != null && <label className="mnt-field"><span>旧版固件目标队伍</span><select className="select" value={expectedTeam} disabled={anyBusy} onChange={event => { setExpectedTeam(event.target.value); setPlan(null); }}><option value="">选择这块板的队伍</option><option value="0">队伍一(红,0)</option><option value="1">队伍二(蓝,1)</option></select></label>}
|
||||
<label className="mnt-field"><span>USB 串口</span><div className="mnt-row"><select className="select" value={port} disabled={anyBusy} onChange={event => { setPort(event.target.value); setDevice(null); setPlan(null); setReport(null); setProgress(null); }}>{ports.length === 0 && <option value="">未发现串口</option>}{ports.map(entry => <option key={entry.portName} value={entry.portName}>{entry.portName} · {entry.label}</option>)}</select><Button icon="refresh" disabled={anyBusy} onClick={() => void refreshPorts(false)}>刷新</Button></div></label>
|
||||
<label className="mnt-field"><span>USB 串口</span><div className="mnt-row"><select className="select" value={port} disabled={anyBusy} onChange={event => { setPort(event.target.value); setDevice(null); setPlan(null); setReport(null); setProgress(null); }}>{ports.length === 0 && <option value="">未发现串口</option>}{ports.map(entry => <option key={entry.portName} value={entry.portName}>{entry.portName} / {entry.label}</option>)}</select><Button icon="refresh" disabled={anyBusy} onClick={() => void refreshPorts(false)}>刷新</Button></div></label>
|
||||
</div>
|
||||
<p className="mnt-hint">请只连接要维护的主板。{firmwareKind === "camera" && "图传板接入右侧 USB 口。"}读取设备信息时,主板会复位。</p>
|
||||
<div className="mnt-task__actions"><Button icon="usb" variant="primary" disabled={anyBusy || !port || !firmwareKind} onClick={() => void probePort(port)}>读取设备并继续</Button><Button icon="firmware" variant="ghost" disabled={anyBusy || !firmwareKind} onClick={() => setViewStep("bundle")}>准备固件包</Button></div>
|
||||
@@ -398,7 +398,7 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
|
||||
{viewStep === "bundle" && <>
|
||||
<div className="mnt-task__title"><span className="label">02 / FIRMWARE</span><h2>选择对应固件</h2></div>
|
||||
<div className="mnt-package"><span className="mnt-package__symbol"><Icon name="firmware" /></span><strong>{bundle ? `${bundle.name} ${bundle.version}` : "选择固件 ZIP"}</strong><span>{bundle ? `${bundle.chip.toUpperCase()} · ${formatBytes(bundle.appSize)}` : firmwareKind === "armor" ? "ESP32-C3 / 装甲板固件" : "ESP32-S3 / 图传固件"}</span>{bundle?.firmwareKind === "armor" && <b>{bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} · 阈值 {bundle.armorThreshold}</b>}<Button icon="file" disabled={anyBusy} onClick={() => void chooseBundle("zip")}>{bundle ? "更换 ZIP" : "选择 ZIP"}</Button></div>
|
||||
<div className="mnt-package"><span className="mnt-package__symbol"><Icon name="firmware" /></span><strong>{bundle ? `${bundle.name} ${bundle.version}` : "选择固件 ZIP"}</strong><span>{bundle ? `${bundle.chip.toUpperCase()} / ${formatBytes(bundle.appSize)}` : firmwareKind === "armor" ? "ESP32-C3 / 装甲板固件" : "ESP32-S3 / 图传固件"}</span>{bundle?.firmwareKind === "armor" && <b>{bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} / 阈值 {bundle.armorThreshold}</b>}<Button icon="file" disabled={anyBusy} onClick={() => void chooseBundle("zip")}>{bundle ? "更换 ZIP" : "选择 ZIP"}</Button></div>
|
||||
{bundle?.firmwareKind === "armor" && bundle.armorTeam != null && <label className="mnt-field"><span>旧版包:核对实物队伍</span><select className="select" value={expectedTeam} disabled={anyBusy} onChange={event => { setExpectedTeam(event.target.value); setPlan(null); }}><option value="">请选择</option><option value="0">队伍一(红)</option><option value="1">队伍二(蓝)</option></select></label>}
|
||||
<div className="mnt-row mnt-secondary">{firmwareKind === "armor" && <Button icon="build" variant="ghost" disabled={anyBusy} onClick={() => setModal("build")}>从源码编译</Button>}<Button icon="folder" variant="ghost" disabled={anyBusy} onClick={() => void chooseBundle("dir")}>选择目录包</Button></div>
|
||||
{mismatch && <p className="mnt-note warn" role="alert">{mismatch}</p>}
|
||||
@@ -412,7 +412,7 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
<div className="mnt-confirmation"><strong className="num">{plan.device.port} / {plan.device.chip.toUpperCase()}</strong><span className="num">MAC {plan.device.mac}</span><span>{plan.bundle.name} {plan.bundle.version}</span></div>
|
||||
<div className="mnt-running"><span className="label">CURRENT PHASE</span><h3>{progress?.phase ?? "准备设备"}</h3><p>{progress?.message ?? "正在核对设备与准备备份"}</p><span className="mnt-hint">左侧显示当前进度,操作结束后会显示结果。</span></div>
|
||||
</> : plan ? <>
|
||||
<div className="mnt-confirmation"><strong className="num">{plan.device.port} / {plan.device.chip.toUpperCase()}</strong><span className="num">MAC {plan.device.mac ?? "未知"}</span><span>{plan.bundle.name} {plan.bundle.version}</span>{plan.mode === "armor-install" && <b>{plan.bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${plan.bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} · 阈值 {plan.bundle.armorThreshold}</b>}</div>
|
||||
<div className="mnt-confirmation"><strong className="num">{plan.device.port} / {plan.device.chip.toUpperCase()}</strong><span className="num">MAC {plan.device.mac ?? "未知"}</span><span>{plan.bundle.name} {plan.bundle.version}</span>{plan.mode === "armor-install" && <b>{plan.bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${plan.bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} / 阈值 {plan.bundle.armorThreshold}</b>}</div>
|
||||
<ul className="mnt-warnings">
|
||||
{plan.mode !== "armor-install" && <>
|
||||
<li>App 写入 {formatOffset(plan.targetOffset)}({formatBytes(plan.appSize)}),整段回读通过后才切换分区表。旧 App 保留在 {formatOffset(plan.currentFactoryOffset)}。</li>
|
||||
@@ -439,11 +439,11 @@ export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { o
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer className="mnt-foot"><span>{busy ? `正在${BUSY_TEXT[busy]} · 请勿拔线` : "USB 固件维护 / ESP32-S3 · ESP32-C3"}</span><div>{(busy === "flash" || busy === "build") && <Button icon="stop" variant="danger" onClick={() => void cancelFlash()}>请求取消</Button>}<Button icon="log" variant="ghost" onClick={() => setModal("details")}>诊断 / 日志 {logs.length > 0 ? `(${logs.length})` : ""}</Button></div></footer>
|
||||
<footer className="mnt-foot"><span>{busy ? `正在${BUSY_TEXT[busy]} / 请勿拔线` : "USB 固件维护 / ESP32-S3 / ESP32-C3"}</span><div>{(busy === "flash" || busy === "build") && <Button icon="stop" variant="danger" onClick={() => void cancelFlash()}>请求取消</Button>}<Button icon="log" variant="ghost" onClick={() => setModal("details")}>诊断 / 日志 {logs.length > 0 ? `(${logs.length})` : ""}</Button></div></footer>
|
||||
|
||||
{modal === "restore" && restoreRequest && <Dialog title={restoreRequest.kind === "armor" ? "恢复完整备份" : "恢复旧分区表"} className="mnt-restore-dialog" onClose={() => { setModal(null); setRestoreRequest(null); }} closeDisabled={anyBusy}>
|
||||
{close => <div className="mnt-restore">
|
||||
<div className="mnt-confirmation"><strong>{restoreRequest.port} · {restoreRequest.kind === "armor" ? "ESP32-C3 装甲板" : "ESP32-S3 图传板"}</strong><span className="num">{restoreRequest.backupDir}</span></div>
|
||||
<div className="mnt-confirmation"><strong>{restoreRequest.port} / {restoreRequest.kind === "armor" ? "ESP32-C3 装甲板" : "ESP32-S3 图传板"}</strong><span className="num">{restoreRequest.backupDir}</span></div>
|
||||
<p>{restoreRequest.kind === "armor" ? "将恢复完整 4 MB Flash,覆盖当前固件和设置。恢复期间不支持取消。" : "将把旧分区表写回 0x8000,设备会复位到旧 App。"}执行前会核对备份与设备身份,请保持供电和 USB 连接。</p>
|
||||
<div className="mnt-task__actions"><Button icon="back" variant="ghost" onClick={close}>返回检查</Button><Button icon="reset" variant="danger" disabled={anyBusy} onClick={() => void restoreTable()}>确认恢复</Button></div>
|
||||
</div>}
|
||||
|
||||
@@ -89,9 +89,12 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
// 命中流水:最近三次,放在控制台头部。裁判在争执时需要的是"刚才谁掉了多少"。
|
||||
const [ledger, setLedger] = useState<HitPulseRecord[]>([]);
|
||||
useEffect(() => {
|
||||
if (!lastHit) return;
|
||||
if (!lastHit) { setLedger([]); return; }
|
||||
setLedger((current) => [lastHit, ...current].slice(0, 3));
|
||||
}, [lastHit]);
|
||||
useEffect(() => {
|
||||
if (snapshot.matchClock.phase === "idle") setLedger([]);
|
||||
}, [snapshot.matchClock.phase]);
|
||||
|
||||
const panes = useMemo(
|
||||
() =>
|
||||
@@ -237,7 +240,7 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
<div className={`ref__feed${dimmed ? " is-dimmed" : ""}`}>
|
||||
<VideoSurface
|
||||
camera={pane.camera}
|
||||
label={`${pane.key.toUpperCase()} · ${label}`}
|
||||
label={`${pane.key.toUpperCase()} / ${label}`}
|
||||
emptyText={
|
||||
pane.stats?.hasFrames
|
||||
? ""
|
||||
@@ -245,7 +248,8 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
? "已连接,等待画面…"
|
||||
: `等待${label}的图传`
|
||||
}
|
||||
mirrored={snapshot.mirrored}
|
||||
mirrored={snapshot.cameraMirrors[String(pane.camera)]?.mirror ?? snapshot.mirrored}
|
||||
mirroredVertical={snapshot.cameraMirrors[String(pane.camera)]?.mirrorVertical ?? snapshot.mirroredVertical}
|
||||
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
||||
crosshair={null}
|
||||
grid={hud.grid}
|
||||
@@ -287,6 +291,13 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
name={pane.health?.name ?? label}
|
||||
onSave={(value) => saveName(pane.team, value)}
|
||||
/>
|
||||
{pane.camera !== null && <div className="ref__mirror-controls" onPointerDown={event => event.stopPropagation()}>
|
||||
{[false, true].map(vertical => {
|
||||
const value = snapshot.cameraMirrors[String(pane.camera)] ?? { mirror: snapshot.mirrored, mirrorVertical: snapshot.mirroredVertical };
|
||||
const checked = vertical ? value.mirrorVertical : value.mirror;
|
||||
return <button className="btn btn--sm" key={String(vertical)} aria-pressed={checked} title="同步到绑定此图传板的选手端" onClick={() => void api.setCameraMirror(pane.camera!, vertical ? value.mirror : !checked, vertical ? !checked : value.mirrorVertical).catch(onError)}><Icon name={vertical ? "mirrorVertical" : "mirrorHorizontal"} />{vertical ? "上下镜像" : "左右镜像"}<span className="ref__mirror-state">{checked ? "开" : "关"}</span></button>;
|
||||
})}
|
||||
</div>}
|
||||
<StatsLine stats={pane.stats} diagnostics={snapshot.diagnostics} />
|
||||
{pane.cameraInfo && (
|
||||
<span
|
||||
@@ -442,7 +453,7 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
left={
|
||||
<span className="statusbar__state">
|
||||
<span className={`dot ${snapshot.clients > 0 ? "dot--live" : "dot--warn"}`} />
|
||||
同时查看两路画面 · 滚轮缩放鼠标所在的画面
|
||||
同时查看两路画面 / 滚轮缩放鼠标所在的画面
|
||||
</span>
|
||||
}
|
||||
center={
|
||||
@@ -475,7 +486,7 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
}
|
||||
right={
|
||||
<span className="statusbar__hint">
|
||||
{scope === "all" ? "按 1 / 2 查看单路" : `正在看 ${scope === "a" ? "左路" : "右路"} · 按 0 显示全部`}
|
||||
{scope === "all" ? "按 1 / 2 查看单路" : `正在看 ${scope === "a" ? "左路" : "右路"} / 按 0 显示全部`}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -9,17 +9,21 @@ import { firmwareLabel, teamName, idText } from "../lib/format";
|
||||
import { useAppStore } from "../lib/store";
|
||||
import { BUILD } from "../lib/version";
|
||||
import type { HudView, Snapshot } from "../lib/types";
|
||||
import { useOperatorControl } from "../lib/use-operator-control";
|
||||
import { OperatorControls } from "../components/OperatorControls";
|
||||
|
||||
interface Props {
|
||||
snapshot: Snapshot;
|
||||
hud: HudView;
|
||||
calibrating: boolean;
|
||||
controlsBlocked: boolean;
|
||||
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 { lastHit, connected } = useAppStore();
|
||||
const control = useOperatorControl({ snapshot, connected, blocked: controlsBlocked || calibrating });
|
||||
const camera = snapshot.config.cameraId;
|
||||
const stats = snapshot.stats.find(entry => entry.camera === camera);
|
||||
const boundCamera = snapshot.cameras.find(entry => entry.id === camera);
|
||||
@@ -37,18 +41,18 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
||||
// 两侧各自使用独立列;放大血条也不能跨过中线压住对方。
|
||||
const healthConfig = { ...hud.health, width: Math.min(1, hud.health.width * 2) };
|
||||
const hasVideo = cameraLive && !!stats?.hasFrames;
|
||||
const emptyText = camera === null ? "未绑定图传板 · 按 ESC 配置"
|
||||
const emptyText = camera === null ? "未绑定图传板 / 按 ESC 配置"
|
||||
: !connected ? "本机服务断开,正在重连"
|
||||
: !boundCamera ? "尚未发现绑定的图传板 · 按 ESC 检查设备"
|
||||
: !boundCamera.compatible ? "图传协议不匹配 · 按 ESC 检查固件"
|
||||
: !boundCamera ? "尚未发现绑定的图传板 / 按 ESC 检查设备"
|
||||
: !boundCamera.compatible ? "图传协议不匹配 / 按 ESC 检查固件"
|
||||
: !cameraLive ? "图传板离线,等待重新连接"
|
||||
: !stats?.hasFrames ? "已连接,等待画面" : "";
|
||||
|
||||
return <div className="op cockpit">
|
||||
<div className="op__stage">
|
||||
<div className="op__stage" ref={control.target}>
|
||||
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
|
||||
mirrored={snapshot.mirrored} 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}>
|
||||
mirrored={snapshot.mirrored} mirroredVertical={snapshot.mirroredVertical} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
|
||||
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__health">
|
||||
{hud.health.visible && mine && <div className="cockpit__health-side"><HealthBar health={mine} config={healthConfig} align="left" tag={healthTag(mine, snapshot.team)} /></div>}
|
||||
@@ -56,7 +60,7 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
||||
{hud.health.visible && theirs && <div className="cockpit__health-side cockpit__health-side--right"><HealthBar health={theirs} config={healthConfig} align="right" tag={healthTag(theirs, snapshot.team)} /></div>}
|
||||
</div>
|
||||
<div className="cockpit__header">
|
||||
<div className="cockpit__identity"><span className="label">RMIC / OPERATOR</span><span title={myName}>{myName}</span>{snapshot.demo && <b>演示 · 合成数据</b>}</div>
|
||||
<div className="cockpit__identity"><span className="label">RMIC / OPERATOR</span><span title={myName}>{myName}</span>{snapshot.demo && <b>演示 / 合成数据</b>}</div>
|
||||
<div className="cockpit__links" aria-label="连接状态">
|
||||
<span className={cameraLive ? "is-live" : "is-offline"}><i />图传 <b>{cameraState}</b></span>
|
||||
<span className={armorLive ? "is-live" : "is-offline"}><i />装甲板 <b>{armorState}</b></span>
|
||||
@@ -64,15 +68,15 @@ export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
|
||||
</div>
|
||||
<div className="cockpit__frame" aria-hidden="true"><i /><i /><i /><i /></div>
|
||||
<div className="cockpit__telemetry">
|
||||
<div className="cockpit__feed"><span className="label">VIDEO SOURCE</span><strong className="num">{camera === null ? "NO BINDING" : boundCamera?.idText ?? idText(camera)}</strong><span>{cameraLive && stats?.hasFrames ? `${stats.width} × ${stats.height}${snapshot.mirrored ? " / 镜像" : ""}` : "等待图传连接"}</span></div>
|
||||
<div className="cockpit__feed"><span className="label">VIDEO SOURCE</span><strong className="num">{camera === null ? "NO BINDING" : boundCamera?.idText ?? idText(camera)}</strong><span>{cameraLive && stats?.hasFrames ? `${stats.width} × ${stats.height}${snapshot.mirrored ? " / 左右镜像" : ""}${snapshot.mirroredVertical ? " / 上下镜像" : ""}` : "等待图传连接"}</span></div>
|
||||
<div className="cockpit__fps"><span className="label">RECEIVE / FPS</span><strong className="num">{cameraLive && stats?.hasFrames ? stats.fps.toFixed(1) : "—"}</strong>{hud.showStats && snapshot.diagnostics && <span>丢包 {cameraLive && stats?.hasFrames ? `${stats.lossPercent.toFixed(1)}%` : "—"}</span>}</div>
|
||||
</div>
|
||||
<div className="cockpit__footer"><span><kbd>ESC</kbd> 菜单 / 设置</span><span className="num">{calibrating ? "瞄准校准中" : hud.showZoom ? `OPTICAL ×${view.zoom.toFixed(1)}` : ""}</span><span>{snapshot.config.armorId === null ? "ARMOR / —" : `ARMOR / ${board?.idText ?? idText(snapshot.config.armorId)}`}</span></div>
|
||||
<div className="cockpit__footer"><div className="cockpit__actions"><OperatorControls control={control} snapshot={snapshot} connected={connected} blocked={controlsBlocked || calibrating} /><span><kbd>ESC</kbd> 菜单 / 设置</span></div><span className="num">{calibrating ? "瞄准校准中" : hud.showZoom ? `OPTICAL ×${view.zoom.toFixed(1)}` : ""}</span><span>{snapshot.config.armorId === null ? "ARMOR / —" : `ARMOR / ${board?.idText ?? idText(snapshot.config.armorId)}`}</span></div>
|
||||
</div>
|
||||
<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} />
|
||||
<TeamMatchCountdown snapshot={snapshot} />
|
||||
{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>
|
||||
</div>
|
||||
</div>;
|
||||
|
||||
@@ -106,3 +106,43 @@
|
||||
/* 异常与校准提示避开顶部血条及底部读数。 */
|
||||
.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); }
|
||||
|
||||
/* 操控入口只占左下角一行,参数在二级菜单中展开。 */
|
||||
.operator-controls { position: relative; z-index: 16; color: var(--ink); pointer-events: auto; flex: none; }
|
||||
.cockpit__actions { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; min-width: 0; }
|
||||
.cockpit__actions > span { white-space: nowrap; }
|
||||
.operator-controls__toggle { gap: 10px; min-width: 116px; background: var(--panel); }
|
||||
.operator-controls__toggle > i { width: 6px; height: 6px; background: var(--ink-3); }
|
||||
.operator-controls__toggle > i.is-on { background: var(--hud); }
|
||||
.operator-controls__toggle > span { margin-left: auto; color: var(--ink-3); font: 10px var(--font-mono); }
|
||||
.operator-controls__menu { position: absolute; bottom: calc(100% + 8px); left: 0; width: min(300px, calc(100vw - 56px)); padding: 16px; display: grid; gap: 16px; border: 1px solid var(--line-3); background: var(--panel); animation: dialog-in var(--dur-short4) var(--m3-emphasized-decelerate) both; }
|
||||
.operator-controls__actions { display: flex; gap: 8px; }
|
||||
.operator-controls__actions > button { flex: 1; }
|
||||
.operator-controls__sensitivity { display: grid; gap: 4px; font-size: 11px; color: var(--ink-2); }
|
||||
.operator-controls__menu small { font-size: 10px; color: var(--ink-3); }
|
||||
.operator-controls__fault { margin-left: 10px; font-size: 10px; color: var(--warn); }
|
||||
.operator-mapping { position: absolute; z-index: 12; pointer-events: none; top: 50%; left: 50%; width: min(460px, calc(100% - 56px)); transform: translate(-50%, -50%); color: var(--hud); padding: 18px 22px; background: rgb(5 16 12 / .28); border: 1px solid #74af8b55; font: 10px/1.5 var(--font-mono); animation: hud-reveal var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
|
||||
.operator-mapping header, .operator-mapping footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.operator-mapping header { letter-spacing: .12em; }
|
||||
.operator-mapping header b { font-weight: 400; color: var(--hud-dim); }
|
||||
.operator-mapping__flow { display: flex; justify-content: center; align-items: center; gap: 20px; padding: 12px 0; color: var(--hud-dim); }
|
||||
.operator-mapping__flow i { font-style: normal; }
|
||||
.operator-mapping__channels { display: grid; gap: 10px; }
|
||||
.operator-mapping__channel { display: grid; grid-template-columns: 80px 1fr 55px; gap: 0 12px; align-items: baseline; }
|
||||
.operator-mapping__channel > strong { text-align: right; font-size: 16px; font-weight: 400; }
|
||||
.operator-mapping__channel > span:first-child { color: var(--hud-dim); }
|
||||
.operator-mapping__track { grid-column: 1 / -1; height: 3px; background: #74af8b22; position: relative; }
|
||||
.operator-mapping__track > i { position: absolute; height: 100%; background: var(--hud); transition: left var(--dur-short1) var(--m3-standard), width var(--dur-short1) var(--m3-standard); }
|
||||
.operator-mapping__track > b { position: absolute; left: 50%; top: -2px; height: 7px; width: 1px; background: #74af8b66; }
|
||||
.operator-mapping footer { border-top: 1px solid #74af8b33; margin-top: 16px; padding-top: 10px; color: var(--hud-dim); }
|
||||
.operator-mapping .is-firing { color: var(--hud); }
|
||||
.ref__mirror-controls { display: flex; align-items: center; gap: 6px; margin-left: auto; flex-wrap: wrap; }
|
||||
.ref__mirror-controls .icon { width: 17px; height: 17px; }
|
||||
.ref__mirror-state { color: var(--ink-3); margin-left: 3px; }
|
||||
.operator-controls__toggle > .icon:last-child { width: 16px; height: 16px; margin-left: auto; transform: rotate(-90deg); transition: transform var(--dur-short3) var(--m3-standard); }
|
||||
.operator-controls__toggle > .icon.is-open { transform: rotate(90deg); }
|
||||
.ref__mirror-controls .btn { background: var(--panel); font-size: 10px; }
|
||||
@media (max-height: 650px) { .operator-mapping { padding: 10px 18px; } }
|
||||
@media (prefers-reduced-motion: reduce) { .operator-controls__menu, .operator-mapping { animation: none; } .operator-mapping__track > i { transition: none; } }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { .operator-controls__toggle > .icon:last-child { transition: none; } }
|
||||
@@ -387,7 +387,7 @@
|
||||
}
|
||||
|
||||
.hp--critical .hp__track {
|
||||
border-color: var(--error-line);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.hp--pulsing .hp__track {
|
||||
@@ -1064,3 +1064,6 @@
|
||||
animation-delay: 0ms;
|
||||
}
|
||||
}
|
||||
|
||||
/* 每路镜像工具占用页脚布局空间,不覆盖图传。窄窗允许整组换行。 */
|
||||
.ref__foot { height: auto; min-height: 44px; flex-wrap: wrap; row-gap: 8px; padding-block: 6px; }
|
||||
+52
-7
@@ -32,24 +32,42 @@ client/
|
||||
|
||||
计时依据 [2026 比赛流程](https://docs.simba-robotics.com/zh-cn/competition/matches/):准备 3 分钟、对局 3 分钟、选手技术暂停 5 分钟。准备结束进入“等待裁判”,不会自动开赛;裁判确认后先执行短倒计时,再开始对局。短倒计时可设 1–60 秒,默认 5 秒,是客户端设置,并非规则页规定的时长。
|
||||
|
||||
裁判端顶部的比赛控制条提供准备、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
||||
裁判端顶部的比赛控制条提供准备、跳过准备倒计时、确认开赛、选手暂停、官方暂停、恢复和结束本局等操作。准备期间点击“跳过准备倒计时”会进入“准备结束 · 等待裁判”;仍需点击“确认开赛”,经过短倒计时后才开始对局。发起选手暂停时,需选择申请方、填写原因并勾选“已获得主裁判批准”;按下开始按钮后才计入暂停时间。
|
||||
|
||||
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时和装甲板扣血,胜负由裁判判定;计时不能控制机器人运动、重置血量或代替判罚。
|
||||
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时、装甲板扣血及本项目键鼠操控输出,胜负由裁判判定;下位机是否实际停机仍需验证,计时不能代替判罚。
|
||||
|
||||
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息、胜负结果和最近命中流水,回到等待准备。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
|
||||
|
||||
远程复位需要更新装甲板固件。请求最多等待 3 秒,未确认或未收到四路满血时保留结束状态,提示具体主板及检查步骤;部分主板成功复位时也不会报告整局重置成功。离线主板或两队误用同一块主板会报错。重置过程中禁止开赛和修改配置;没有分配装甲板时只重置计时。旧固件仍可长按 BOOT 复位血量,但不会确认远程请求,不能完成这项一键重置。
|
||||
|
||||
选手端将阶段与剩余时间放在顶部两条血条中间,悬停可查看对局用时与暂停原因。开赛前最后 5 秒覆盖整个画面,逐秒缩放数字并显示环形动效,最后 2 秒加强颜色提示;收到正式开赛状态后短暂显示“开始”,随后恢复操作画面。系统开启“减少动态效果”时停用动画,仍保留数字倒计时。计时失联或比赛暂停时不显示全屏倒计时。原始规则和状态机在 Rust 核心,前端仅在有效快照期限内插值。两台电脑通过同一局域网 UDP 5601 广播同步,需允许客户端的本地网络收发;与装甲板共用接收端口,不需要图传板或装甲板配合转发。旧客户端没有同步显示能力。
|
||||
|
||||
正式裁判端会向当前比赛装甲板下发独立扣血许可:仅对局进行中允许扣血,准备、等待开赛、倒计时、暂停和结束均禁止。禁止时受击仍闪灯,血量不变。许可丢失 1 秒后停止扣血,恢复比赛不会补血。此功能必须更新装甲板固件;旧固件忽略许可消息。绑定、灯色和扣血许可的规则见[装甲板说明](../hardware/armor.md#规则)。
|
||||
|
||||
对局进行中首次确认任一方血量归零时,Rust 核心会锁定本局结论、结束计时,并唤醒发送任务向双方下发禁止扣血许可;接收线程不等待网络发送或界面消费。结论由裁判端持续广播给选手端,后续扣血、迟到报文、掉线或补血均不重新改判;只有成功重置本局才清除。血量仍显示主板实际读数,不伪造满血。若首次结算快照中双方都已归零则保留平局;结算后另一方才上报归零不会把原结果改成平局。缺少一方有效血量时不凭空宣布其获胜。禁止扣血仍受网络可达性与原有 1 秒租约约束,发布前需复测实际停止时间。裁判端与选手端均需更新客户端;已有支持扣血许可的 C3 固件可继续使用。
|
||||
|
||||
计时失联 1.5 秒后冻结,显示“计时同步中断”;同一裁判会话恢复时自动校正。裁判端重启或网卡地址改变后,按 ESC,在操作菜单中选择“重新接收裁判计时”。该操作会解除原会话锁定并接收下一份广播,因此操作前应确保局域网中只有一个正式裁判端。
|
||||
|
||||
计时不写入个人配置。裁判进程重启后从等待准备开始,需现场人工核对,不会自行恢复或判罚上一局。
|
||||
|
||||
`--demo` 和浏览器预览只在本机合成,不发送、跟随现场计时。浏览器可用 `?preview=referee&match=ready` 检查确认开赛,`match=preparation` / `countdown` / `running` / `paused-player` / `paused-official` / `paused-expired` 检查各状态;去掉 `preview=referee` 可检查选手 HUD,`?match=offline` 检查冻结提示。演示不代表跨电脑广播验证。
|
||||
`--demo` 和浏览器预览只在本机合成,不发送、跟随现场计时或向真实装甲板发送复位。浏览器可用 `?preview=referee&match=ready` 检查确认开赛,`match=preparation` / `countdown` / `running` / `paused-player` / `paused-official` / `paused-expired` 检查各状态;`match=finished` 合成一方归零,供检查一键重置。去掉 `preview=referee` 可检查选手 HUD,`?match=offline` 检查冻结提示。演示中的重置只恢复合成血量,不代表跨电脑广播或硬件复位验证。
|
||||
|
||||
自动验证入口:`pnpm test:match` 检查显示插值与断线冻结;`client/core` 主机测试覆盖规则转换、暂停冻结、过期、乱序和角色限制,集成测试 `match_sync` 使用真实回环 UDP 经生产消息分流到跟随计时器。协议测试检查长度、版本、UTF-8 和字段拒收。发布前仍需在两台电脑上检查广播可达、各网卡与防火墙、暂停同步和裁判重启后的人工重连。
|
||||
自动验证入口:`pnpm test:match` 检查显示插值与断线冻结;`pnpm test:video` 检查镜像坐标、用户端 HUD 和裁判操作入口。`client/core` 主机测试覆盖规则转换、跳过准备、重置、暂停冻结、过期、乱序和角色限制,集成测试 `match_sync` 使用真实回环 UDP 经生产消息分流到跟随计时器,`armor_reset` 验证复位重试、回执与满血确认。协议测试检查长度、版本、UTF-8 和字段拒收,装甲板规则测试覆盖复位去重及许可限制。发布前仍需在两台电脑和真实主板上检查广播可达、各网卡与防火墙、复位和暂停同步,以及裁判重启后的人工重连。
|
||||
|
||||
固件维护页用简化线条绘制 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)。
|
||||
|
||||
操控入口默认只保留左下角开关,比赛/赛前调试与灵敏度滑条在二级菜单中。赛前调试发送时,画面中央以半透明 HUD 显示 CH0–CH3 的输入、速度值和发射位;它显示客户端输入,不是下位机实测速度或串口应答。动画使用现有 M3 缓动令牌并支持减少动态效果。
|
||||
|
||||
画面镜像按图传板 ID 双向同步:选手修改本车后裁判对应一路更新,裁判每路的左右/上下镜像按钮也会回传;旧配置保留原默认方向。两端需更新客户端,固件无需更新,详情见[镜像同步协议](../protocol/udp.md#画面镜像同步类型-12)。
|
||||
|
||||
`pnpm test:input` 检查速度换算、停止与最新输入队列;浏览器预览只模拟本地输入,页面标记“合成输入”,不会发送现场控制。
|
||||
|
||||
### 配色:墨黑蓝打底,只有一支红
|
||||
|
||||
| 角色 | 值 | 用在哪 |
|
||||
@@ -135,6 +153,7 @@ python scripts/generate-brand-assets.py
|
||||
### 每页最顺手的那个操作
|
||||
|
||||
- 用户端通过滚轮缩放、拖动平移、双击复位。顶栏和常驻操作按钮已收进 ESC 菜单,画面边缘持续显示当前图传、接收帧率、图传及绑定装甲板状态。未绑定或离线时显示对应状态,不显示旧帧率;准星与网格在收到画面后显示。顶部身份与链路、双方血条、底部读数各自分区,放大血条不会盖住对方。菜单开合和维护步骤有短过渡,系统开启“减少动态效果”时停用。
|
||||
- 用户端设置的“设备绑定”和裁判端设置的“画面槽位”提供“左右镜像画面”和“上下镜像画面”两个独立开关,可组合使用,自动保存到本机配置;上下镜像默认关闭,旧配置保持原方向。用户端和裁判端的图像、网格、准星偏移、拖动与校准随对应轴翻转,HUD 文字保持正向。镜像只影响本机显示,截图和录制仍使用原始图像。
|
||||
- 按 ESC 打开操作菜单,可继续操作、进入画面与设备设置、打开固件维护、切换全屏或退出。再次按 ESC 返回;设置和退出沿用密码规则。菜单打开时图传接收与受击上报继续运行,并不暂停比赛。
|
||||
- 裁判端点击左侧画面后,下方列表只显示该侧的装甲板;再次点击恢复显示全部,键盘 `1` / `2` / `0` 也可切换。拖动中间的竖线可调整两路画面的宽度,双击恢复等宽。拖动画面与控制台之间的横线可调整回放区域高度。
|
||||
- 设置覆盖整个窗口,左侧切换分类,中间只显示当前分类的控件。用户端包含常规、设备绑定、瞄准器、瞄点校准、辅助网格、装甲条、受击与提示、录制与截图、安全;裁判端提供画面槽位分类。分类可用鼠标或方向键切换,按 ESC 返回。控件分列排布,低高度窗口仅在当前分类内滚动,不再浏览整页设置。
|
||||
@@ -170,10 +189,10 @@ cd client/src-tauri && cargo test # 40,其中几条真的会起 ffmpeg
|
||||
|
||||
```powershell
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci -- --locked --config 'unstable.build-std=[]'
|
||||
pnpm bundle:windows
|
||||
```
|
||||
|
||||
`--target` 覆盖本目录原来的 macOS target,`--bundles nsis` 选择 Windows 安装包;末尾的 Cargo 参数清空从根固件项目继承的 `build-std`。
|
||||
该命令调用 `scripts/build-windows-release.ps1`,显式选择 Windows x64、NSIS 安装包与 stable 工具链,并清空从固件项目继承的 `build-std`。
|
||||
|
||||
- 程序:`src-tauri/target/x86_64-pc-windows-msvc/release/cam-desktop.exe`。当前 Cargo 和 Tauri 构建都使用这个二进制文件名;安装器的显示名和文件名使用 `RMIC-2026`。
|
||||
- 安装包:同一 release 目录下的 `bundle/nsis/*-setup.exe`。
|
||||
@@ -198,6 +217,26 @@ icacls .\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\*-setup.exe
|
||||
|
||||
权限回归检查:打包下载过 NSIS 工具后,在 `client/` 执行 `./scripts/test-windows-bundle.ps1`。它在独立样例目录验证 Low 进程拒绝、文件标签修复及重复执行,并编译一个仅写临时文件后退出的 NSIS 程序;不安装应用。工具不在默认缓存时可传 `-NsisCompiler <makensis.exe 路径>`。
|
||||
|
||||
SmartScreen 的发布者与文件信誉和上述完整性标签是两套机制。未签名的软件、使用自签证书的软件以及信誉尚未建立的新签名包都可能出现提示;有效代码签名也不保证新包立即免提示,见[微软的 SmartScreen 开发者说明](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/smartscreen-reputation)。
|
||||
|
||||
Windows 发布通过 Tauri 原生签名配置,对主程序及 NSIS 安装包使用 SHA-256 和 RFC 3161 时间戳。发布脚本要求 PowerShell 7.4+,首次运行默认在 `CurrentUser/My` 创建项目专用的 RSA 3072 自签名代码证书,有效期 3 年,私钥不可导出。公开指纹保存在 `%LOCALAPPDATA%/RMIC-2026/signing/windows.json`;后续构建复用同一证书,不会每版重新创建。配置丢失时可找回同名的唯一证书;证书过期、私钥丢失或存在多个候选时停止,需明确选择或补建身份。私钥仍需依靠原构建账户和机器保留;换机不能只复制公钥继续签名。
|
||||
|
||||
自签名交付文件名带 `self-signed`,附带 `RMIC-2026-codesign.cer` 公钥证书及 `windows-signature-verification.json`。校验器分别验证 CMS 签名、Windows SIP 文件摘要、固定证书指纹,以及 RFC 3161 时间戳的签名、绑定和时间戳机构证书链。自签名链仅在本次校验对象中按指纹验证,不会把证书导入系统 Root 或 TrustedPublisher。报告中的 `integrityVerified=true` 与 `windowsTrusted=false` 可以同时成立;系统可能显示 `UnknownError`,原因仍是根证书未受信任。完整文件 SHA-256 另见同目录校验文件。
|
||||
|
||||
如改用 CA 证书,将证书及可访问的私钥配置到构建用户的 `CurrentUser/My`,再指定 `RMIC_WINDOWS_CERT_THUMBPRINT`。个人证书身份不会写入共享 Tauri 配置。只有显式传入 `-AllowUnsigned` 且没有指定证书指纹时,才生成带 `unsigned` 的未签名包;它不读取本地默认身份。`-SigningConfigPath` 或 `RMIC_WINDOWS_SIGNING_CONFIG` 可指定本机配置位置。这些方式不改变系统防护设置,也不代表已建立 SmartScreen 信誉。
|
||||
|
||||
```powershell
|
||||
# 在 client/ 执行。默认创建或复用本机自签名身份。
|
||||
pnpm bundle:windows
|
||||
# 只读预检(首次创建前会提示没有身份)。
|
||||
pwsh -NoProfile -File scripts/build-windows-release.ps1 -PreflightOnly
|
||||
# 仅用于明确接受未签名限制的开发测试。
|
||||
.\scripts\build-windows-release.ps1 -AllowUnsigned
|
||||
.\scripts\test-windows-signing.ps1
|
||||
```
|
||||
|
||||
交付文件与签名报告输出到根目录 `target/releases/v<版本>+<构建号>/`。CI 发布同样默认复用 runner 账户的自签名身份;需要持久保存该账户的证书库和本机配置,临时 runner 无法自动继承前一次身份。`WINDOWS_CODE_SIGNING_THUMBPRINT` 仓库变量可覆盖默认选择。PR 构建只生成未签名预览包。签名 runner 应仅接受可信源码;私钥或证书密码不写入仓库、构建参数或报告。
|
||||
|
||||
NSIS 安装流程使用简体中文,包括欢迎、安装位置、安装完成、覆盖安装、卸载与 WebView2 错误提示。`src-tauri/installer/hooks.nsh` 定义页面提示和安装日志,`SimpChinese.nsh` 定义 Tauri 安装器的补充翻译;`tauri.windows.conf.json` 引用这些脚本和主题图片。沿用 Tauri 默认安装模板和当前用户安装方式;首次启动的模式选择与裁判系统绑定仍在客户端内完成。
|
||||
|
||||
现场裁判系统采用固定热点约定:SSID 为 `SR-602-2G4`,密码为 `12345678`。热点需提供 2.4 GHz Wi-Fi;运行客户端的电脑也应接入同一网络,并允许设备间互访。固定这组参数是为了便于现场连接和调试,安装完成页会直接显示它们。
|
||||
@@ -340,6 +379,8 @@ Rust 侧的配置修改命令会调用 `AppState::require_unlocked`。即使从
|
||||
|
||||
血量归零后,血条保留数字 0 和空条,比赛结果由中央横幅显示。
|
||||
|
||||
低血量时保留队伍原色:红方保持红色、蓝方保持蓝色,队名、数字、填充和低血边框使用同一队伍色。低血提示通过边框与可配置的脉动体现;开启减少动态效果时停止动画,保留边框。
|
||||
|
||||
图传离线或本机视频通道断开时,保留的最后一帧会灰度化并叠加灰色遮罩,同时显示等待或重连原因;图传恢复后自动移除。遮罩仅作用于视频层,HUD 的队伍色、血量和状态仍保持可读;装甲板单独离线不会使正常图传变灰。
|
||||
|
||||
### 胜负横幅
|
||||
@@ -347,7 +388,7 @@ Rust 侧的配置修改命令会调用 `AppState::require_unlocked`。即使从
|
||||
一方血量归零后,图传中央显示结果:获胜方为“胜利”,落败方为“落败”,双方同时归零为“平局”。提示带上对手名字,便于在裁判端两路画面中判断胜负。
|
||||
|
||||
- 结果由 Rust 侧计算(`snapshot::resolve_outcomes`,有单测)。自己归零即可判负,即使对手掉线;判胜则要求对手归零且自己仍有血,避免在本队从未上报时误判获胜。
|
||||
- 横幅持续显示到血量重置(长按 BOOT / 下一局开始),供截图、回放和现场核对。
|
||||
- 正式比赛的终局横幅由裁判端锁定并同步,持续显示到裁判端成功“重置到未开始”。单独长按 BOOT 补血不会清除本局结论,单纯开始准备也不会补血。
|
||||
- 比赛结果放在画面中央;比赛中的命中反馈避开中央瞄准区域。
|
||||
|
||||
### 瞄准器
|
||||
@@ -443,6 +484,7 @@ teamNames = ["队伍一", "队伍二"]
|
||||
cameraId = "0x0DE00001"
|
||||
armorId = "0x0A200001"
|
||||
mirror = false
|
||||
mirrorVertical = false
|
||||
password = "$argon2id$v=19$m=19456,t=2,p=1$..."
|
||||
|
||||
[recording]
|
||||
@@ -569,3 +611,6 @@ RUST_LOG=debug ./target/aarch64-apple-darwin/debug/cam-desktop | grep 'stream:'
|
||||
| 两路画面与队伍对应不符 | 在设置中核对图传板槽位,必要时手动指定;通用装甲板固件在客户端选择队伍,旧版固定队伍固件才使用编译时的 `ARMOR_TEAM` |
|
||||
| macOS 上 WebKit 报 `could not create directory .../WebKit/...` | 运行环境禁止写 `~/Library/WebKit`(沙箱)。WebView 会退回无缓存的临时目录,功能不受影响 |
|
||||
| `libc` 找不到 `MAP_FAILED` | `client/.cargo/config.toml` 的 target 没改成宿主三元组 |
|
||||
|
||||
|
||||
镜像按钮位于裁判每路画面下方的信息栏,不再覆盖视频。选手端操控开关与 ESC 提示共用底部工具行,由 HUD 网格为其保留空间;图传读数位于上一行,避免按钮遮挡。镜像、操控、比赛和调试入口使用本地图标,界面分隔不再使用中点符号。
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
> 状态:部分实现,其余待确认。准备、开赛倒计时、对局计时、选手/官方暂停和选手端同步已实现,操作方法与边界见[比赛计时与暂停](../client/client.md#比赛计时与暂停)。其余内容保留为 2026-10-19 草案;下文的布局、命令、快捷键和验收数字均不代表当前能力或测试结果。
|
||||
> 比赛判负、系列赛比分、直播页和双路同步回放仍需确认。已实现的 USB 维护与固件包格式见[固件维护](../maintenance/firmware.md)。计时同步实际使用类型 7 `MatchState`;类型 6 已用于 `ArmorControl`,下文原协议草案不作为线路定义。
|
||||
> 当前还已实现跳过准备后等待确认开赛,以及结束后的定向装甲板复位。扣血许可使用类型 8,复位与回执使用类型 9;需更新装甲板固件,主机测试不代表板上验证。下文关于暂停不影响硬件扣血、尚无下行控制及复位未实现的描述保留为原草案背景,以[UDP 协议](../protocol/udp.md)和[客户端说明](../client/client.md)为准。
|
||||
> 原草案中的旧色板、字体方案、单文件 CSS 基线、烧录实现计划和排期已被当前实现取代,不再作为开发依据。
|
||||
> 规则依据:[2026 校内赛参赛手册](https://docs.simba-robotics.com/zh-cn/competition/)、[对抗赛与奖项](https://docs.simba-robotics.com/zh-cn/competition/matches/)、[裁判系统](https://docs.simba-robotics.com/zh-cn/competition/referee-system/)。规则摘录沿用原稿,实施前需核对手册。
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ node scripts/version.mjs --print
|
||||
|
||||
构建号取 `git rev-list --count HEAD`。提交正文中,以 `- ` 开头且符合 `type(scope): 说明` 的行也会归为独立条目,可用于记录 squash 提交中的多项改动。历史发布按标签区间重新计算,不从上一次生成的文件续写。
|
||||
|
||||
发布基线以 `v<major>.<minor>.<patch>` 标签为准。同一未发布区间内即使有多次 `feat`,也只相对基线提升一次 minor;生成版本文件或增加构建号不表示已经建立新发布基线。完成一次正式版本交付后,应在对应源码提交上记录该语义版本标签;标签推送按发布安排执行。下一轮功能变更再从该标签计算,不能用反复更新构建号代替语义版本迭代。
|
||||
|
||||
## 派生文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|
||||
+14
-12
@@ -32,12 +32,12 @@ armor/
|
||||
| 压电片 左 | GPIO3(ADC1_CH3) | |
|
||||
| 压电片 右 | GPIO1(ADC1_CH1) | |
|
||||
| BOOT 键 | GPIO9 | 低有效,内部上拉 |
|
||||
| 调试串口 UART0 TXD | GPIO21 | 115200 8N1,日志从这里出来(主控制台) |
|
||||
| 调试串口 UART0 RXD | GPIO20 | 目前空闲,留给以后的命令通道 |
|
||||
| 用户 UART TXD | GPIO21 | UART1 路由,115200 8N1,输出键鼠操作协议 |
|
||||
| 用户 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)。
|
||||
|
||||
## 规则
|
||||
|
||||
@@ -50,12 +50,14 @@ armor/
|
||||
| 受击阈值 | 原始 12 bit ADC > 2000(`ARMOR_THRESHOLD` 可改) | `Rules::threshold` |
|
||||
| 血量归零 | 四路全黑,直到复位 | `Armor::strip` |
|
||||
| 正常颜色 | 队伍一红(`0xFF0000`)、队伍二蓝(`0x0000FF`) | `Rgb::for_team` |
|
||||
| 复位(新一局) | 长按 BOOT ≥500 ms → 满血、清计数 | `Button` + `Armor::reset` |
|
||||
| 复位(新一局) | 长按 BOOT ≥500 ms,或裁判端定向复位 → 满血、清计数;保留队伍与灯色 | `Button` / `DamageLink::accept_reset` + `Armor::reset` |
|
||||
| 打印状态 | 短按 BOOT → 立刻打一行状态并重发上报 | `ButtonEvent::Click` |
|
||||
|
||||
整车共用一条血量,由主板计算;裁判端负责发送扣血许可和显示血量。四条上报的 `hp` 相同,`index` 分别为 0..3。界面按 `(team, index)` 收齐四条后显示同一个数值。
|
||||
|
||||
装甲板默认禁止扣血。正式裁判端仅在对局进行中允许当前比赛装甲板扣血,其他阶段均禁止。禁止扣血时,受击路仍熄灭 50 ms,冷却与检测继续,血量不变。许可每 200 ms 续约,超过 1 秒未收到新许可、Wi-Fi 断开或客户端保活失效后停止扣血。恢复许可不会补血,开始新一局仍需长按 BOOT 复位。此功能需要更新装甲板固件,旧固件会忽略许可消息。线路和来源规则见[UDP 协议](../protocol/udp.md#装甲板扣血许可)。
|
||||
装甲板默认禁止扣血。正式裁判端仅在对局进行中允许当前比赛装甲板扣血,其他阶段均禁止。禁止扣血时,受击路仍熄灭 50 ms,冷却与检测继续,血量不变。许可每 200 ms 续约,超过 1 秒未收到新许可、Wi-Fi 断开或客户端保活失效后停止扣血。恢复许可不会补血,新一局可长按 BOOT 或使用裁判端“重置到未开始”复位。扣血许可及远程复位都需要对应版本的装甲板固件;旧固件会忽略未知消息。线路和来源规则见[UDP 协议](../protocol/udp.md#装甲板扣血许可)。
|
||||
|
||||
远程复位只接受目标 id 匹配、同一裁判来源与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复 100 血、清受击计数和冷却,保留队伍与灯色;同一个复位 id 的重试只回执,不再次补血。板端定向回复回执并立即广播四路血量,客户端确认后才回到未开始。运行许可、过期许可和旧序号下的复位均拒绝。此规则已有主机测试,板上复位、丢包重试及两台电脑同步仍需实测。
|
||||
|
||||
参考实现使用全局 50 ms 冷却,一路受击会抑制其余路在该窗口内的击打。当前四路分别冷却,由 `cooldown_is_per_plate_not_global` 测试验证。
|
||||
|
||||
@@ -227,9 +229,9 @@ C3 只有 2 个 TX 通道,四路灯带无法各占一个。因此只创建一
|
||||
|
||||
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
|
||||
|
||||
@@ -267,7 +269,7 @@ status: hp=0 hits=37 dead=true plates[front=37 rear=0 left=0 right=0]
|
||||
|
||||
### 9. USB 控制台看不到复位后的头两秒
|
||||
|
||||
UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也能读取日志。但复位时 USB 会重新枚举,**复位后最初约 1–2 秒的日志会丢**,实测曾漏掉启动横幅。需要完整启动日志时,通过 UART0 连接 USB-TTL。
|
||||
原生 USB Serial/JTAG 现在是软件日志主控制台。早期采用 USB 次控制台时,实测复位重新枚举可能丢失最初约 1–2 秒日志;切换后的启动可见范围仍需实测。用户 TXD 现在输出二进制操控帧,不再作为应用日志口。
|
||||
|
||||
## 与早期 C 版设计的差异
|
||||
|
||||
@@ -276,7 +278,7 @@ UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也
|
||||
| | 参考实现 | 这里 | 为什么 |
|
||||
| --- | --- | --- | --- |
|
||||
| 主从链路 | ESP-NOW 配对,两块板对拷 | 无:三块从板只是直接接线的灯与传感器 | 按实际硬件(只有主板一颗 MCU) |
|
||||
| DBUS 透传 | UART0 收发 10 字节 DBUS,USB CDC 打 CSV | 不做 | 这套硬件没有 DBUS 需求;UART0 让给日志 |
|
||||
| 串口操作 | 固定 10 字节盲透传,未定义通道字段 | 项目自定义 20 字节 UART 帧,四轴、使能及发射,CRC 校验 | 明确通道含义与失联行为,不假定兼容 DBUS |
|
||||
| 受击变暗 | 四条灯带一起全黑 50 ms | 只暗被打的那一路 | 各面灯带独立反馈受击 |
|
||||
| 冷却窗口 | 全局 50 ms | 每板独立 50 ms | 一路受击不应抑制其他板位的检测 |
|
||||
| 灯带刷新 | 每 10 ms 无条件刷四遍 | 只在内容变化时刷 + 每秒强制全刷 | 四路独立控制后,省掉四轮 RMT 开销 |
|
||||
@@ -289,8 +291,8 @@ UART0 是主控制台,USB Serial/JTAG 是次控制台,因此原生 USB 也
|
||||
|
||||
- **另外三路(后/左/右)的压电片与灯带还没接**(2026-10-14 实机只有前一路)。
|
||||
代码支持四路,接线后无需修改;四路同时受击与各路独立变暗仍未完成实板验证。
|
||||
- **UART0 RX(GPIO20)上的命令通道**:日志输出已可用;反向的 `status` / `reset` 命令尚未接入,当前通过长按 BOOT 复位。
|
||||
- **用户 UART RX(GPIO20)上的反向命令/应答**:当前只输出操控帧,未解析下位机状态。血量复位使用 BOOT 或裁判 UDP 请求。
|
||||
- **从板加 MCU 的方案**:如果以后从板也装单片机(走 UART 或无线回传),
|
||||
`armor-protocol` 里已经预留了板位枚举与上报格式,加一个 `slave` bin 即可。
|
||||
- **双击 / 多击**:`Button` 只实现短按与长按,参考实现里未使用的 OneButton 功能没有移植。
|
||||
- **下发血量**:当前由板子计算血量,裁判端只显示该数值。若以后改由裁判端决定血量并下发血量/复位,需要新增一条下行消息,由 `client` 发送。
|
||||
- **下发任意血量**:当前仍由板子计算血量。裁判端可通过独立的复位消息恢复满血,但尚不支持指定任意血量或远程判负。
|
||||
+2
-1
@@ -20,6 +20,7 @@
|
||||
- [图传板硬件](hardware/camera.md):引脚、PSRAM、分区、故障 Flash 与驱动补丁。
|
||||
- [装甲板](hardware/armor.md):接线、受击规则、上报、构建与实现要点。
|
||||
- [UDP 协议](protocol/udp.md):线路格式、版本通告、帧重组与拒收条件。
|
||||
- [键鼠操作与用户 UART](protocol/operator-control.md):FPS 输入映射、赛前调试、串口帧、失联回零及接收端示例。
|
||||
|
||||
## 测试与排查记录
|
||||
|
||||
@@ -35,7 +36,7 @@
|
||||
|
||||
- [改动记录](releases/changelog.md):由 Git 历史生成;[JSON](releases/changelog.json)供程序读取。
|
||||
- [早期人工记录](releases/changelog-legacy.md):自动版本机制建立前的记录。
|
||||
- [比赛计时与暂停](client/client.md#比赛计时与暂停):裁判控制、选手同步及验证边界。
|
||||
- [比赛计时与暂停](client/client.md#比赛计时与暂停):裁判控制、跳过准备、一键复位、选手同步及验证边界。
|
||||
- [比赛控制与直播提案](design/match-and-broadcast.md):未实现的判罚、比分、直播与回放需求。
|
||||
|
||||
## 文档维护
|
||||
|
||||
@@ -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/下位机单独重启、血量归零和复位。编译及合成预览不代表已经完成上述硬件验证。
|
||||
@@ -75,6 +75,12 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
|
||||
| 6 `ArmorControl` | 客户端 → 指定装甲板 | 运行时选择队伍并保活(回复广播源端口) |
|
||||
| 7 `MatchState` | 裁判端 → 选手端 | 完整比赛计时快照,广播至 UDP 5601,5 Hz |
|
||||
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
||||
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
||||
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
|
||||
| 12 `CameraMirror` | 选手端 ↔ 裁判端 | 每路图传镜像寄存器,广播 UDP 5601 |
|
||||
| 11 `OperatorControl` | 选手端 → 绑定的装甲板 | 四轴速度和发射状态,定向发送到主板上报端口 |
|
||||
|
||||
类型 11 保持线路版本 1,不改变旧消息布局;旧 C3 会忽略该类型,使用操控功能需更新 C3。载荷、租约及下游 UART 帧见[键鼠操作与用户 UART](operator-control.md)。
|
||||
|
||||
### 比赛计时快照(类型 7)
|
||||
|
||||
@@ -101,6 +107,23 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
|
||||
|
||||
选手端锁定首次收到的来源 IP 与 session;1500 ms 无新快照则冻结,重复包不续约。同一会话恢复后直接校正到最新快照,不补播错过的倒计时。其他来源与重启后的新会话需通过操作菜单“重新接收裁判计时”显式接入。会话锁定防止意外混用,不提供来源认证;现场同一局域网只运行一个正式裁判端。
|
||||
|
||||
### 终局快照(类型 10)
|
||||
|
||||
`MatchResult` 使用协议版本 1、27 字节共用头和 `sender_id=0`,其他头部业务字段置零,不改变类型 7 的布局。负载固定 34 字节,整包 61 字节:
|
||||
|
||||
| 负载偏移 | 字段 | 类型 / 取值 |
|
||||
| --- | --- | --- |
|
||||
| 0 | session | u64 LE,非零,与裁判计时会话相同 |
|
||||
| 8 | sequence | u64 LE,本次完整快照的序号 |
|
||||
| 16 | result_id | u64 LE,首次结算时的序号;重发不变,非零且不大于 sequence |
|
||||
| 24 | remaining_ms | u32 LE,结束时的剩余毫秒,最多 180000 |
|
||||
| 28 | elapsed_ms | u32 LE,结束时的对局用时,最多 180000 |
|
||||
| 32 | outcomes | 两个 u8,分别对应队伍 0/1:0 未判定、1 胜、2 负、3 平局 |
|
||||
|
||||
有效结论组合仅为 `[1,2]`、`[2,1]`、`[2,0]`、`[0,2]` 或 `[3,3]`。缺少一队有效血量时只记录已知败方,不凭空判胜。首次归零会锁定结论并结束计时,裁判端立即唤醒发送任务下发双方禁止扣血许可,之后随每 200 ms 心跳重发终局快照。血量读数继续反映实际主板上报,但不能重算已锁定的胜负。
|
||||
|
||||
终局包自包含结束阶段及计时,可在类型 7 丢失或乱序时独立应用;同序号的计时与终局包以完整终局结论合并,重复包不延长租约。来源 IP、session 和序号沿用计时会话规则,同一 result_id 的结论与结束时间不得变更。成功重置后,新的空闲计时序号会使旧终局包失效;新一局使用递增的 result_id。旧选手客户端忽略类型 10,需与裁判端一起更新。装甲板扣血许可格式不变,已有支持类型 8 的 C3 固件无需为此更新。
|
||||
|
||||
### 四个设计决定
|
||||
|
||||
头长保留为 27 字节,不额外补齐。它只占每个 1427 字节数据报的 1.9%;为对齐而在固件和客户端分别维护手写偏移常量,反而更容易引入不易察觉的错位。
|
||||
@@ -251,3 +274,32 @@ UDP 不保证数据报的顺序和到达。接收端等待下一张完整帧,
|
||||
板端默认禁止扣血。只有 Wi-Fi 可用、客户端颜色保活有效且扣血许可在 1 秒内收到新序号时才允许扣血。同一来源与会话的重复包、旧序号不能续约。租约有效时拒绝其他来源或会话,过期后可接受新的裁判来源。该机制用于现场状态同步,不提供身份认证。
|
||||
|
||||
扣血许可与 `ArmorControl` 分开管理,裁判发送许可不会抢占操作手的灯色控制。禁止扣血时,ADC 检测、每板冷却和受击熄灯 50 ms 继续执行,血量保持不变;恢复许可不会自动补血。旧装甲板固件会忽略 type=8,必须更新固件才能使用此规则。独立字节核对包含在 `python armor/scripts/test-probe.py` 中,探测器不发送扣血许可。
|
||||
|
||||
### 装甲板复位与回执
|
||||
|
||||
`ArmorReset` 使用 `type=9`、协议版本 1 和原有 27 字节头,不改变视频、血量及其他消息载荷。请求的 `sender_id=0`,回执的 `sender_id=board_id`,其余头部业务字段置零。负载严格为 29 字节,完整数据报 56 字节:
|
||||
|
||||
| 载荷偏移 | 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| 0 | u32 LE | 目标 `board_id`,非零 |
|
||||
| 4 | u64 LE | 裁判计时会话,非零 |
|
||||
| 12 | u64 LE | 本次禁止扣血许可的序号,非零 |
|
||||
| 20 | u64 LE | `reset_id`,非零且不大于序号;同次操作重试保持不变 |
|
||||
| 28 | u8 | 0 请求,1 回执,其他值拒收 |
|
||||
|
||||
客户端先进入结束阶段并发送禁止扣血许可,再向固定的本局槽位主板发送同序号复位请求;每 200 ms 随新许可更新请求序号,最多等待 3 秒。板端只接受目标 id 匹配、同一来源 IP/端口与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复满血并清受击计数、冷却;同复位 id 的重试只回复回执并重发血量,不重复复位。旧复位 id、旧许可序号、过期许可及运行许可下的请求均拒绝。
|
||||
|
||||
回执定向发回裁判端,并沿用请求字段;板端同时通过原血量通道广播四路真实血量。客户端逐板核对来源地址、会话、复位 id 和已发送序号,收到回执及其后的四路 100 血上报才完成重置,不根据回执伪造血量。部分成功或超时均保留结束阶段。来源与会话约束防止意外混用,不提供身份认证。旧装甲板忽略 type=9,必须更新固件才能远程复位;图传板无需更新。独立字节核对见 `python armor/scripts/test-probe.py`,探测器不发送复位。
|
||||
|
||||
### 画面镜像同步(类型 12)
|
||||
|
||||
客户端按图传板 ID 保存水平、垂直镜像,双方均可修改;裁判两路独立。沿用线路版本 1、27 字节头,头部业务字段均为零。固定 21 字节负载依次为 camera_id:u32、revision:u64、origin:u64、flags:u8,均小端;flags bit0 水平、bit1 垂直,其余位必须为零。三个整数必须非零,整包严格 48 字节。
|
||||
|
||||
revision 为逻辑时钟,本地修改取已知最大修订号加一,origin 为进程实例标识。接收仅应用 `(revision, origin)` 更大的值,重复、乱序和回声不会反复覆盖;并发同修订号按 origin 排序收敛,不依赖两台电脑墙钟。只接收已绑定图传板或裁判当前槽位的设置,每 200 ms 重发这些相机已有的修订记录以补偿 UDP 丢包和晚加入。镜像同时使用独立的 IPv4 组播 `239.255.56.2:5602`(TTL=1、开启本机回环),支持同机多实例各自订阅;原 UDP 5601 广播作为跨版本兼容路径保留。装甲板及计时的 5601 端口不改为共享绑定,避免 Windows 单播回执被随机分发到某个实例。接收回调只更新最多两路的内存收件箱,配置写盘在后台执行。
|
||||
|
||||
配置中 `cameraMirrors` 保存每路记录,旧配置缺失时回落到原有镜像默认值。尚未改动过的默认值不广播,避免新加入的客户端覆盖已配置记录。全局设置对当前槽位批量应用,裁判画面下方按钮只修改所在一路。演示预览不收发真实同步消息。需要双方更新客户端,固件无需更新;广播仍受网卡、防火墙和局域网可达性影响,该消息不提供身份认证。
|
||||
|
||||
|
||||
同机验证入口:先从 `client/` 运行 `pnpm build` 并编译桌面端,再运行 `node client/scripts/test-mirror-instances.mjs <客户端可执行文件>`(仓库根目录)。未给路径时使用已编译的 debug 客户端,需先启动 `pnpm dev`。脚本启动两个真正的原生客户端进程,通过各自独立 WebView2 调试端口调用生产 IPC、读取生产快照;使用独立临时配置和合成图传 ID,保持角色选择未完成,禁止测试实例广播正式比赛状态,也不启动操作输入。完成后只关闭它启动的实例。
|
||||
|
||||
脚本覆盖两路独立、双向设置、12 轮并发写入、任一实例退出期间另一端修改、重启后的追赶、改绑到另一图传板及双方再次重启后的持久化一致性。这里的断连为关闭实例后重新加入,不代表已测试真实网卡拔插、跨网段或无线 AP 的组播转发。完整的同机测试结果写入 `target/mirror-instances-*/report.json`。
|
||||
@@ -1,195 +1,12 @@
|
||||
{
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.1",
|
||||
"major": 0,
|
||||
"minor": 3,
|
||||
"patch": 0,
|
||||
"build": 42,
|
||||
"minor": 6,
|
||||
"patch": 1,
|
||||
"build": 48,
|
||||
"protocol": 1,
|
||||
"date": "2026-10-24",
|
||||
"baseline": "v0.2.1",
|
||||
"commits": 7,
|
||||
"groups": {
|
||||
"feat": [
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "改进启动窗口、维护交互与操作图标",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "增加无边框动画启动窗口,加载完成后恢复主窗口",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "ui",
|
||||
"text": "为操作按钮引入本地 Material Symbols Rounded 图标",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "match",
|
||||
"text": "同步比赛计时与装甲板扣血许可",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "增加裁判比赛计时、技术暂停与选手端局域网同步",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "armor",
|
||||
"text": "红蓝共用通用固件,按客户端选队并显示网络连接状态",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "armor",
|
||||
"text": "仅在对局进行中允许扣血,其他阶段保留受击闪烁",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "将计时置于血条中间并增加开赛前五秒全屏动画",
|
||||
"breaking": false
|
||||
}
|
||||
],
|
||||
"fix": [
|
||||
{
|
||||
"scope": "maintenance",
|
||||
"text": "移除烧录前无效的原生确认框,保留页面检查与后端校验",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "maintenance",
|
||||
"text": "统一板卡示意风格并修正装甲板比例和图传右侧 USB 接线",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "修复连续血条、对手镜像和图传断连灰度遮罩",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "统一界面中文字体并整理各页面文案",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "maintenance",
|
||||
"text": "备份迁移装甲板分区,恢复 SDK 构建与固件打包",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "installer",
|
||||
"text": "保留现场固定热点约定并说明连接要求",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "installer",
|
||||
"text": "使用共享热点默认值,并修正本地覆盖配置的包含路径",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "packaging",
|
||||
"text": "修复 Windows 安装与固件打包并完善客户端文案",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "installer",
|
||||
"text": "修复低完整性产物无法写入临时目录的问题,并在 CI 打包前后检查完整性标签",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "firmware",
|
||||
"text": "从本次 Cargo ELF 打包并同步配套镜像,修正短目录说明与 LLVM 搜索顺序",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "installer",
|
||||
"text": "修复中文完成页和页眉遮挡,侧栏使用等比缩放的原始 Logo",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "config",
|
||||
"text": "安装提示改用可选本地热点配置,排除 Wi-Fi 凭据",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "统一状态与操作文案,录制和截图成功后再显示完成提示",
|
||||
"breaking": false
|
||||
}
|
||||
],
|
||||
"refactor": [
|
||||
{
|
||||
"scope": "repo",
|
||||
"text": "按 armor、vt 和 client 整理工程与脚本,移除旧参考实现",
|
||||
"breaking": false
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"scope": null,
|
||||
"text": "按 humanizer-zh 润色项目文档并将写作约定纳入 AGENTS.md",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": null,
|
||||
"text": "同步构建、协议、比赛控制和硬件验证边界",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "network",
|
||||
"text": "明确设备按固件中的固定热点参数连接,客户端电脑需接入同一网络,更换热点后需重新编译烧录",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "agents",
|
||||
"text": "区分现场统一热点约定与个人 Wi-Fi 配置,保留前者及对应安装说明",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": null,
|
||||
"text": "润色项目说明并统一裁判系统术语",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": null,
|
||||
"text": "整理项目文档并统一界面表述",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": null,
|
||||
"text": "README 不写死构建号,改由 version.json 提供",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": null,
|
||||
"text": "按 humanizer 重写项目文档并同步 RMIC::2026 现状",
|
||||
"breaking": false
|
||||
}
|
||||
],
|
||||
"test": [
|
||||
{
|
||||
"scope": null,
|
||||
"text": "补充线路、受击许可、回环 UDP、维护和 HUD 验证",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "packaging",
|
||||
"text": "补充 Windows 完整性和固件打包回归,覆盖外部输出目录、旧镜像与重复生成",
|
||||
"breaking": false
|
||||
},
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "按文件名核对媒体类型,避免依赖时间戳排序",
|
||||
"breaking": false
|
||||
}
|
||||
],
|
||||
"style": [
|
||||
{
|
||||
"scope": "client",
|
||||
"text": "应用图标增加圆角,统一“裁判系统客户端”命名",
|
||||
"breaking": false
|
||||
}
|
||||
]
|
||||
}
|
||||
"date": "2026-11-01",
|
||||
"baseline": "v0.6.1",
|
||||
"commits": 0,
|
||||
"groups": {}
|
||||
}
|
||||
@@ -4,9 +4,68 @@
|
||||
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
|
||||
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
|
||||
|
||||
## v0.6.1 — 2026-11-01
|
||||
|
||||
1 个提交
|
||||
|
||||
### 修复
|
||||
|
||||
- **client** · 修复双实例镜像同步并调整底部工具布局
|
||||
|
||||
## v0.6.0 — 2026-11-01
|
||||
|
||||
1 个提交
|
||||
|
||||
### 新增
|
||||
|
||||
- **client** · 同步每路镜像并精简操控入口与 HUD 映射
|
||||
|
||||
## v0.5.0 — 2026-10-31
|
||||
|
||||
1 个提交
|
||||
|
||||
### 新增
|
||||
|
||||
- **control** · 添加选手 FPS 键鼠操作与 C3 用户 UART 输出
|
||||
|
||||
## v0.4.1 — 2026-10-31
|
||||
|
||||
1 个提交
|
||||
|
||||
### 修复
|
||||
|
||||
- **build** · 默认复用自签名证书签署 Windows 发布包
|
||||
- **signing** · 独立校验文件摘要、CMS 签名与 RFC 3161 时间戳,不修改系统信任库
|
||||
|
||||
### 构建
|
||||
|
||||
- **windows** · 发布脚本和 CI 复用本机签名身份,交付公钥证书与真实信任状态
|
||||
|
||||
## v0.4.0 — 2026-10-31
|
||||
|
||||
2 个提交
|
||||
|
||||
### 新增
|
||||
|
||||
- **client** · 锁定终局结果并接入 Windows 签名构建
|
||||
- **match** · 添加画面上下镜像、跳过准备和装甲板整局复位
|
||||
|
||||
### 修复
|
||||
|
||||
- **match** · 首次归零结束对局并撤销双方扣血许可,裁判结果同步后不再改判
|
||||
- **hud** · 蓝方低血量始终保留队伍颜色
|
||||
|
||||
### 构建
|
||||
|
||||
- **windows** · 校验代码签名身份和时间戳,明确标注未签名测试包
|
||||
|
||||
### 文档
|
||||
|
||||
- **version** · 说明发布标签基线与语义版本迭代
|
||||
|
||||
## v0.3.0 — 2026-10-24
|
||||
|
||||
构建号 **42** · 线路协议 **1** · 7 个提交(v0.2.1 → v0.3.0)
|
||||
7 个提交
|
||||
|
||||
### 新增
|
||||
|
||||
|
||||
+6
-6
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.1",
|
||||
"major": 0,
|
||||
"minor": 3,
|
||||
"patch": 0,
|
||||
"build": 42,
|
||||
"minor": 6,
|
||||
"patch": 1,
|
||||
"build": 48,
|
||||
"protocol": 1,
|
||||
"date": "2026-10-24",
|
||||
"baseline": "v0.2.1",
|
||||
"date": "2026-11-01",
|
||||
"baseline": "v0.6.1",
|
||||
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN, PROTOCOL_VERSION};
|
||||
|
||||
/// 定向复位及回执。sequence 对齐本次禁止扣血许可;reset_id 在重试间保持不变。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ArmorReset {
|
||||
pub board_id: u32,
|
||||
pub session: u64,
|
||||
pub sequence: u64,
|
||||
pub reset_id: u64,
|
||||
pub acknowledged: bool,
|
||||
}
|
||||
|
||||
impl ArmorReset {
|
||||
pub fn encode(&self) -> Option<Vec<u8>> {
|
||||
if self.board_id == 0
|
||||
|| self.session == 0
|
||||
|| self.reset_id == 0
|
||||
|| self.sequence < self.reset_id
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(HEADER_LEN + 29);
|
||||
encode_header_into(
|
||||
&Header {
|
||||
msg_type: MsgType::ArmorReset,
|
||||
version: PROTOCOL_VERSION,
|
||||
sender_id: if self.acknowledged { self.board_id } else { 0 },
|
||||
..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.extend(self.reset_id.to_le_bytes());
|
||||
out.push(u8::from(self.acknowledged));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
let h = decode_header(bytes)?;
|
||||
if h.msg_type != MsgType::ArmorReset || bytes.len() != HEADER_LEN + 29 {
|
||||
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()?),
|
||||
reset_id: u64::from_le_bytes(p[20..28].try_into().ok()?),
|
||||
acknowledged: match p[28] {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return None,
|
||||
},
|
||||
};
|
||||
(value.board_id != 0
|
||||
&& value.session != 0
|
||||
&& value.reset_id != 0
|
||||
&& value.sequence >= value.reset_id
|
||||
&& h.sender_id
|
||||
== if value.acknowledged {
|
||||
value.board_id
|
||||
} else {
|
||||
0
|
||||
})
|
||||
.then_some(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reset_matches_the_independent_probe_golden_bytes() {
|
||||
let bytes = ArmorReset {
|
||||
board_id: 0x12345678,
|
||||
session: 0x0102030405060708,
|
||||
sequence: 3,
|
||||
reset_id: 2,
|
||||
acknowledged: false,
|
||||
}
|
||||
.encode()
|
||||
.unwrap();
|
||||
let hex = bytes
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>();
|
||||
assert_eq!(
|
||||
hex,
|
||||
concat!(
|
||||
"3143564d090100",
|
||||
"0000000000000000000000000000000000000000",
|
||||
"78563412",
|
||||
"0807060504030201",
|
||||
"0300000000000000",
|
||||
"0200000000000000",
|
||||
"00"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_roundtrip_is_exact_and_rejects_invalid_identity_and_bounds() {
|
||||
for acknowledged in [false, true] {
|
||||
let packet = ArmorReset {
|
||||
board_id: 17,
|
||||
session: 88,
|
||||
sequence: 123,
|
||||
reset_id: 120,
|
||||
acknowledged,
|
||||
};
|
||||
let bytes = packet.encode().unwrap();
|
||||
assert_eq!(bytes.len(), 56);
|
||||
assert_eq!(ArmorReset::decode(&bytes), Some(packet));
|
||||
assert!(crate::ArmorDamageControl::decode(&bytes).is_none());
|
||||
assert!(crate::ArmorHealth::decode_from(&bytes).is_none());
|
||||
for n in 0..bytes.len() {
|
||||
assert!(ArmorReset::decode(&bytes[..n]).is_none());
|
||||
}
|
||||
for (at, byte) in [(4, 8), (5, 99), (7, 42), (55, 2)] {
|
||||
let mut bad = bytes.clone();
|
||||
bad[at] = byte;
|
||||
assert!(ArmorReset::decode(&bad).is_none());
|
||||
}
|
||||
for range in [27..31, 31..39, 39..47, 47..55] {
|
||||
let mut bad = bytes.clone();
|
||||
bad[range].fill(0);
|
||||
assert!(ArmorReset::decode(&bad).is_none());
|
||||
}
|
||||
let mut bad = bytes;
|
||||
bad.push(0);
|
||||
assert!(ArmorReset::decode(&bad).is_none());
|
||||
assert!(ArmorReset {
|
||||
reset_id: 124,
|
||||
..packet
|
||||
}
|
||||
.encode()
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN};
|
||||
|
||||
/// 每路画面的镜像寄存器。revision 是逻辑时钟,origin 用于并发写入的确定排序。
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CameraMirror {
|
||||
pub camera_id: u32,
|
||||
pub revision: u64,
|
||||
pub origin: u64,
|
||||
pub mirror: bool,
|
||||
pub mirror_vertical: bool,
|
||||
}
|
||||
impl CameraMirror {
|
||||
pub fn encode(self) -> Option<Vec<u8>> {
|
||||
if self.camera_id == 0 || self.revision == 0 || self.origin == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
encode_header_into(
|
||||
&Header {
|
||||
msg_type: MsgType::CameraMirror,
|
||||
..Default::default()
|
||||
},
|
||||
&mut bytes,
|
||||
);
|
||||
bytes.extend(self.camera_id.to_le_bytes());
|
||||
bytes.extend(self.revision.to_le_bytes());
|
||||
bytes.extend(self.origin.to_le_bytes());
|
||||
bytes.push(u8::from(self.mirror) | (u8::from(self.mirror_vertical) << 1));
|
||||
Some(bytes)
|
||||
}
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
let h = decode_header(bytes)?;
|
||||
if h.msg_type != MsgType::CameraMirror
|
||||
|| bytes.len() != HEADER_LEN + 21
|
||||
|| bytes[7..HEADER_LEN].iter().any(|v| *v != 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let p = &bytes[HEADER_LEN..];
|
||||
if p[20] > 3 {
|
||||
return None;
|
||||
}
|
||||
let value = Self {
|
||||
camera_id: u32::from_le_bytes(p[..4].try_into().ok()?),
|
||||
revision: u64::from_le_bytes(p[4..12].try_into().ok()?),
|
||||
origin: u64::from_le_bytes(p[12..20].try_into().ok()?),
|
||||
mirror: p[20] & 1 != 0,
|
||||
mirror_vertical: p[20] & 2 != 0,
|
||||
};
|
||||
value.encode()?;
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn exact_validated_mirror_roundtrip() {
|
||||
let p = CameraMirror {
|
||||
camera_id: 7,
|
||||
revision: 4,
|
||||
origin: 2,
|
||||
mirror: true,
|
||||
mirror_vertical: false,
|
||||
};
|
||||
let bytes = p.encode().unwrap();
|
||||
assert_eq!(CameraMirror::decode(&bytes), Some(p));
|
||||
for n in 0..bytes.len() {
|
||||
assert!(CameraMirror::decode(&bytes[..n]).is_none());
|
||||
}
|
||||
for at in [5, 7, HEADER_LEN + 20] {
|
||||
let mut bad = bytes.clone();
|
||||
bad[at] = 255;
|
||||
assert!(CameraMirror::decode(&bad).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,11 +47,19 @@
|
||||
//! ```
|
||||
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
mod camera_mirror;
|
||||
pub use camera_mirror::CameraMirror;
|
||||
|
||||
mod match_state;
|
||||
pub use match_state::MatchState;
|
||||
mod match_result;
|
||||
pub use match_result::MatchResult;
|
||||
mod armor_damage;
|
||||
pub use armor_damage::ArmorDamageControl;
|
||||
mod armor_reset;
|
||||
pub use armor_reset::ArmorReset;
|
||||
mod operator_control;
|
||||
pub use operator_control::OperatorControl;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 端口
|
||||
@@ -124,6 +132,13 @@ pub enum MsgType {
|
||||
MatchState = 7,
|
||||
/// 裁判端下发本局的扣血许可,定向发送到装甲板上报端口。
|
||||
ArmorDamageControl = 8,
|
||||
/// 裁判定向复位装甲板及板端回执。
|
||||
ArmorReset = 9,
|
||||
/// 裁判广播的锁定胜负及结束计时,自包含快照(5601)。
|
||||
MatchResult = 10,
|
||||
/// 选手端定向发送给已绑定装甲板的四轴速度与发射状态。
|
||||
OperatorControl = 11,
|
||||
CameraMirror = 12,
|
||||
}
|
||||
|
||||
impl MsgType {
|
||||
@@ -138,6 +153,10 @@ impl MsgType {
|
||||
6 => MsgType::ArmorControl,
|
||||
7 => MsgType::MatchState,
|
||||
8 => MsgType::ArmorDamageControl,
|
||||
9 => MsgType::ArmorReset,
|
||||
10 => MsgType::MatchResult,
|
||||
11 => MsgType::OperatorControl,
|
||||
12 => MsgType::CameraMirror,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN, PROTOCOL_VERSION};
|
||||
|
||||
/// 自包含的裁判终局快照。独立消息保持原计时和装甲板许可格式兼容。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct MatchResult {
|
||||
pub session: u64,
|
||||
pub sequence: u64,
|
||||
/// 首次结算时的序号;重发时不变,下一局严格递增。
|
||||
pub result_id: u64,
|
||||
pub remaining_ms: u32,
|
||||
pub elapsed_ms: u32,
|
||||
/// 队伍 0/1:0 未判定、1 胜、2 负、3 平局。
|
||||
pub outcomes: [u8; 2],
|
||||
}
|
||||
|
||||
impl MatchResult {
|
||||
pub fn valid(&self) -> bool {
|
||||
self.session != 0
|
||||
&& self.result_id != 0
|
||||
&& self.result_id <= self.sequence
|
||||
&& self.remaining_ms <= 180_000
|
||||
&& self.elapsed_ms <= 180_000
|
||||
&& matches!(self.outcomes, [1, 2] | [2, 1] | [2, 0] | [0, 2] | [3, 3])
|
||||
}
|
||||
pub fn encode(&self) -> Option<Vec<u8>> {
|
||||
if !self.valid() {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(HEADER_LEN + 34);
|
||||
encode_header_into(
|
||||
&Header {
|
||||
msg_type: MsgType::MatchResult,
|
||||
version: PROTOCOL_VERSION,
|
||||
..Default::default()
|
||||
},
|
||||
&mut out,
|
||||
);
|
||||
out.extend(self.session.to_le_bytes());
|
||||
out.extend(self.sequence.to_le_bytes());
|
||||
out.extend(self.result_id.to_le_bytes());
|
||||
out.extend(self.remaining_ms.to_le_bytes());
|
||||
out.extend(self.elapsed_ms.to_le_bytes());
|
||||
out.extend(self.outcomes);
|
||||
Some(out)
|
||||
}
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
let header = decode_header(bytes)?;
|
||||
if header.msg_type != MsgType::MatchResult
|
||||
|| header.sender_id != 0
|
||||
|| bytes.len() != HEADER_LEN + 34
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let p = &bytes[HEADER_LEN..];
|
||||
let result = Self {
|
||||
session: u64::from_le_bytes(p[0..8].try_into().ok()?),
|
||||
sequence: u64::from_le_bytes(p[8..16].try_into().ok()?),
|
||||
result_id: u64::from_le_bytes(p[16..24].try_into().ok()?),
|
||||
remaining_ms: u32::from_le_bytes(p[24..28].try_into().ok()?),
|
||||
elapsed_ms: u32::from_le_bytes(p[28..32].try_into().ok()?),
|
||||
outcomes: p[32..34].try_into().ok()?,
|
||||
};
|
||||
result.valid().then_some(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn exact_result_roundtrip_rejects_bad_identity_length_and_conclusions() {
|
||||
let result = MatchResult {
|
||||
session: 9,
|
||||
sequence: 20,
|
||||
result_id: 18,
|
||||
remaining_ms: 100_000,
|
||||
elapsed_ms: 80_000,
|
||||
outcomes: [2, 1],
|
||||
};
|
||||
let bytes = result.encode().unwrap();
|
||||
assert_eq!(bytes.len(), 61);
|
||||
let hex = bytes
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>();
|
||||
assert_eq!(
|
||||
hex,
|
||||
concat!(
|
||||
"3143564d0a0100",
|
||||
"0000000000000000000000000000000000000000",
|
||||
"0900000000000000",
|
||||
"1400000000000000",
|
||||
"1200000000000000",
|
||||
"a0860100",
|
||||
"80380100",
|
||||
"0201"
|
||||
)
|
||||
);
|
||||
assert_eq!(MatchResult::decode(&bytes), Some(result));
|
||||
assert!(crate::MatchState::decode(&bytes).is_none());
|
||||
assert!(crate::ArmorHealth::decode_from(&bytes).is_none());
|
||||
for n in 0..bytes.len() {
|
||||
assert!(MatchResult::decode(&bytes[..n]).is_none());
|
||||
}
|
||||
let mut extra = bytes.clone();
|
||||
extra.push(0);
|
||||
assert!(MatchResult::decode(&extra).is_none());
|
||||
for (offset, value) in [(4, 7), (5, 99), (7, 1), (HEADER_LEN + 33, 4)] {
|
||||
let mut bad = bytes.clone();
|
||||
bad[offset] = value;
|
||||
assert!(MatchResult::decode(&bad).is_none());
|
||||
}
|
||||
for outcomes in [[1, 1], [0, 1], [2, 2], [3, 0], [0, 0]] {
|
||||
assert!(MatchResult { outcomes, ..result }.encode().is_none());
|
||||
}
|
||||
assert!(MatchResult {
|
||||
result_id: 21,
|
||||
..result
|
||||
}
|
||||
.encode()
|
||||
.is_none());
|
||||
assert!(MatchResult {
|
||||
elapsed_ms: 180_001,
|
||||
..result
|
||||
}
|
||||
.encode()
|
||||
.is_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());
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,10 @@ MSG_ARMOR_HEALTH = 5
|
||||
MSG_ARMOR_CONTROL = 6
|
||||
MSG_MATCH_STATE = 7
|
||||
MSG_ARMOR_DAMAGE_CONTROL = 8
|
||||
MSG_ARMOR_RESET = 9
|
||||
MSG_MATCH_RESULT = 10
|
||||
MSG_OPERATOR_CONTROL = 11
|
||||
MSG_CAMERA_MIRROR = 12
|
||||
|
||||
TYPE_NAMES = {
|
||||
MSG_VIDEO: "video",
|
||||
@@ -47,6 +51,10 @@ TYPE_NAMES = {
|
||||
MSG_ARMOR_CONTROL: "armor-control",
|
||||
MSG_MATCH_STATE: "match-state",
|
||||
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
||||
MSG_ARMOR_RESET: "armor-reset",
|
||||
MSG_MATCH_RESULT: "match-result",
|
||||
MSG_OPERATOR_CONTROL: "operator-control",
|
||||
MSG_CAMERA_MIRROR: "camera-mirror",
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user