feat(match): 同步比赛计时与装甲板扣血许可
构建客户端 / 检查(类型 + 单元测试) (push) Canceled after 0s
构建客户端 / Linux x64(deb + AppImage) (push) Canceled after 0s
构建客户端 / Windows x64(NSIS 安装包) (push) Canceled after 0s
构建客户端 / macOS 通用(.app + .dmg) (push) Canceled after 0s

- feat(client): 增加裁判比赛计时、技术暂停与选手端局域网同步
- feat(armor): 红蓝共用通用固件,按客户端选队并显示网络连接状态
- feat(armor): 仅在对局进行中允许扣血,其他阶段保留受击闪烁
- feat(client): 将计时置于血条中间并增加开赛前五秒全屏动画
- fix(client): 修复连续血条、对手镜像和图传断连灰度遮罩
- fix(client): 统一界面中文字体并整理各页面文案
- fix(maintenance): 备份迁移装甲板分区,恢复 SDK 构建与固件打包
- refactor(repo): 按 armor、vt 和 client 整理工程与脚本,移除旧参考实现
- test: 补充线路、受击许可、回环 UDP、维护和 HUD 验证
- docs: 同步构建、协议、比赛控制和硬件验证边界

验证:前端构建与 19 项相关测试通过;核心 91 项单元测试与 2 项回环 UDP 集成测试通过;装甲板规则 25 项、线路 26 项、Tauri 51 项测试通过;独立探测器 5 项与目录回归 4 项通过。完成 C3 两组阈值实际编译、导出与 ZIP 校验,检查 900×600 / 1280×720 页面、倒计时和随包中文字体。
未执行烧录、板上运行、跨电脑广播或硬件稳定性验证。
This commit is contained in:
sloray committed 2026-10-22 17:08:49 +08:00
1 parent 72901939c6
commit f7ca246b68
581 files changed
+6596 -7683

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# 编译通用装甲板固件(ESP32-C3),凭据来自 .env,队伍由客户端下发。
#
# 已有 ESP-IDF 通过进程环境的 IDF_PATH 指定,否则下载固定的 v6.0.1。
set -euo pipefail
cd "$(dirname "$0")/.."
if [ -f .env ]; then
set -a
# shellcheck disable=SC1091
. ./.env
set +a
fi
: "${WIFI_SSID:?set WIFI_SSID in .env (or export it) before building}"
export WIFI_PASS="${WIFI_PASS:-}"
export CARGO_WORKSPACE_DIR="$PWD"
export ESP_IDF_GLOB_BASE="$PWD/armor-firmware"
export ESP_IDF_GLOB_PARTITIONS="partitions.csv"
export ESP_IDF_SDKCONFIG_DEFAULTS="$PWD/armor-firmware/sdkconfig.defaults"
# 受击阈值(原始 12 bit ADC)。看 status 行里的 peak[...] 来定:底噪要明显低于它,
# 正常敲击要明显高于它。不写就是参考实现的 2000。
export ARMOR_THRESHOLD="${ARMOR_THRESHOLD:-2000}"
case "$ARMOR_THRESHOLD" in
'' | *[!0-9]*)
echo "ARMOR_THRESHOLD must be a non-negative integer, got '$ARMOR_THRESHOLD'" >&2
exit 1
;;
esac
echo "==> building armor firmware for esp32c3 (universal, threshold $ARMOR_THRESHOLD)"
cargo build --release --locked --bin armor "$@"
echo
echo "elf: ${CARGO_TARGET_DIR:-$PWD/target}/riscv32imc-esp-espidf/release/armor"
echo "next: armor/scripts/flash.sh"
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# 编译 + 烧录装甲板固件,然后抓一段串口日志(UART0 = RXD GPIO20 / TXD GPIO21)。
#
# armor/scripts/flash.sh # 自动找串口,烧完看 20 秒日志
# ESP_PORT=/dev/cu.usbmodem1101 armor/scripts/flash.sh
# armor/scripts/flash.sh --monitor 60 # 看 60 秒
# armor/scripts/flash.sh --no-monitor # 只烧不抓
#
# 板子上的调试口就是 UART0,所以烧完之后日志会直接从这里出来,不需要另开串口工具。
set -euo pipefail
cd "$(dirname "$0")/.."
MONITOR_SECS=20
while [ $# -gt 0 ]; do
case "$1" in
--monitor)
MONITOR_SECS="${2:-20}"
shift 2
;;
--no-monitor)
MONITOR_SECS=0
shift
;;
*) break ;;
esac
done
port="${ESP_PORT:-}"
if [ -z "$port" ]; then
port=$(ls /dev/cu.usbmodem* /dev/cu.wchusbserial* /dev/cu.SLAB* /dev/cu.usbserial* 2>/dev/null | head -1 || true)
fi
if [ -z "$port" ]; then
echo "no serial port found; set ESP_PORT=/dev/cu.xxx" >&2
exit 1
fi
echo "==> build"
./scripts/build.sh "$@"
elf="${CARGO_TARGET_DIR:-target}/riscv32imc-esp-espidf/release/armor"
if [ ! -f "$elf" ]; then
echo "expected $elf; run armor/scripts/build.sh first" >&2
exit 1
fi
echo "==> flash $port"
# espflash 直接吃 ELF:分区表与 bootloader 都从 ELF 里读,不用手工拼地址。
espflash flash --chip esp32c3 --port "$port" --non-interactive "$elf"
if [ "$MONITOR_SECS" -gt 0 ]; then
echo "==> serial log (${MONITOR_SECS}s, 115200 8N1)"
python3 - "$port" "$MONITOR_SECS" <<'PY'
import os, sys, termios, time
fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NOCTTY)
a = termios.tcgetattr(fd)
a[0] = a[1] = a[3] = 0
a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
a[4] = a[5] = termios.B115200
a[6][termios.VMIN] = 0
a[6][termios.VTIME] = 1
termios.tcsetattr(fd, termios.TCSANOW, a)
end = time.time() + float(sys.argv[2])
while time.time() < end:
try:
data = os.read(fd, 4096)
except OSError:
break
if data:
sys.stdout.write(data.decode("utf-8", "replace"))
sys.stdout.flush()
PY
fi
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
"""独立验证装甲板血量上报的诊断脚本。
不依赖 Rust,也不依赖 protocol / armor-protocol crate——常量是手写的。正因如此它
是线路格式的**独立**检查:如果 Rust 侧的编码写错了,这个脚本仍按文档解析,会立刻
报出不一致。
用法:
python3 armor/scripts/probe.py [秒数]
它监听 UDP 5601(装甲板主板的广播目标),把收到 `ArmorHealth` 数据报按
`(team, index)` 汇总,打印血量变化与心跳间隔。板子每 200 ms 广播四条,所以
正常情况下每秒每个 `(team, index)` 大约 5 条。
用它可以确认三件事,都不需要打开裁判端界面:
1. 板子在广播、IP 与 MAC 派生 id 是多少
2. 四条 index 的血量是否一致(协议约定:整车一条血,四格同值)
3. 比赛进行中,血量有没有随受击下降(每击 −3,100 起)
默认仅旁听。扣血需要裁判端持续发送有效许可;本脚本不发送扣血许可。
常量与 protocol/src/lib.rs 保持一致。改了协议记得改这里——这正是它作为交叉检查
的价值所在。
"""
import socket
import argparse
import sys
import time
from collections import defaultdict
# ---- 与 protocol/src/lib.rs 一致 ----
HEADER = 27 # magic4 + type1 + ver2 + sender4 + frame4 + idx2 + cnt2 + len4 + w2 + h2
MAGIC = 0x4D564331 # "MVC1"
ARMOR_PORT = 5601 # ARMOR_PORT
MSG_ARMOR_HEALTH = 5 # MsgType::ArmorHealth
MSG_ARMOR_CONTROL = 6
MSG_MATCH_STATE = 7 # 比赛计时广播;装甲板探测器忽略
MSG_ARMOR_DAMAGE_CONTROL = 8 # 扣血许可;装甲板探测器忽略
PROTOCOL_VERSION = 1
TEAM_NAMES = {0: "队伍一", 1: "队伍二", 255: "待分配队伍"}
def encode_control(board_id, team):
"""独立编码 ArmorControl:27 字节头 + board_id(u32 LE) + team(u8)。"""
if not 0 < board_id <= 0xffffffff or team not in (0, 1):
raise ValueError("board id must be nonzero u32 and team must be 0 or 1")
header = MAGIC.to_bytes(4, "little") + bytes([MSG_ARMOR_CONTROL])
header += PROTOCOL_VERSION.to_bytes(2, "little") + bytes(20)
return header + board_id.to_bytes(4, "little") + bytes([team])
def decode_damage_control(data):
"""独立核对 type=8 的线路字节,仅解析,不向设备发送许可。"""
if len(data) != HEADER + 21 or int.from_bytes(data[:4], "little") != MAGIC:
return None
if data[4] != MSG_ARMOR_DAMAGE_CONTROL or int.from_bytes(data[5:7], "little") != PROTOCOL_VERSION:
return None
if int.from_bytes(data[7:11], "little") != 0 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")
return (board, session, sequence, bool(data[47])) if board and session and sequence else None
def decode(data):
"""解析一个数据报,返回 (team, index, hp, sender_id, version) 或 None。"""
if len(data) < HEADER + 4:
return None
if int.from_bytes(data[0:4], "little") != MAGIC:
return None
if data[4] != MSG_ARMOR_HEALTH:
return None
version = int.from_bytes(data[5:7], "little")
sender_id = int.from_bytes(data[7:11], "little")
team = data[HEADER]
index = data[HEADER + 1]
hp = int.from_bytes(data[HEADER + 2 : HEADER + 4], "little")
return team, index, hp, sender_id, version
def main():
parser = argparse.ArgumentParser(description="装甲板探测;默认仅旁听,显式指定 --board 和 --team 才下发队伍")
parser.add_argument("seconds", type=float, nargs="?", default=10.0)
parser.add_argument("--board", type=lambda s: int(s, 0), help="目标板 id,例如 0x12345678")
parser.add_argument("--team", type=int, choices=(0, 1))
args = parser.parse_args()
if (args.board is None) != (args.team is None):
parser.error("--board 和 --team 必须同时提供")
control = encode_control(args.board, args.team) if args.board is not None else None
seconds = args.seconds
last_control = 0.0
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", ARMOR_PORT))
sock.settimeout(0.5)
print(f"listening on UDP {ARMOR_PORT} for {seconds:g}s ...")
# (team, index) -> 最后一次 (hp, 收到时刻)
latest = {}
# (team, index) -> 收到过的 hp 序列(去重后按时间)
history = defaultdict(list)
# (team, index) -> 包数
counts = defaultdict(int)
senders = set()
versions = set()
deadline = time.time() + seconds
while time.time() < deadline:
try:
data, addr = sock.recvfrom(2048)
except socket.timeout:
continue
parsed = decode(data)
if parsed is None:
continue
team, index, hp, sender_id, version = parsed
now = time.time()
if control and sender_id == args.board and version == PROTOCOL_VERSION and now - last_control >= 0.5:
sock.sendto(control, addr)
last_control = now
key = (team, index)
counts[key] += 1
senders.add((sender_id, f"{addr[0]}:{addr[1]}"))
versions.add(version)
previous = latest.get(key)
if previous is None or previous[0] != hp:
history[key].append((round(now, 3), hp))
print(
f" {TEAM_NAMES.get(team, f'team{team}')} plate {index}: "
f"hp {hp}"
+ (f" (was {previous[0]})" if previous else " (first seen)")
)
latest[key] = (hp, now)
print()
if not counts:
print("没有收到装甲板上报。检查:")
print(" - 板子上电了吗(UART0 上应有 'reporting to 255.255.255.255:5601')")
print(" - 板子和这台机器在同一个局域网、同一个子网吗")
print(" - 防火墙放行 UDP 5601 了吗")
return 1
print(f"发送方 ({len(senders)}):")
for sender_id, addr in sorted(senders):
print(f" 0x{sender_id:08X} {addr}")
print(f"协议版本: {sorted(versions)}")
print()
by_team = defaultdict(dict)
for (team, index), count in sorted(counts.items()):
by_team[team][index] = count
elapsed = max(seconds, 0.001)
print("每个 (队伍, index) 的包数 / 心率:")
for team, plates in sorted(by_team.items()):
cells = []
for index in range(4):
n = plates.get(index, 0)
cells.append(f"index{index}={n} ({n / elapsed:.1f}/s)")
print(f" {TEAM_NAMES.get(team, f'team{team}')}: " + " ".join(cells))
# 协议约定:整车一条血 → 四格同值;四条都在新鲜期内才等于"这条队伍在线"。
print()
print("四条 index 的血量:")
for team, plates in sorted(by_team.items()):
hps = []
for index in range(4):
reading = latest.get((team, index))
hps.append(str(reading[0]) if reading else "-")
same = len(set(hps)) == 1 and "-" not in hps
print(
f" {TEAM_NAMES.get(team, f'team{team}')}: [{', '.join(hps)}]"
+ (" <- 一致(整车一条血量)" if same else " <- 不一致:检查 index 或丢包")
)
if history:
print()
print("血量变化:")
for key in sorted(history):
team, index = key
events = history[key]
if len(events) == 1:
continue
line = " ".join(f"t={t:+.1f}s hp={hp}" for t, hp in events[:12])
if len(events) > 12:
line += f" ... (+{len(events) - 12} more)"
print(f" {TEAM_NAMES.get(team, f'team{team}')} plate {index}: {line}")
return 0
if __name__ == "__main__":
sys.exit(main())
+28
View File
@@ -0,0 +1,28 @@
"""离线检查独立探测器的线路字节,不连接设备。"""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("armor_probe", Path(__file__).with_name("probe.py"))
probe = importlib.util.module_from_spec(spec)
spec.loader.exec_module(probe)
class WireTests(unittest.TestCase):
def test_control_golden(self):
self.assertEqual(probe.encode_control(0x12345678, 1).hex(),
"3143564d060100" + "00" * 20 + "7856341201")
def test_control_rejects_wrong_team(self):
with self.assertRaises(ValueError): probe.encode_control(1, 255)
def test_unassigned_health(self):
data = bytes.fromhex("3143564d05010078563412" + "00" * 16 + "ff036400")
self.assertEqual(probe.decode(data), (255, 3, 100, 0x12345678, 1))
def test_control_is_not_health(self):
self.assertIsNone(probe.decode(probe.encode_control(1, 0)))
def test_damage_control_golden(self):
packet = bytes.fromhex("3143564d080100" + "00" * 20 + "78563412" + "0807060504030201" + "0200000000000000" + "01")
self.assertEqual(probe.decode_damage_control(packet), (0x12345678, 0x0102030405060708, 2, True))
self.assertEqual(probe.decode_damage_control(packet[:-1] + b'\x00')[-1], False)
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))
if __name__ == "__main__": unittest.main()