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

+16
View File
@@ -1,3 +1,19 @@
fn main() {
for key in ["ARMOR_THRESHOLD", "WIFI_SSID", "WIFI_PASS"] {
println!("cargo:rerun-if-env-changed={key}");
}
let threshold: u16 = std::env::var("ARMOR_THRESHOLD")
.unwrap_or_else(|_| "2000".into())
.parse()
.expect("ARMOR_THRESHOLD must be 0..4095");
assert!(threshold <= 4095, "ARMOR_THRESHOLD must be 0..4095");
let mut identity = b"RMIC_ARMOR_V2\0".to_vec();
identity.extend_from_slice(&threshold.to_le_bytes());
identity.extend_from_slice(b"\0END_ARMOR");
std::fs::write(
std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("armor-identity.bin"),
identity,
)
.unwrap();
embuild::espidf::sysenv::output();
}
+103 -159
View File
@@ -18,14 +18,14 @@
//!
//! - 整车一条血量:100 起,每次受击 −3,减到 0 不变负;0 血四路全黑。
//! - 受击时**只有被打的那一路**灯带全黑 50 ms,其余三路不动。
//! - 颜色由队伍决定:队伍一红、队伍二蓝;`ARMOR_TEAM` 编译期注入。
//! - 颜色由队伍决定:队伍一红、队伍二蓝;客户端选择后定向下发。
//! - 血量账在板子上算,按 `protocol::ArmorHealth` 广播给本项目裁判终端。
//!
//! # 构建与烧录
//!
//! ```text
//! scripts/build_armor.sh # 用 .env 里的 WIFI_SSID/WIFI_PASS/ARMOR_TEAM
//! scripts/flash_armor.sh # 编译 + espflash + 串口日志
//! armor/scripts/build.sh # 用 .env 里的 WIFI_SSID/WIFI_PASS
//! armor/scripts/flash.sh # 编译 + espflash + 串口日志
//! ```
//!
//! 串口调试走 UART0:RXD = GPIO20 / TXD = GPIO21,115200 8N1(日志从 TX 出来,
@@ -40,10 +40,12 @@ use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::hal::gpio::{PinDriver, Pull};
use esp_idf_svc::hal::peripherals::Peripherals;
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::{BlockingWifi, EspWifi};
use log::{error, info, warn};
use esp_idf_svc::wifi::EspWifi;
use log::{info, warn};
use armor_protocol::{Armor, Button, ButtonEvent, Plate, ReportSchedule, Rules, TEAM_2};
use armor_protocol::{
Armor, Button, ButtonEvent, ClientLink, DamageLink, Plate, ReportSchedule, Rgb, Rules,
};
mod esp;
mod leds;
@@ -51,16 +53,10 @@ mod net;
mod piezo;
mod settings;
/// WiFi 账号来自 .env(构建期注入,固件里不留密码)。
/// WiFi 账号来自 .env(构建期注入,凭据会编入镜像)。
const SSID: &str = env!("WIFI_SSID");
const PASSWORD: &str = env!("WIFI_PASS");
/// 编译期注入的队伍号:`0` = 队伍一(红),`1` = 队伍二(蓝)。不写就是队伍一。
const TEAM_ENV: &str = match option_env!("ARMOR_TEAM") {
Some(value) => value,
None => "0",
};
/// 受击阈值(原始 12 bit ADC)。参考实现用 2000,但压电片的幅度取决于贴装、线长
/// 与有没有放大级,所以这里留一个编译期入口:`ARMOR_THRESHOLD=1200`。
///
@@ -79,7 +75,7 @@ const REPORT_HEARTBEAT_MS: u64 = 200;
const STATUS_INTERVAL_MS: u64 = 1000;
/// WiFi 断线检查周期。
const WIFI_CHECK_MS: u64 = 5000;
const WIFI_CHECK_MS: u64 = 10000;
/// 毫秒时基。`esp_timer` 是微秒计数器,转毫秒后 u64 不会被绕回。
fn now_ms() -> u64 {
@@ -91,16 +87,23 @@ fn main() -> Result<()> {
// esp-idf-sys 的运行时补丁必须跑一次,日志系统也要先起来。
esp_idf_svc::sys::link_patches();
esp_idf_svc::log::EspLogger::initialize_default();
let team = armor_protocol::parse_team(TEAM_ENV)
.ok_or_else(|| anyhow!("ARMOR_TEAM must be 0 or 1, got {TEAM_ENV:?}"))?;
// 保留可由客户端核对的产品与阈值标记;不含 Wi-Fi 凭据。
info!(
"firmware identity: {:?}",
std::hint::black_box(include_bytes!(concat!(
env!("OUT_DIR"),
"/armor-identity.bin"
)))
);
let peripherals = Peripherals::take()?;
let sys_loop = EspSystemEventLoop::take()?;
let nvs = EspDefaultNvsPartition::take()?;
// 队别与颜色:ARMOR_TEAM 是权威,NVS 只记住结果。
let color = settings::Settings::new(nvs.clone())?.resolve_color(team)?;
let settings = settings::Settings::new(nvs.clone())?;
let mut team = settings.team()?;
let color = Rgb::for_team(team);
let mut client = ClientLink::default();
let mut damage = DamageLink::default();
let threshold: u16 = THRESHOLD_ENV
.parse()
@@ -117,7 +120,7 @@ fn main() -> Result<()> {
info!("pins: boot=GPIO9 debug uart0 rxd=GPIO20 txd=GPIO21 115200 8N1");
info!(
"armor board: team={team} ({}), {} hp, -{} per hit, {} ms dark on the hit strip",
if team == TEAM_2 { "blue" } else { "red" },
"client-selected",
armor.hp(),
rules.damage_per_hit,
rules.hit_blink.as_millis()
@@ -130,15 +133,11 @@ fn main() -> Result<()> {
let button = PinDriver::input(peripherals.pins.gpio9, Pull::Up)?;
let mut button_fsm = Button::default();
let mut wifi = BlockingWifi::wrap(
EspWifi::new(peripherals.modem, sys_loop.clone(), Some(nvs))?,
sys_loop,
)?;
// WiFi 是尽力而为:**连不上也绝不能挡住受击检测与灯效**。一块因为没网就不亮
// 灯的装甲板,在场上比"裁判端看不到血量"糟糕得多。所以这里只报警,主循环照跑,
// 由看门狗每 5 s 重试。
if let Err(err) = join(&mut wifi, Duration::from_secs(10)) {
warn!("no referee link yet ({err:#}); hits and LEDs still work, retrying every {WIFI_CHECK_MS} ms");
// EspWifi 的 connect 只发起关联;不等待 DHCP,不阻塞闪烁与受击采样。
let mut wifi = EspWifi::new(peripherals.modem, sys_loop, Some(nvs))?;
leds.refresh(client.strips(&armor, false, Duration::ZERO), now_ms())?;
if let Err(err) = join(&mut wifi) {
warn!("Wi-Fi connection attempt failed: {err:#}");
}
let reporter = net::Reporter::new()?;
@@ -162,6 +161,47 @@ fn main() -> Result<()> {
loop {
let now = Duration::from_millis(now_ms());
// 在采样前应用裁判许可;无网络、无客户端或许可过期时只闪烁,不扣血。
let wifi_up = link_state().associated() && sta_ip().is_some();
if !wifi_up {
client.disconnect();
damage.disconnect();
} else {
for _ in 0..8 {
match reporter.receive() {
Ok(Some((net::ControlCommand::Team(command), from))) => {
if command.board_id == sender_id
&& client.accept(from, now)
&& team != command.team
{
team = command.team;
armor.set_color(Rgb::for_team(team));
if let Err(err) = settings.save_team(team) {
warn!("could not save team: {err:#}");
}
info!("client selected team {team}");
force_report = true;
}
}
Ok(Some((net::ControlCommand::Damage(command), from))) => {
if command.board_id == sender_id {
damage.accept(command, from, now);
}
}
Ok(None) => break,
Err(err) => {
warn!("client control receive failed: {err:#}");
break;
}
}
}
}
let enabled = wifi_up && client.connected(now) && damage.enabled(now);
if armor.damage_enabled() != enabled {
info!("damage enabled={enabled}");
}
armor.set_damage_enabled(enabled);
// 采样:一次读一帧(约 10 ms),这一帧就是主循环的节拍。
match piezo.read_frame(armor.rules().threshold, &mut hits) {
Ok(stats) => {
@@ -172,11 +212,12 @@ fn main() -> Result<()> {
for (plate, raw) in hits.iter().copied() {
if let Some(event) = armor.on_sample(plate, raw, now) {
info!(
"hit plate={} raw={} hp={} (hits={})",
"hit plate={} raw={} hp={} (hits={}, damage_enabled={})",
event.plate.name(),
event.raw,
event.hp,
armor.hits()
armor.hits(),
armor.damage_enabled()
);
if event.dead {
warn!("hp reached 0: all four strips stay dark until the next reset");
@@ -192,7 +233,7 @@ fn main() -> Result<()> {
}
// 灯带:只有内容变化的那一路才真的发 RMT(每秒另有一次强制全刷)。
let strips = armor.strips(now);
let strips = client.strips(&armor, wifi_up, now);
if let Err(err) = leds.refresh(strips, now_ms()) {
leds::log_failure(&err);
}
@@ -216,7 +257,7 @@ fn main() -> Result<()> {
// 上报:血量一变立刻发,其余按心跳重发。
let current_ms = now_ms();
if force_report || reports.due(armor.hp(), now) {
if wifi_up && (force_report || reports.due(armor.hp(), now)) {
match broadcast_health(&reporter, &armor, team, sender_id) {
Ok(()) => {
reports.mark_sent(armor.hp(), now);
@@ -241,29 +282,12 @@ fn main() -> Result<()> {
peak = [0u16; 4];
}
// WiFi 看门狗:**关联上 + 拿到 IP** 才算链路好。
//
// 判断不用 `BlockingWifi::is_connected()/is_up()`:那两个读的是 esp-idf-svc
// 自己的事件缓存,实测在 IDF v6.0.1 上会停留在"已连接",而 IDF 的 API 明明
// 说没关联(现场表现就是日志说一切正常、裁判端一个包都收不到)。所以这里
// 直接问 IDF:`esp_wifi_sta_get_ap_info()` 与 `esp_netif_get_ip_info()`。
//
// 重连时只给 3 s 等 IP(启动时给的 10 s):这里是主循环,等太久会漏掉受击。
// 每 10 s 重试;直接查询 IDF 关联/IP,绕开旧事件缓存。
if current_ms.saturating_sub(last_wifi_check_ms) >= WIFI_CHECK_MS {
last_wifi_check_ms = current_ms;
let link = link_state();
let ip = sta_ip();
let healthy = link.associated() && ip.is_some_and(|ip| !ip.is_unspecified());
if !healthy {
warn!("link is not usable ({}); reconnecting", describe_link(&link, ip));
// 断开再连:关联掉了或 DHCP 没下来时,只有重新来一遍才会好。
if let Err(err) = wifi.disconnect() {
warn!("disconnect failed: {err}");
}
if let Err(err) = join(&mut wifi, Duration::from_secs(3)) {
if !wifi_up {
let _ = wifi.disconnect();
if let Err(err) = join(&mut wifi) {
warn!("reconnect failed: {err:#}");
}
}
@@ -339,7 +363,12 @@ fn status_line(armor: &Armor, now: Duration, link: &str, peak: [u16; 4]) -> Stri
/// 现场"裁判端没显示"时,第一件事是分清链路问题还是对端问题:`reports` 在涨就说明
/// 包已经出去了,该去查裁判端;一直不动就是这块板子没连上。而"没连上"还要再分
/// 关联与 DHCP —— 关联上但 IP 是 0.0.0.0 是最容易看错的一种。
fn link_line(link: &Link, ip: Option<std::net::Ipv4Addr>, reports_sent: u64, report_errors: u64) -> String {
fn link_line(
link: &Link,
ip: Option<std::net::Ipv4Addr>,
reports_sent: u64,
report_errors: u64,
) -> String {
format!(
"{} reports={reports_sent} errs={report_errors}",
describe_link(link, ip)
@@ -350,11 +379,7 @@ fn link_line(link: &Link, ip: Option<std::net::Ipv4Addr>, reports_sent: u64, rep
#[derive(Debug, Clone)]
enum Link {
/// 关联上了:AP 名字、RSSI、信道。
Associated {
ssid: String,
rssi: i8,
channel: u8,
},
Associated { ssid: String, rssi: i8, channel: u8 },
/// 没关联(或者 IDF 说 STA 没在跑)。
Idle { rc: i32 },
}
@@ -395,9 +420,8 @@ fn link_state() -> Link {
/// `None` 表示还没拿到 DHCP 地址。0.0.0.0 也按 `None` 处理 —— 那等于没有地址。
fn sta_ip() -> Option<std::net::Ipv4Addr> {
// 默认 STA 网卡的 interface key(`esp_netif_create_default_wifi_sta` 用的就是它)。
let handle = unsafe {
esp_idf_svc::sys::esp_netif_get_handle_from_ifkey(c"WIFI_STA_DEF".as_ptr())
};
let handle =
unsafe { esp_idf_svc::sys::esp_netif_get_handle_from_ifkey(c"WIFI_STA_DEF".as_ptr()) };
if handle.is_null() {
return None;
}
@@ -443,84 +467,26 @@ fn describe_link(link: &Link, ip: Option<std::net::Ipv4Addr>) -> String {
}
}
/// 等到 STA 真的拿到 IP(权威来源),最多等 `timeout`。
///
/// 不用 `BlockingWifi::wait_netif_up()`:它读的是 esp-idf-svc 的事件缓存,在
/// IDF v6.0.1 上会"立刻成功"而实际没有地址 —— 那样 join() 会假装连上了,看门狗
/// 也就永远不会重试。
fn wait_for_ip(timeout: Duration) -> Option<std::net::Ipv4Addr> {
let deadline = std::time::Instant::now() + timeout;
loop {
if let Some(ip) = sta_ip() {
return Some(ip);
}
if std::time::Instant::now() >= deadline {
return None;
}
std::thread::sleep(Duration::from_millis(200));
}
}
/// 连上 WiFi 并等一个 IP(幂等:已启动就不再 start 一次)。
///
/// 连不上时把扫到的网络打出来:这块模块只有 2.4 GHz,SSID 若在 5 GHz 上,现场看到
/// 一张空列表比看一个关联超时有用得多。**调用方不应该因为这个错误就退出** —— 没有
/// 网也要能打灯。
fn join(wifi: &mut BlockingWifi<EspWifi<'static>>, ip_timeout: Duration) -> Result<()> {
/// 发起一次关联,不等待关联或 DHCP 完成,主循环负责查询实际链路状态。
fn join(wifi: &mut EspWifi<'static>) -> Result<()> {
wifi.set_configuration(&Configuration::Client(ClientConfiguration {
ssid: SSID.try_into().map_err(|_| anyhow!("WIFI_SSID too long"))?,
password: PASSWORD
.try_into()
.map_err(|_| anyhow!("WIFI_PASS too long"))?,
auth_method: default_auth_method(),
pmf_cfg: PmfConfiguration::Capable { required: false },
..Default::default()
}))?;
if !wifi.is_started()? {
wifi.start()?;
}
if !link_state().associated() {
let config = Configuration::Client(ClientConfiguration {
ssid: SSID
.try_into()
.map_err(|_| anyhow!("WIFI_SSID too long (max 32 bytes)"))?,
bssid: None,
auth_method: default_auth_method(),
password: PASSWORD
.try_into()
.map_err(|_| anyhow!("WIFI_PASS too long (max 64 bytes)"))?,
channel: None,
// 通告 PMF:WPA2/WPA3 混合模式的路由器否则会丢掉握手;`required: false`
// 仍然允许纯 WPA2 的 AP。
pmf_cfg: PmfConfiguration::Capable { required: false },
..Default::default()
});
wifi.set_configuration(&config)?;
if let Err(err) = wifi.connect() {
error!("could not join \"{SSID}\": {err}");
report_scan(wifi);
return Err(err.into());
}
}
// 省电模式换来的电流不值得:它会让上报晚一个信标间隔(上百毫秒),而"受击后
// 50 ms 变暗"这件事本来就是要给人即时反馈的。
let rc = unsafe {
esp_idf_svc::sys::esp_wifi_set_ps(esp_idf_svc::sys::wifi_ps_type_t_WIFI_PS_NONE)
};
wifi.connect()?;
let rc =
unsafe { esp_idf_svc::sys::esp_wifi_set_ps(esp_idf_svc::sys::wifi_ps_type_t_WIFI_PS_NONE) };
if rc != esp_idf_svc::sys::ESP_OK {
warn!("could not disable wifi power save ({})", esp::name(rc));
warn!("could not disable power save ({})", esp::name(rc));
}
let link = link_state();
let Some(ip) = wait_for_ip(ip_timeout) else {
report_scan(wifi);
return Err(anyhow!(
"no DHCP address within {} ms ({})",
ip_timeout.as_millis(),
describe_link(&link, None)
));
};
info!("joined \"{SSID}\" on {ip}");
Ok(())
}
@@ -532,25 +498,3 @@ fn default_auth_method() -> AuthMethod {
AuthMethod::WPA2Personal
}
}
/// 把扫到的网络打出来,并标出我们要连的那个。连不上时的第一诊断信息。
fn report_scan(wifi: &mut BlockingWifi<EspWifi<'static>>) {
match wifi.scan() {
Ok(aps) if aps.is_empty() => {
error!("scan found no networks; check the antenna and that the AP is on 2.4 GHz");
}
Ok(aps) => {
for ap in aps {
info!(
" {:<32} ch {:>2} {:>4} dBm {:?}{}",
ap.ssid,
ap.channel,
ap.signal_strength,
ap.auth_method,
if ap.ssid.as_str() == SSID { " <- target" } else { "" }
);
}
}
Err(err) => warn!("scan failed: {err}"),
}
}
+45 -6
View File
@@ -6,11 +6,8 @@
//! VFS 转接,而这里只需要"建一个 UDP socket + 广播"这一件事,直接用 IDF 原生的
//! `lwip_*` 就能与图传板跑在同一条被验证过的代码路径上。
//!
//! # 为什么不 bind
//!
//! 装甲板只发不收:血量是板子算出来的,裁判端只显示。所以 socket 不绑定端口,
//! 由 lwIP 选一个临时端口即可 —— 绑定 5601 反而会和裁判端、以及同网段的另一块
//! 装甲板抢同一个端口。裁判端监听 5601,板子往 5601 发,方向是单向的。
//! 血量发往 5601,客户端从监听 socket 定向回复广播的源 IP/临时端口。
//! 同一个 socket 非阻塞接收队伍设置和保活,无需新增端口。
//!
//! # 广播而不是单播
//!
@@ -24,7 +21,12 @@ use anyhow::{anyhow, Result};
use esp_idf_svc::sys as ffi;
use log::{info, warn};
use armor_protocol::{ARMOR_PORT, BROADCAST_ADDR};
use armor_protocol::{ArmorControl, ArmorDamageControl, ARMOR_PORT, BROADCAST_ADDR};
pub enum ControlCommand {
Team(ArmorControl),
Damage(ArmorDamageControl),
}
/// 把 Rust 的 socket 地址转成 lwIP 期望的 C 结构。
///
@@ -69,6 +71,43 @@ 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() };
let mut len = core::mem::size_of::<ffi::sockaddr_in>() as ffi::socklen_t;
let count = unsafe {
ffi::lwip_recvfrom(
self.socket,
bytes.as_mut_ptr().cast(),
bytes.len(),
ffi::MSG_DONTWAIT as i32,
(&mut addr as *mut ffi::sockaddr_in).cast(),
&mut len,
)
};
if count < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock {
return Ok(None);
}
return Err(err.into());
}
let bytes = &bytes[..count as usize];
let control = if let Some(control) = ArmorControl::decode(bytes) {
ControlCommand::Team(control)
} else if let Some(control) = ArmorDamageControl::decode(bytes) {
ControlCommand::Damage(control)
} else {
return Ok(None);
};
let ip = std::net::Ipv4Addr::from(addr.sin_addr.s_addr.to_le_bytes());
Ok(Some((
control,
SocketAddrV4::new(ip, u16::from_be(addr.sin_port)),
)))
}
/// 建一个开了广播许可的 UDP socket。
pub fn new() -> Result<Self> {
// SAFETY: 建 socket 不涉及 Rust 内存。
+2 -2
View File
@@ -163,8 +163,8 @@ impl Piezo {
}
esp::check("adc_continuous_read", rc)?;
let count = (out_length as usize / ffi::SOC_ADC_DIGI_RESULT_BYTES as usize)
.min(FRAME_MEASUREMENTS);
let count =
(out_length as usize / ffi::SOC_ADC_DIGI_RESULT_BYTES as usize).min(FRAME_MEASUREMENTS);
stats.samples = count;
for index in 0..count {
+14 -52
View File
@@ -1,65 +1,27 @@
//! 板子自己的持久化设置(NVS):队别与颜色。
//!
//! 命名空间与键名都沿用参考实现(`armor` / `color`),所以从参考固件刷过来时,
//! 之前存过的颜色还能被读到。新增一个 `team` 键用来记住这块板子是哪一队。
//! 客户端选择的队伍持久化;仅在队伍变化时写 NVS。
use anyhow::Result;
use armor_protocol::{Rgb, ARMOR_UNASSIGNED};
use esp_idf_svc::nvs::{EspDefaultNvsPartition, EspNvs, NvsDefault};
use log::info;
use armor_protocol::Rgb;
/// NVS 命名空间(与参考实现一致)。
const NAMESPACE: &str = "armor";
/// 队别键名。
const KEY_TEAM: &str = "team";
/// 颜色键名,值是 `0x00RRGGBB`(与参考实现一致)。
const KEY_COLOR: &str = "color";
/// 打开着的 NVS 句柄。
pub struct Settings {
nvs: EspNvs<NvsDefault>,
}
impl Settings {
/// 打开(必要时创建)命名空间。
pub fn new(partition: EspDefaultNvsPartition) -> Result<Self> {
Ok(Self {
nvs: EspNvs::new(partition, NAMESPACE, true)?,
nvs: EspNvs::new(partition, "armor", true)?,
})
}
/// 定出这次该用哪个颜色,并把它写回 NVS。
///
/// 规则:**编译期注入的 `ARMOR_TEAM` 是权威**。换队伍只要重刷固件,不用先擦
/// NVS;NVS 里的值只用来记住当前状态(也给以后加"手动换色"留位置)。两者
/// 不一致时以 `ARMOR_TEAM` 为准并覆盖,日志里会说一声,免得现场纳闷为什么
/// 灯色变了。
pub fn resolve_color(&self, team: u8) -> Result<Rgb> {
let expected = Rgb::for_team(team);
let stored_team = self.nvs.get_u8(KEY_TEAM)?;
let stored_color = self.nvs.get_u32(KEY_COLOR)?;
let color = match (stored_team, stored_color) {
(Some(stored), Some(raw)) if stored == team => Rgb::from_u32(raw),
(Some(stored), Some(raw)) => {
info!(
"ARMOR_TEAM={team} overrides the stored team {stored} (colour #{raw:06X}); rewriting NVS"
);
expected
}
_ => {
info!(
"first boot as team {team}: storing colour #{:06X}",
expected.to_u32()
);
expected
}
};
self.nvs.set_u8(KEY_TEAM, team)?;
self.nvs.set_u32(KEY_COLOR, color.to_u32())?;
Ok(color)
pub fn team(&self) -> Result<u8> {
Ok(self
.nvs
.get_u8("team")?
.filter(|team| *team <= 1)
.unwrap_or(ARMOR_UNASSIGNED))
}
pub fn save_team(&self, team: u8) -> Result<()> {
self.nvs.set_u8("team", team)?;
self.nvs.set_u32("color", Rgb::for_team(team).to_u32())?;
Ok(())
}
}