feat(client): 同步每路镜像并精简操控入口与 HUD 映射
This commit is contained in:
28 files changed
+501
-60
No files matched your search
@@ -200,6 +200,7 @@ pub struct ArmorHealthStore {
|
|||||||
sink: Mutex<Option<ArmorSink>>,
|
sink: Mutex<Option<ArmorSink>>,
|
||||||
assignments: Mutex<Vec<(u32, u8)>>,
|
assignments: Mutex<Vec<(u32, u8)>>,
|
||||||
match_sink: Mutex<Option<MatchSink>>,
|
match_sink: Mutex<Option<MatchSink>>,
|
||||||
|
mirror_sink: Mutex<Option<Arc<dyn Fn(protocol::CameraMirror) + Send + Sync>>>,
|
||||||
match_result_sink: Mutex<Option<MatchResultSink>>,
|
match_result_sink: Mutex<Option<MatchResultSink>>,
|
||||||
damage_participants: Mutex<HashSet<u32>>,
|
damage_participants: Mutex<HashSet<u32>>,
|
||||||
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
|
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
|
||||||
@@ -219,6 +220,7 @@ impl ArmorHealthStore {
|
|||||||
sink: Mutex::new(None),
|
sink: Mutex::new(None),
|
||||||
assignments: Mutex::new(Vec::new()),
|
assignments: Mutex::new(Vec::new()),
|
||||||
match_sink: Mutex::new(None),
|
match_sink: Mutex::new(None),
|
||||||
|
mirror_sink: Mutex::new(None),
|
||||||
match_result_sink: Mutex::new(None),
|
match_result_sink: Mutex::new(None),
|
||||||
damage_participants: Mutex::new(HashSet::new()),
|
damage_participants: Mutex::new(HashSet::new()),
|
||||||
reset: Mutex::new(None),
|
reset: Mutex::new(None),
|
||||||
@@ -278,6 +280,17 @@ impl ArmorHealthStore {
|
|||||||
|
|
||||||
/// 处理一条上报。测试从这里喂字节。
|
/// 处理一条上报。测试从这里喂字节。
|
||||||
pub fn datagram(&self, bytes: &[u8], from: SocketAddr) {
|
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 {
|
let SocketAddr::V4(addr) = from else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -418,6 +431,9 @@ impl ArmorHealthStore {
|
|||||||
pub fn set_match_sink(&self, sink: MatchSink) {
|
pub fn set_match_sink(&self, sink: MatchSink) {
|
||||||
*self.match_sink.lock().expect("match sink poisoned") = Some(sink);
|
*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) {
|
pub fn set_match_result_sink(&self, sink: MatchResultSink) {
|
||||||
*self
|
*self
|
||||||
.match_result_sink
|
.match_result_sink
|
||||||
|
|||||||
@@ -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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -440,6 +440,7 @@ pub struct Config {
|
|||||||
pub mirror: bool,
|
pub mirror: bool,
|
||||||
/// 上下镜像,与左右镜像独立;旧配置默认关闭。
|
/// 上下镜像,与左右镜像独立;旧配置默认关闭。
|
||||||
pub mirror_vertical: bool,
|
pub mirror_vertical: bool,
|
||||||
|
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||||
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
||||||
///
|
///
|
||||||
/// 只对用户端有意义([`Role::needs_password`])。
|
/// 只对用户端有意义([`Role::needs_password`])。
|
||||||
@@ -466,6 +467,7 @@ impl Default for Config {
|
|||||||
armor_id: None,
|
armor_id: None,
|
||||||
mirror: true,
|
mirror: true,
|
||||||
mirror_vertical: false,
|
mirror_vertical: false,
|
||||||
|
camera_mirrors: Default::default(),
|
||||||
password: None,
|
password: None,
|
||||||
hud: HudConfig::default(),
|
hud: HudConfig::default(),
|
||||||
referee: RefereeConfig::default(),
|
referee: RefereeConfig::default(),
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
pub mod armor;
|
pub mod armor;
|
||||||
pub mod armor_reset;
|
pub mod armor_reset;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod camera_mirror;
|
||||||
pub mod match_clock;
|
pub mod match_clock;
|
||||||
pub mod operator;
|
pub mod operator;
|
||||||
pub mod password;
|
pub mod password;
|
||||||
|
|||||||
@@ -385,6 +385,7 @@ pub struct SlotsDto {
|
|||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Snapshot {
|
pub struct Snapshot {
|
||||||
|
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||||
pub operator_control: crate::operator::OperatorView,
|
pub operator_control: crate::operator::OperatorView,
|
||||||
pub match_clock: crate::match_clock::MatchView,
|
pub match_clock: crate::match_clock::MatchView,
|
||||||
pub role: Role,
|
pub role: Role,
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "rmic-2026",
|
"name": "rmic-2026",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.5.0",
|
"version": "0.6.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -234,9 +234,7 @@ pub fn set_role(
|
|||||||
/// 左右镜像。摄像头装反了才需要,不是判罚相关的东西,所以不设密码。
|
/// 左右镜像。摄像头装反了才需要,不是判罚相关的东西,所以不设密码。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||||
state
|
state.set_camera_mirror(None, Some(mirror), None)?;
|
||||||
.update_config(move |config| config.mirror = mirror)
|
|
||||||
.map_err(|err| format!("{err}"))?;
|
|
||||||
|
|
||||||
Ok(ConfigView::from(&state.config()))
|
Ok(ConfigView::from(&state.config()))
|
||||||
}
|
}
|
||||||
@@ -244,13 +242,21 @@ pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String>
|
|||||||
/// 上下镜像,独立保存,不改动左右镜像。
|
/// 上下镜像,独立保存,不改动左右镜像。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||||
state
|
state.set_camera_mirror(None, None, Some(mirror_vertical))?;
|
||||||
.update_config(move |config| config.mirror_vertical = mirror_vertical)
|
|
||||||
.map_err(|err| format!("{err}"))?;
|
|
||||||
|
|
||||||
Ok(ConfigView::from(&state.config()))
|
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 设置(血条、瞄准器、网格、命中反馈)。
|
/// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||||
|
|||||||
@@ -344,6 +344,7 @@ fn run() -> Result<(), Box<dyn Error>> {
|
|||||||
commands::set_team,
|
commands::set_team,
|
||||||
commands::set_role,
|
commands::set_role,
|
||||||
commands::set_mirror,
|
commands::set_mirror,
|
||||||
|
commands::set_camera_mirror,
|
||||||
commands::set_mirror_vertical,
|
commands::set_mirror_vertical,
|
||||||
commands::save_hud,
|
commands::save_hud,
|
||||||
commands::set_team_name,
|
commands::set_team_name,
|
||||||
|
|||||||
@@ -60,6 +60,8 @@ pub struct AppState {
|
|||||||
match_socket: Option<std::net::UdpSocket>,
|
match_socket: Option<std::net::UdpSocket>,
|
||||||
match_error: Mutex<Option<String>>,
|
match_error: Mutex<Option<String>>,
|
||||||
match_changed: tokio::sync::Notify,
|
match_changed: tokio::sync::Notify,
|
||||||
|
mirror_inbox: Mutex<cam_core::camera_mirror::CameraMirrors>,
|
||||||
|
mirror_origin: u64,
|
||||||
operator: Mutex<OperatorState>,
|
operator: Mutex<OperatorState>,
|
||||||
operator_socket: Option<std::net::UdpSocket>,
|
operator_socket: Option<std::net::UdpSocket>,
|
||||||
operator_focused: AtomicBool,
|
operator_focused: AtomicBool,
|
||||||
@@ -90,6 +92,125 @@ pub struct AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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,
|
||||||
|
};
|
||||||
|
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.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 {
|
fn operator_context(&self) -> OperatorContext {
|
||||||
let config = self.config();
|
let config = self.config();
|
||||||
let clock = self.match_view();
|
let clock = self.match_view();
|
||||||
@@ -432,6 +553,8 @@ impl AppState {
|
|||||||
match_socket,
|
match_socket,
|
||||||
match_error: Mutex::new(match_error),
|
match_error: Mutex::new(match_error),
|
||||||
match_changed: tokio::sync::Notify::new(),
|
match_changed: tokio::sync::Notify::new(),
|
||||||
|
mirror_inbox: Mutex::new(Default::default()),
|
||||||
|
mirror_origin: session.max(1),
|
||||||
operator: Mutex::new(OperatorState::new(session)),
|
operator: Mutex::new(OperatorState::new(session)),
|
||||||
operator_socket,
|
operator_socket,
|
||||||
operator_focused: AtomicBool::new(true),
|
operator_focused: AtomicBool::new(true),
|
||||||
@@ -462,6 +585,17 @@ impl AppState {
|
|||||||
///
|
///
|
||||||
/// 必须在 `Arc<AppState>` 建好之后调用(sink 里要持有 state 的通道)。
|
/// 必须在 `Arc<AppState>` 建好之后调用(sink 里要持有 state 的通道)。
|
||||||
pub fn install_sinks(self: &Arc<Self>) {
|
pub fn install_sinks(self: &Arc<Self>) {
|
||||||
|
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);
|
let weak = Arc::downgrade(self);
|
||||||
self.armor.set_match_sink(Arc::new(move |packet, ip| {
|
self.armor.set_match_sink(Arc::new(move |packet, ip| {
|
||||||
if let Some(state) = weak.upgrade() {
|
if let Some(state) = weak.upgrade() {
|
||||||
@@ -848,6 +982,7 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn tick(&self) {
|
pub fn tick(&self) {
|
||||||
|
self.tick_mirrors();
|
||||||
self.tick_match();
|
self.tick_match();
|
||||||
let online: Vec<u32> = self
|
let online: Vec<u32> = self
|
||||||
.discovery
|
.discovery
|
||||||
@@ -958,12 +1093,19 @@ impl AppState {
|
|||||||
.apply_outcomes(&mut health);
|
.apply_outcomes(&mut health);
|
||||||
|
|
||||||
Snapshot {
|
Snapshot {
|
||||||
|
camera_mirrors: config.camera_mirrors.clone(),
|
||||||
operator_control: self.operator.lock().expect("operator poisoned").view(),
|
operator_control: self.operator.lock().expect("operator poisoned").view(),
|
||||||
match_clock: self.match_view(),
|
match_clock: self.match_view(),
|
||||||
role: config.role,
|
role: config.role,
|
||||||
team: config.team,
|
team: config.team,
|
||||||
mirrored: config.mirror,
|
mirrored: config
|
||||||
mirrored_vertical: config.mirror_vertical,
|
.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,
|
demo: self.demo,
|
||||||
diagnostics,
|
diagnostics,
|
||||||
unlocked: self.is_unlocked(),
|
unlocked: self.is_unlocked(),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "RMIC-2026",
|
"productName": "RMIC-2026",
|
||||||
"version": "0.5.0",
|
"version": "0.6.0",
|
||||||
"identifier": "com.simbarobotics.rmic2026",
|
"identifier": "com.simbarobotics.rmic2026",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -1,29 +1,39 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
import type { Snapshot } from "../lib/types";
|
import type { Snapshot } from "../lib/types";
|
||||||
import { operatorGate, type useOperatorControl } from "../lib/use-operator-control";
|
import { operatorGate, type useOperatorControl } from "../lib/use-operator-control";
|
||||||
|
import { Slider } from "./controls";
|
||||||
|
import { OperatorMapping } from "./OperatorMapping";
|
||||||
|
|
||||||
export function OperatorControls({ control, snapshot, connected, blocked }: {
|
export function OperatorControls({ control, snapshot, connected, blocked }: {
|
||||||
control: ReturnType<typeof useOperatorControl>;
|
control: ReturnType<typeof useOperatorControl>; snapshot: Snapshot; connected: boolean; blocked: boolean;
|
||||||
snapshot: Snapshot;
|
|
||||||
connected: boolean;
|
|
||||||
blocked: boolean;
|
|
||||||
}) {
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const root = useRef<HTMLElement>(null);
|
||||||
const matchReason = operatorGate(snapshot, connected, "match");
|
const matchReason = operatorGate(snapshot, connected, "match");
|
||||||
const debugReason = operatorGate(snapshot, connected, "debug");
|
const debugReason = operatorGate(snapshot, connected, "debug");
|
||||||
return <section className={`operator-controls${control.activeMode ? " is-active" : ""}${control.activeMode === "debug" ? " is-debug" : ""}`} aria-label="机器人操作" onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()}>
|
useEffect(() => { if (blocked || control.activeMode) setOpen(false); }, [blocked, control.activeMode]);
|
||||||
{control.activeMode ? <>
|
useEffect(() => {
|
||||||
<strong>{control.activeMode === "debug" ? "赛前调试发送中" : "操作输入发送中"}{snapshot.demo ? " · 合成输入" : ""}</strong>
|
const dismiss = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); };
|
||||||
<span>WASD 移动 · 鼠标控制云台 · 左键发射 · ESC 退出</span>
|
document.addEventListener("pointerdown", dismiss);
|
||||||
<small>{snapshot.demo ? "仅合成预览,无真实发送" : "仅表示客户端发送状态;装甲板及下位机无应答"}</small>
|
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)}>
|
||||||
|
<i className={control.activeMode ? "is-on" : ""} />{control.activeMode === "debug" ? "调试发送" : control.activeMode ? "操控发送" : "操控"}<span>{control.activeMode ? "ESC" : open ? "−" : "+"}</span>
|
||||||
|
</button>
|
||||||
|
{open && <div className="operator-controls__menu" id="operator-submenu">
|
||||||
<div className="operator-controls__actions">
|
<div className="operator-controls__actions">
|
||||||
<button className="btn btn--primary" disabled={blocked || control.pending || !!matchReason} title={matchReason ?? "锁定鼠标并开始接收键鼠输入"} onClick={() => control.start("match")}>{control.pending ? "正在处理…" : "开启比赛操作"}</button>
|
<button className="btn" disabled={!!matchReason} title={matchReason ?? "WASD / 鼠标 / 左键"} onClick={() => {setOpen(false);control.start("match");}}>比赛操作</button>
|
||||||
<button className="btn" disabled={blocked || control.pending || !!debugReason} title={debugReason ?? "未开赛时显式开启调试,开始倒数后自动停止"} onClick={() => control.start("debug")}>开启赛前调试</button>
|
<button className="btn" disabled={!!debugReason} title={debugReason ?? "未开赛时发送调试输入"} onClick={() => {setOpen(false);control.start("debug");}}>赛前调试</button>
|
||||||
</div>
|
</div>
|
||||||
<label className="operator-controls__sensitivity">鼠标灵敏度 <input aria-label="本次鼠标灵敏度" type="range" min="0.25" max="4" step="0.25" value={control.sensitivity} onChange={event => control.setSensitivity(Number(event.target.value))} /><span>×{control.sensitivity.toFixed(2)} · 本次</span></label>
|
<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>
|
||||||
<p>{snapshot.demo ? "预览使用合成数据,不向装甲板发送真实操作。" : "WASD 移动 · 鼠标控制云台速度 · 左键发射;ESC 或失焦立即停止。"}</p>
|
{matchReason && debugReason && <small>{debugReason}</small>}
|
||||||
{!snapshot.demo && <p>仅确认客户端发送,装甲板及下位机未提供应答。装甲板重启或连接超时后,请退出再开启。</p>}
|
{snapshot.demo && <small>合成预览</small>}
|
||||||
{matchReason && debugReason && <p>{matchReason};{debugReason}</p>}
|
{control.error && <small role="alert">{control.error}</small>}
|
||||||
{control.error && <p className="operator-controls__error" role="alert">{control.error}</p>}
|
</div>}
|
||||||
</>}
|
{!open && control.error && <span className="operator-controls__fault" role="alert" title={control.error}>操作已停止</span>}
|
||||||
</section>;
|
</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>;
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
const previewMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }> = {};
|
||||||
/**
|
/**
|
||||||
* 仅开发用的浏览器预览。
|
* 仅开发用的浏览器预览。
|
||||||
*
|
*
|
||||||
@@ -243,6 +244,9 @@ function handle(command: string, args: Record<string, unknown>): unknown {
|
|||||||
case "set_role":
|
case "set_role":
|
||||||
state.role = args.role as "team" | "referee";
|
state.role = args.role as "team" | "referee";
|
||||||
return configView();
|
return configView();
|
||||||
|
case "set_camera_mirror":
|
||||||
|
previewMirrors[String(args.camera)] = { mirror: Boolean(args.mirror), mirrorVertical: Boolean(args.mirrorVertical) };
|
||||||
|
return;
|
||||||
case "set_mirror":
|
case "set_mirror":
|
||||||
state.mirror = Boolean(args.mirror);
|
state.mirror = Boolean(args.mirror);
|
||||||
return configView();
|
return configView();
|
||||||
@@ -432,6 +436,7 @@ function snapshot(): Snapshot {
|
|||||||
team: state.team,
|
team: state.team,
|
||||||
mirrored: state.mirror,
|
mirrored: state.mirror,
|
||||||
mirroredVertical: state.mirrorVertical,
|
mirroredVertical: state.mirrorVertical,
|
||||||
|
cameraMirrors: previewMirrors,
|
||||||
matchClock: previewMatch(),
|
matchClock: previewMatch(),
|
||||||
operatorControl: { ...previewOperator },
|
operatorControl: { ...previewOperator },
|
||||||
demo: true,
|
demo: true,
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ export const api = {
|
|||||||
call<ConfigView>("set_team", { team, password: password ?? null }),
|
call<ConfigView>("set_team", { team, password: password ?? null }),
|
||||||
setRole: (role: Role, password?: string) =>
|
setRole: (role: Role, password?: string) =>
|
||||||
call<ConfigView>("set_role", { role, password: password ?? null }),
|
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 }),
|
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
||||||
setMirrorVertical: (mirrorVertical: boolean) => call<ConfigView>("set_mirror_vertical", { mirrorVertical }),
|
setMirrorVertical: (mirrorVertical: boolean) => call<ConfigView>("set_mirror_vertical", { mirrorVertical }),
|
||||||
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
||||||
|
|||||||
@@ -227,6 +227,7 @@ export interface MediaFileDto {
|
|||||||
|
|
||||||
/** `cam_core::snapshot::Snapshot` */
|
/** `cam_core::snapshot::Snapshot` */
|
||||||
export interface Snapshot {
|
export interface Snapshot {
|
||||||
|
cameraMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }>;
|
||||||
operatorControl: OperatorControlView;
|
operatorControl: OperatorControlView;
|
||||||
matchClock: MatchClockView;
|
matchClock: MatchClockView;
|
||||||
role: Role;
|
role: Role;
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ export function operatorGate(snapshot: Snapshot, connected: boolean, mode: Opera
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useOperatorControl(options: Options) {
|
export function useOperatorControl(options: Options) {
|
||||||
|
const mapping = useRef(neutralAxes());
|
||||||
const target = useRef<HTMLDivElement>(null);
|
const target = useRef<HTMLDivElement>(null);
|
||||||
const current = useRef(options);
|
const current = useRef(options);
|
||||||
current.current = options;
|
current.current = options;
|
||||||
@@ -43,6 +44,7 @@ export function useOperatorControl(options: Options) {
|
|||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
const stop = useCallback((reason = "") => {
|
const stop = useCallback((reason = "") => {
|
||||||
|
mapping.current = neutralAxes();
|
||||||
generation.current++;
|
generation.current++;
|
||||||
attempt.current = null;
|
attempt.current = null;
|
||||||
sampler.current.reset(performance.now());
|
sampler.current.reset(performance.now());
|
||||||
@@ -177,6 +179,7 @@ export function useOperatorControl(options: Options) {
|
|||||||
}
|
}
|
||||||
const sampled = sampler.current.sample(performance.now(), sensitivityRef.current);
|
const sampled = sampler.current.sample(performance.now(), sensitivityRef.current);
|
||||||
if (sampled.stalled) { stop("界面输入已超时,操作已停止,请重新开启"); return; }
|
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() });
|
session.sender.offer({ input: { captureId: session.id, sequence: ++session.sequence, active: true, ...sampled.axes }, at: performance.now() });
|
||||||
}, INPUT_INTERVAL_MS);
|
}, INPUT_INTERVAL_MS);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -199,5 +202,5 @@ export function useOperatorControl(options: Options) {
|
|||||||
sensitivityRef.current = value;
|
sensitivityRef.current = value;
|
||||||
setSensitivityState(value);
|
setSensitivityState(value);
|
||||||
};
|
};
|
||||||
return { target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
return { mapping, target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
||||||
}
|
}
|
||||||
@@ -6,16 +6,16 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export const BUILD = {
|
export const BUILD = {
|
||||||
version: "0.5.0",
|
version: "0.6.0",
|
||||||
major: 0,
|
major: 0,
|
||||||
minor: 5,
|
minor: 6,
|
||||||
patch: 0,
|
patch: 0,
|
||||||
/** git 提交数,单调递增。 */
|
/** git 提交数,单调递增。 */
|
||||||
build: 46,
|
build: 47,
|
||||||
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
||||||
protocol: 1,
|
protocol: 1,
|
||||||
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
||||||
date: "2026-10-31",
|
date: "2026-11-01",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
|
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
|
||||||
|
|||||||
@@ -248,8 +248,8 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
|||||||
? "已连接,等待画面…"
|
? "已连接,等待画面…"
|
||||||
: `等待${label}的图传`
|
: `等待${label}的图传`
|
||||||
}
|
}
|
||||||
mirrored={snapshot.mirrored}
|
mirrored={snapshot.cameraMirrors[String(pane.camera)]?.mirror ?? snapshot.mirrored}
|
||||||
mirroredVertical={snapshot.mirroredVertical}
|
mirroredVertical={snapshot.cameraMirrors[String(pane.camera)]?.mirrorVertical ?? snapshot.mirroredVertical}
|
||||||
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
||||||
crosshair={null}
|
crosshair={null}
|
||||||
grid={hud.grid}
|
grid={hud.grid}
|
||||||
@@ -265,6 +265,13 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
|||||||
focused={focused}
|
focused={focused}
|
||||||
onSelect={() => setScope((current) => (current === pane.key ? "all" : pane.key))}
|
onSelect={() => setScope((current) => (current === pane.key ? "all" : pane.key))}
|
||||||
>
|
>
|
||||||
|
{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)}>{vertical ? "上下镜像" : "左右镜像"}{checked ? " · 开" : " · 关"}</button>;
|
||||||
|
})}
|
||||||
|
</div>}
|
||||||
{hud.health.visible && pane.health && (
|
{hud.health.visible && pane.health && (
|
||||||
<div className={`ref__bar ref__bar--${pane.align}`}>
|
<div className={`ref__bar ref__bar--${pane.align}`}>
|
||||||
<HealthBar health={pane.health} config={hud.health} align={pane.align} />
|
<HealthBar health={pane.health} config={hud.health} align={pane.align} />
|
||||||
|
|||||||
@@ -107,16 +107,34 @@
|
|||||||
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
|
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
|
||||||
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
|
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
|
||||||
|
|
||||||
.operator-controls { position: absolute; z-index: 16; left: 50%; bottom: clamp(70px, 12vh, 120px); transform: translateX(-50%); width: min(580px, calc(100% - 48px)); padding: 14px 18px; color: var(--ink); background: #07100de8; border: 1px solid #74af8b55; font: 12px/1.5 var(--font-ui); text-align: center; }
|
/* 操控入口只占左下角一行,参数在二级菜单中展开。 */
|
||||||
.operator-controls__actions { display: flex; justify-content: center; gap: 12px; }
|
.operator-controls { position: absolute; z-index: 16; left: 28px; bottom: 48px; color: var(--ink); }
|
||||||
.operator-controls__sensitivity { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 12px; }
|
.operator-controls__toggle { gap: 10px; min-width: 116px; background: var(--panel); }
|
||||||
.operator-controls__sensitivity input { width: 120px; }
|
.operator-controls__toggle > i { width: 6px; height: 6px; background: var(--ink-3); }
|
||||||
.operator-controls__sensitivity span { min-width: 88px; color: var(--ink-2); }
|
.operator-controls__toggle > i.is-on { background: var(--hud); }
|
||||||
.operator-controls p { margin: 8px 0 0; color: var(--ink-2); }
|
.operator-controls__toggle > span { margin-left: auto; color: var(--ink-3); font: 10px var(--font-mono); }
|
||||||
.operator-controls .operator-controls__error { color: var(--warn); }
|
.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.is-active { width: auto; max-width: calc(100% - 48px); padding: 8px 14px; bottom: 58px; display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 16px; pointer-events: none; }
|
.operator-controls__actions { display: flex; gap: 8px; }
|
||||||
.operator-controls.is-active strong { color: var(--hud); white-space: nowrap; }
|
.operator-controls__actions > button { flex: 1; }
|
||||||
.operator-controls.is-active small { flex-basis: 100%; color: var(--ink-2); font-size: 10px; }
|
.operator-controls__sensitivity { display: grid; gap: 4px; font-size: 11px; color: var(--ink-2); }
|
||||||
.operator-controls.is-debug { border-color: var(--warn-line); }
|
.operator-controls__menu small { font-size: 10px; color: var(--ink-3); }
|
||||||
.operator-controls.is-debug strong { color: var(--warn); }
|
.operator-controls__fault { margin-left: 10px; font-size: 10px; color: var(--warn); }
|
||||||
@media (max-height: 650px) { .operator-controls { bottom: 68px; padding: 10px 14px; } .operator-controls.is-active { bottom: 42px; } }
|
.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 { position: absolute; z-index: 8; bottom: 42px; right: 12px; display: flex; gap: 6px; }
|
||||||
|
.ref__mirror-controls .btn { background: var(--panel); font-size: 10px; }
|
||||||
|
@media (max-height: 650px) { .operator-controls { bottom: 38px; } .operator-mapping { padding: 10px 18px; } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .operator-controls__menu, .operator-mapping { animation: none; } .operator-mapping__track > i { transition: none; } }
|
||||||
@@ -58,10 +58,14 @@ client/
|
|||||||
|
|
||||||
### 选手键鼠操作
|
### 选手键鼠操作
|
||||||
|
|
||||||
绑定在线 C3 后,可在画面下方开启操作:WASD 平移、鼠标滑动控制云台速度、左键按住发送发射状态。鼠标锁定后不受窗口边缘限制;按 ESC 退出,再按 ESC 打开菜单。比赛模式仅在比赛进行中有效;“赛前调试”单独开启,准备、待开赛或尚未连接裁判时可使用,开始倒计时会退出。失焦、断连、结束或输入超时均回零,恢复后需重新点击。
|
绑定在线 C3 后,可在画面左下角“操控”开关的二级菜单开启操作:WASD 平移、鼠标滑动控制云台速度、左键按住发送发射状态。鼠标锁定后不受窗口边缘限制;按 ESC 退出,再按 ESC 打开菜单。比赛模式仅在比赛进行中有效;“赛前调试”单独开启,准备、待开赛或尚未连接裁判时可使用,开始倒计时会退出。失焦、断连、结束或输入超时均回零,恢复后需重新点击。
|
||||||
|
|
||||||
默认 1000 像素/秒映射到通道满幅 ±1000,支持本次会话的灵敏度调节。装甲板 TXD/GPIO21 以 115200 8N1 输出项目协议,软件日志改走 USB。客户端与 C3 均需更新,并在下位机接入解析器;当前没有串口操控应答,界面不表示电机已经响应。完整映射、串口帧与 C99 接收示例见[键鼠操作与用户 UART](../protocol/operator-control.md)。
|
默认 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` 检查速度换算、停止与最新输入队列;浏览器预览只模拟本地输入,页面标记“合成输入”,不会发送现场控制。
|
`pnpm test:input` 检查速度换算、停止与最新输入队列;浏览器预览只模拟本地输入,页面标记“合成输入”,不会发送现场控制。
|
||||||
|
|
||||||
### 配色:墨黑蓝打底,只有一支红
|
### 配色:墨黑蓝打底,只有一支红
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
|
|||||||
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
|
||||||
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
|
||||||
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
|
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
|
||||||
|
| 12 `CameraMirror` | 选手端 ↔ 裁判端 | 每路图传镜像寄存器,广播 UDP 5601 |
|
||||||
| 11 `OperatorControl` | 选手端 → 绑定的装甲板 | 四轴速度和发射状态,定向发送到主板上报端口 |
|
| 11 `OperatorControl` | 选手端 → 绑定的装甲板 | 四轴速度和发射状态,定向发送到主板上报端口 |
|
||||||
|
|
||||||
类型 11 保持线路版本 1,不改变旧消息布局;旧 C3 会忽略该类型,使用操控功能需更新 C3。载荷、租约及下游 UART 帧见[键鼠操作与用户 UART](operator-control.md)。
|
类型 11 保持线路版本 1,不改变旧消息布局;旧 C3 会忽略该类型,使用操控功能需更新 C3。载荷、租约及下游 UART 帧见[键鼠操作与用户 UART](operator-control.md)。
|
||||||
@@ -289,3 +290,11 @@ UDP 不保证数据报的顺序和到达。接收端等待下一张完整帧,
|
|||||||
客户端先进入结束阶段并发送禁止扣血许可,再向固定的本局槽位主板发送同序号复位请求;每 200 ms 随新许可更新请求序号,最多等待 3 秒。板端只接受目标 id 匹配、同一来源 IP/端口与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复满血并清受击计数、冷却;同复位 id 的重试只回复回执并重发血量,不重复复位。旧复位 id、旧许可序号、过期许可及运行许可下的请求均拒绝。
|
客户端先进入结束阶段并发送禁止扣血许可,再向固定的本局槽位主板发送同序号复位请求;每 200 ms 随新许可更新请求序号,最多等待 3 秒。板端只接受目标 id 匹配、同一来源 IP/端口与会话、序号等于最新有效禁止扣血许可的请求。首次执行恢复满血并清受击计数、冷却;同复位 id 的重试只回复回执并重发血量,不重复复位。旧复位 id、旧许可序号、过期许可及运行许可下的请求均拒绝。
|
||||||
|
|
||||||
回执定向发回裁判端,并沿用请求字段;板端同时通过原血量通道广播四路真实血量。客户端逐板核对来源地址、会话、复位 id 和已发送序号,收到回执及其后的四路 100 血上报才完成重置,不根据回执伪造血量。部分成功或超时均保留结束阶段。来源与会话约束防止意外混用,不提供身份认证。旧装甲板忽略 type=9,必须更新固件才能远程复位;图传板无需更新。独立字节核对见 `python armor/scripts/test-probe.py`,探测器不发送复位。
|
回执定向发回裁判端,并沿用请求字段;板端同时通过原血量通道广播四路真实血量。客户端逐板核对来源地址、会话、复位 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 丢包和晚加入。接收回调只更新最多两路的内存收件箱,配置写盘在后台执行。
|
||||||
|
|
||||||
|
配置中 `cameraMirrors` 保存每路记录,旧配置缺失时回落到原有镜像默认值。尚未改动过的默认值不广播,避免新加入的客户端覆盖已配置记录。全局设置对当前槽位批量应用,裁判画面下方按钮只修改所在一路。演示预览不收发真实同步消息。需要双方更新客户端,固件无需更新;广播仍受网卡、防火墙和局域网可达性影响,该消息不提供身份认证。
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"version": "0.5.0",
|
"version": "0.6.0",
|
||||||
"major": 0,
|
"major": 0,
|
||||||
"minor": 5,
|
"minor": 6,
|
||||||
"patch": 0,
|
"patch": 0,
|
||||||
"build": 46,
|
"build": 47,
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"date": "2026-10-31",
|
"date": "2026-11-01",
|
||||||
"baseline": "v0.5.0",
|
"baseline": "v0.6.0",
|
||||||
"commits": 0,
|
"commits": 0,
|
||||||
"groups": {}
|
"groups": {}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,14 @@
|
|||||||
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
|
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
|
||||||
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
|
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
|
||||||
|
|
||||||
|
## v0.6.0 — 2026-11-01
|
||||||
|
|
||||||
|
1 个提交
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **client** · 同步每路镜像并精简操控入口与 HUD 映射
|
||||||
|
|
||||||
## v0.5.0 — 2026-10-31
|
## v0.5.0 — 2026-10-31
|
||||||
|
|
||||||
1 个提交
|
1 个提交
|
||||||
|
|||||||
+5
-5
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"version": "0.5.0",
|
"version": "0.6.0",
|
||||||
"major": 0,
|
"major": 0,
|
||||||
"minor": 5,
|
"minor": 6,
|
||||||
"patch": 0,
|
"patch": 0,
|
||||||
"build": 46,
|
"build": 47,
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"date": "2026-10-31",
|
"date": "2026-11-01",
|
||||||
"baseline": "v0.5.0",
|
"baseline": "v0.6.0",
|
||||||
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
|
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
|
||||||
}
|
}
|
||||||
@@ -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,6 +47,8 @@
|
|||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||||
|
mod camera_mirror;
|
||||||
|
pub use camera_mirror::CameraMirror;
|
||||||
|
|
||||||
mod match_state;
|
mod match_state;
|
||||||
pub use match_state::MatchState;
|
pub use match_state::MatchState;
|
||||||
@@ -136,6 +138,7 @@ pub enum MsgType {
|
|||||||
MatchResult = 10,
|
MatchResult = 10,
|
||||||
/// 选手端定向发送给已绑定装甲板的四轴速度与发射状态。
|
/// 选手端定向发送给已绑定装甲板的四轴速度与发射状态。
|
||||||
OperatorControl = 11,
|
OperatorControl = 11,
|
||||||
|
CameraMirror = 12,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MsgType {
|
impl MsgType {
|
||||||
@@ -153,6 +156,7 @@ impl MsgType {
|
|||||||
9 => MsgType::ArmorReset,
|
9 => MsgType::ArmorReset,
|
||||||
10 => MsgType::MatchResult,
|
10 => MsgType::MatchResult,
|
||||||
11 => MsgType::OperatorControl,
|
11 => MsgType::OperatorControl,
|
||||||
|
12 => MsgType::CameraMirror,
|
||||||
_ => return None,
|
_ => return None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ MSG_ARMOR_DAMAGE_CONTROL = 8
|
|||||||
MSG_ARMOR_RESET = 9
|
MSG_ARMOR_RESET = 9
|
||||||
MSG_MATCH_RESULT = 10
|
MSG_MATCH_RESULT = 10
|
||||||
MSG_OPERATOR_CONTROL = 11
|
MSG_OPERATOR_CONTROL = 11
|
||||||
|
MSG_CAMERA_MIRROR = 12
|
||||||
|
|
||||||
TYPE_NAMES = {
|
TYPE_NAMES = {
|
||||||
MSG_VIDEO: "video",
|
MSG_VIDEO: "video",
|
||||||
@@ -53,6 +54,7 @@ TYPE_NAMES = {
|
|||||||
MSG_ARMOR_RESET: "armor-reset",
|
MSG_ARMOR_RESET: "armor-reset",
|
||||||
MSG_MATCH_RESULT: "match-result",
|
MSG_MATCH_RESULT: "match-result",
|
||||||
MSG_OPERATOR_CONTROL: "operator-control",
|
MSG_OPERATOR_CONTROL: "operator-control",
|
||||||
|
MSG_CAMERA_MIRROR: "camera-mirror",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user