feat(receiver): 持久化接收机发现端点并支持位置备注信息
@@ -16,6 +16,7 @@ host/
|
||||
|
||||
# Runtime map cache and user-supplied offline tiles
|
||||
/maps/
|
||||
/map_cache/
|
||||
/receiver-config.json
|
||||
/config.json
|
||||
/.build.lock
|
||||
|
||||
@@ -58,6 +58,18 @@ dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-lock"
|
||||
version = "3.4.2"
|
||||
@@ -218,6 +230,12 @@ version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -230,6 +248,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -535,6 +562,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -722,9 +750,11 @@ dependencies = [
|
||||
name = "fpv-rid-registry"
|
||||
version = "3.0.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"find-msvc-tools",
|
||||
"fs2",
|
||||
"futures-util",
|
||||
"image",
|
||||
@@ -1774,6 +1804,17 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
@@ -1972,7 +2013,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1982,9 +2023,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
@@ -2691,6 +2738,12 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
|
||||
@@ -12,6 +12,18 @@ members = ["crates/rid-shared", "crates/realtime-core", "crates/web-ui", "crates
|
||||
default-members = [".", "crates/rid-shared", "crates/realtime-core", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[features]
|
||||
portable = [
|
||||
"dep:tempfile",
|
||||
"windows-sys/Win32_System_Com_StructuredStorage",
|
||||
"windows-sys/Win32_System_Console",
|
||||
"windows-sys/Win32_System_LibraryLoader",
|
||||
"windows-sys/Win32_System_SystemInformation",
|
||||
"windows-sys/Win32_System_Variant",
|
||||
"windows-sys/Win32_UI_Shell_PropertiesSystem",
|
||||
"windows-sys/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8", features = ["ws"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "sync", "time", "io-util"] }
|
||||
@@ -31,10 +43,15 @@ fs2 = "0.4"
|
||||
regex = "1"
|
||||
reqwest = { version = "=0.13.5", default-features = false, features = ["native-tls", "query", "system-proxy"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
argon2 = "0.5.3"
|
||||
tempfile = { version = "3", optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_System_Registry"] }
|
||||
|
||||
[target.'cfg(windows)'.build-dependencies]
|
||||
find-msvc-tools = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
|
||||
tempfile = "3"
|
||||
|
||||
@@ -6,7 +6,7 @@ FPV-RID 本地备案登记站,Rust + Axum + SQLite。对应 GitHub 仓库:`z
|
||||
|
||||
## Rust 启动与验证
|
||||
|
||||
- 发布目录:双击 `启动Rust版.cmd`,打开 http://127.0.0.1:8787/ ,无需 Node.js。
|
||||
- 发布目录:双击 `fpv-rid-registry.exe` 或 `启动Rust版.cmd`,默认浏览器打开 http://127.0.0.1:8787/workbench/ ,无需 Node.js。首次运行请创建本地管理员。
|
||||
- 本机现有终端先执行 `. ./scripts/rust-env.ps1`,加载集中工具目录。
|
||||
- 首次构建前端:`cargo xtask web`;开发运行:`cargo run -p fpv-rid-registry -- --data-root .`。
|
||||
- 统一发布:`cargo xtask package`,先构建前端与 Worker,再内嵌资源并生成 Release 发布包。
|
||||
@@ -54,12 +54,14 @@ FPV-RID 本地备案登记站,Rust + Axum + SQLite。对应 GitHub 仓库:`z
|
||||
- 改本地接口和档案卡:`src/http.rs`、`src/archive.rs`;数据库逻辑在 `src/store.rs`。
|
||||
- 接入无人机监管平台:先看 `doc/realtime/platform/api/receiver-transports.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。
|
||||
|
||||
当前服务仅监听 `127.0.0.1`,没有登录认证。要让局域网内的其他电脑读取档案,应由 RID 平台后端做受控同步接口,不能直接把这个本地服务改成对全网开放。
|
||||
当前服务仅监听 `127.0.0.1`。工作台、设备登记、档案管理与数据接口需要登录,现有二维码档案卡和查询入口保留原访问方式。登录数据库是数据目录下的 `registry/data/workbench-auth.sqlite`,独立于登记和轨迹数据库,更新时一并保留。账号经浏览器首次创建,密码以 Argon2 哈希保存,重启后需要重新登录。
|
||||
|
||||
历史轨迹从实时工作台左侧“历史轨迹”进入,可按目标和时间查询并回放。仅保存可信位置,连续轨迹通常每目标每秒采样一次;定位丢失、来源切换或超时会分段。轨迹单独保存在数据目录的 `registry/data/track-history.sqlite`,不会自动删除;备份或迁移时应在程序安全退出后同时保留该文件。历史画面不代表实时位置。
|
||||
|
||||
## 实时目标工作台
|
||||
|
||||
登录后进入 BSRID 布局,使用现有 RID 接收器、地图、围栏和历史数据。顶部“设备登记”“本地档案”进入原页面,也可返回地图工作台。阶段一支持本机 USB/UDP/TCP 接收、围栏和告警查询处置、已有轨迹查询与回放;BLE、厂商设备网络写入、固件和排名等功能后续接入。
|
||||
|
||||
打开 http://127.0.0.1:8787/realtime 使用已选择的 C 方案(目标研判)。当前提供天地图在线代理、自动离线回退、GPU 批量目标、选择和有限轨迹;离线支持 XYZ 栅格瓦片与 MBTiles,但未附带实际地图数据,已具备 USB/UDP/TCP 传输接入,厂商 RID 解析待报文确认。正常运行不自动生成模拟目标。
|
||||
|
||||
协议与隔离仿真步骤见 [实时通道 v1](doc/realtime/platform/api/synthetic-protocol.md)。实施范围及验证边界见 [实施记录](doc/realtime/platform/review/implementation-status.md)。
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn collect(root: &Path, folder: &Path, output: &mut String) {
|
||||
fn collect(root: &Path, folder: &Path, url_prefix: &str, output: &mut String) {
|
||||
let mut files: Vec<_> = fs::read_dir(folder)
|
||||
.expect("frontend assets")
|
||||
.map(|f| f.unwrap().path())
|
||||
@@ -15,7 +15,7 @@ fn collect(root: &Path, folder: &Path, output: &mut String) {
|
||||
}
|
||||
assert!(!path.is_symlink(), "frontend assets must not be symlinks");
|
||||
if path.is_dir() {
|
||||
collect(root, &path, output);
|
||||
collect(root, &path, url_prefix, output);
|
||||
continue;
|
||||
}
|
||||
let relative = path
|
||||
@@ -29,32 +29,93 @@ fn collect(root: &Path, folder: &Path, output: &mut String) {
|
||||
"wasm" => "application/wasm",
|
||||
"css" => "text/css; charset=utf-8",
|
||||
"png" => "image/png",
|
||||
"ico" => "image/x-icon",
|
||||
"svg" => "image/svg+xml",
|
||||
"json" => "application/json",
|
||||
"wav" => "audio/wav",
|
||||
"txt" => "text/plain; charset=utf-8",
|
||||
_ => continue,
|
||||
};
|
||||
output.push_str(&format!(
|
||||
"{:?} => Some((include_bytes!({:?}), {:?})),\n",
|
||||
format!("/{relative}"),
|
||||
format!("{url_prefix}/{relative}"),
|
||||
path.to_string_lossy(),
|
||||
mime
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn embed_windows_icon(workbench: &Path, output: &Path) {
|
||||
if env::var("CARGO_CFG_TARGET_ENV").as_deref() != Ok("msvc") {
|
||||
return;
|
||||
}
|
||||
|
||||
let arch = env::var("CARGO_CFG_TARGET_ARCH").expect("Windows target architecture");
|
||||
let sdk = find_msvc_tools::find_windows_sdk(&arch).expect("Windows SDK required for RID icon");
|
||||
let compiler = sdk
|
||||
.path()
|
||||
.map(|path| path.join("rc.exe"))
|
||||
.find(|path| path.is_file())
|
||||
.expect("Windows SDK resource compiler (rc.exe)");
|
||||
|
||||
fs::copy(
|
||||
workbench.join("assets/rid-app.ico"),
|
||||
output.join("rid-app.ico"),
|
||||
)
|
||||
.expect("copy Windows application icon");
|
||||
fs::write(output.join("rid-app.rc"), "1 ICON \"rid-app.ico\"\r\n")
|
||||
.expect("write application icon resource script");
|
||||
let status = std::process::Command::new(compiler)
|
||||
.current_dir(output)
|
||||
.args(["/nologo", "/fo", "rid-app.res", "rid-app.rc"])
|
||||
.status()
|
||||
.expect("run Windows resource compiler");
|
||||
assert!(
|
||||
status.success(),
|
||||
"Windows application icon compilation failed"
|
||||
);
|
||||
println!(
|
||||
"cargo:rustc-link-arg-bin=fpv-rid-registry-fullstack={}",
|
||||
output.join("rid-app.res").display()
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("dist/web-ui");
|
||||
let project = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
let root = project.join("dist/web-ui");
|
||||
let workbench = project.join("crates/web-ui/workbench");
|
||||
let output_directory = PathBuf::from(env::var("OUT_DIR").unwrap());
|
||||
println!("cargo:rerun-if-changed={}", root.display());
|
||||
println!("cargo:rerun-if-changed={}", workbench.display());
|
||||
#[cfg(windows)]
|
||||
embed_windows_icon(&workbench, &output_directory);
|
||||
if env::var_os("CARGO_FEATURE_PORTABLE").is_some() {
|
||||
println!("cargo:rerun-if-env-changed=RID_MAP_DOWNLOADER");
|
||||
let downloader = PathBuf::from(
|
||||
env::var_os("RID_MAP_DOWNLOADER")
|
||||
.expect("Build the map downloader for the portable target"),
|
||||
);
|
||||
println!("cargo:rerun-if-changed={}", downloader.display());
|
||||
fs::copy(downloader, output_directory.join("rid-map-downloader.bin"))
|
||||
.expect("embed the map downloader");
|
||||
}
|
||||
assert!(
|
||||
root.join("index.html").is_file(),
|
||||
"Build Rust frontend first: cargo xtask web"
|
||||
);
|
||||
let mut output = r#"pub fn resource(path: &str) -> Option<(&'static [u8], &'static str)> { let path = if path == "/" || path == "/realtime" { "/index.html" } else { path }; match path {
|
||||
let mut output = r#"pub fn resource(path: &str) -> Option<(&'static [u8], &'static str)> { let path = match path { "/" | "/realtime" | "/workbench/module.html" => "/index.html", "/workbench" | "/workbench/" => "/workbench/login.html", _ => path }; match path {
|
||||
"#.to_owned();
|
||||
collect(&root, &root, &mut output);
|
||||
collect(&root, &root, "", &mut output);
|
||||
collect(&workbench, &workbench, "/workbench", &mut output);
|
||||
if env::var_os("CARGO_FEATURE_PORTABLE").is_some() {
|
||||
let license = project.join("scripts/map-downloader/LICENSE-upstream.txt");
|
||||
println!("cargo:rerun-if-changed={}", license.display());
|
||||
output.push_str(&format!(
|
||||
"\"/map-downloader-LICENSE.txt\" => Some((include_bytes!({:?}), \"text/plain; charset=utf-8\")),\n",
|
||||
license.to_string_lossy(),
|
||||
));
|
||||
}
|
||||
output.push_str("_ => None } }\n");
|
||||
fs::write(
|
||||
PathBuf::from(env::var("OUT_DIR").unwrap()).join("web_assets.rs"),
|
||||
output,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(output_directory.join("web_assets.rs"), output).unwrap();
|
||||
}
|
||||
|
||||
@@ -20,20 +20,37 @@ pub struct Store {
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
fn refresh(track: &mut Track) {
|
||||
const SOURCE_HOLD_MS: u64 = 4_000;
|
||||
|
||||
fn refresh(track: &mut Track, now_ms: u64) {
|
||||
let mut sources: Vec<_> = track.sources.values().cloned().collect();
|
||||
sources.sort_by(|a, b| {
|
||||
a.received_at_ms
|
||||
.cmp(&b.received_at_ms)
|
||||
.then_with(|| a.observation.receiver_id.cmp(&b.observation.receiver_id))
|
||||
});
|
||||
let selected = sources
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|s| s.observation.coordinates().is_some())
|
||||
let old = &track.target.observation;
|
||||
let primary = track.sources.get(&old.receiver_id);
|
||||
let fresh_primary = primary.filter(|s| {
|
||||
s.observation.coordinates().is_some()
|
||||
&& now_ms.saturating_sub(s.received_at_ms) < SOURCE_HOLD_MS
|
||||
});
|
||||
let selected = fresh_primary
|
||||
.or_else(|| {
|
||||
sources.iter().rev().find(|s| {
|
||||
s.observation.coordinates().is_some()
|
||||
&& now_ms.saturating_sub(s.received_at_ms) < SOURCE_HOLD_MS
|
||||
})
|
||||
})
|
||||
.or_else(|| primary.filter(|s| s.observation.coordinates().is_some()))
|
||||
.or_else(|| {
|
||||
sources
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|s| s.observation.coordinates().is_some())
|
||||
})
|
||||
.or_else(|| sources.last())
|
||||
.expect("nonempty source set");
|
||||
let old = &track.target.observation;
|
||||
if old.coordinates().is_some() != selected.observation.coordinates().is_some()
|
||||
|| old.receiver_id != selected.observation.receiver_id
|
||||
{
|
||||
@@ -74,7 +91,7 @@ impl Store {
|
||||
self.changes.push_back((self.metrics.sequence, id));
|
||||
}
|
||||
|
||||
/// Select the latest still-valid position, retaining independent source observations.
|
||||
/// Keep a healthy position source, retaining independent observations for failover.
|
||||
pub fn apply(&mut self, observation: Observation, now_ms: u64) -> bool {
|
||||
if !observation.validate() {
|
||||
self.metrics.rejected += 1;
|
||||
@@ -125,7 +142,7 @@ impl Store {
|
||||
track
|
||||
.sources
|
||||
.retain(|_, s| now_ms.saturating_sub(s.received_at_ms) < self.ttl_ms);
|
||||
refresh(track);
|
||||
refresh(track, now_ms);
|
||||
track.target.received_count = track.target.received_count.saturating_add(1);
|
||||
track.suppressed = false;
|
||||
if let Some(observer) = &self.observer {
|
||||
@@ -141,6 +158,22 @@ impl Store {
|
||||
self.tracks.get(id).map(|track| &track.target.observation)
|
||||
}
|
||||
|
||||
/// Withdraw an alias from the receiver that supplied the confirmed identity.
|
||||
pub fn remove_source(&mut self, id: &str, receiver_id: &str, now_ms: u64) {
|
||||
let Some(track) = self.tracks.get_mut(id) else {
|
||||
return;
|
||||
};
|
||||
if track.sources.remove(receiver_id).is_none() {
|
||||
return;
|
||||
}
|
||||
if track.sources.is_empty() {
|
||||
self.tracks.remove(id);
|
||||
} else {
|
||||
refresh(track, now_ms);
|
||||
}
|
||||
self.changed(id.to_owned());
|
||||
}
|
||||
|
||||
pub fn expire(&mut self, now_ms: u64) {
|
||||
let _ = self.expire_with_changes(now_ms);
|
||||
}
|
||||
@@ -191,7 +224,7 @@ impl Store {
|
||||
if track.sources.is_empty() {
|
||||
removed.push(id.clone());
|
||||
} else if track.sources.len() != count || track.suppressed {
|
||||
refresh(track);
|
||||
refresh(track, now_ms);
|
||||
track.suppressed = false;
|
||||
if let Some(observer) = &self.observer {
|
||||
observer(&track.target.observation, now_ms);
|
||||
@@ -291,7 +324,7 @@ mod tests {
|
||||
let frame = store.frame(None, 5);
|
||||
assert_eq!(frame.targets.len(), 1);
|
||||
assert_eq!(frame.targets[0].sources.len(), 2);
|
||||
assert_eq!(frame.targets[0].observation.receiver_id, "b");
|
||||
assert_eq!(frame.targets[0].observation.receiver_id, "a");
|
||||
let generation = frame.targets[0].position_generation;
|
||||
a.sequence = 2;
|
||||
a.longitude = None;
|
||||
@@ -321,6 +354,35 @@ mod tests {
|
||||
store.expire(45);
|
||||
assert!(store.frame(None, 45).targets.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lagging_receivers_do_not_replace_a_healthy_source_and_failover_is_sticky() {
|
||||
let mut store = Store::new(10, 100, 30_000, 1);
|
||||
let mut primary = sample("one-aircraft", 1);
|
||||
primary.receiver_id = "primary".into();
|
||||
let mut standby = primary.clone();
|
||||
standby.receiver_id = "standby".into();
|
||||
standby.longitude = Some(119.);
|
||||
assert!(store.apply(primary.clone(), 100));
|
||||
assert!(store.apply(standby.clone(), 200));
|
||||
primary.sequence += 1;
|
||||
primary.longitude = Some(120.01);
|
||||
assert!(store.apply(primary.clone(), 1_000));
|
||||
standby.sequence += 1;
|
||||
assert!(store.apply(standby.clone(), 1_500));
|
||||
let live = store.frame(None, 1_500);
|
||||
assert_eq!(live.targets.len(), 1);
|
||||
assert_eq!(live.targets[0].sources.len(), 2);
|
||||
assert_eq!(live.targets[0].observation, primary);
|
||||
let generation = live.targets[0].position_generation;
|
||||
standby.sequence += 1;
|
||||
assert!(store.apply(standby.clone(), 5_000));
|
||||
primary.sequence += 1;
|
||||
assert!(store.apply(primary, 5_100));
|
||||
let live = store.frame(None, 5_100);
|
||||
assert_eq!(live.targets[0].observation, standby);
|
||||
assert_eq!(live.targets[0].position_generation, generation + 1);
|
||||
}
|
||||
fn sample(id: &str, sequence: u64) -> Observation {
|
||||
Observation {
|
||||
target_id: id.into(),
|
||||
|
||||
@@ -118,6 +118,9 @@ pub struct DeviceTelemetry {
|
||||
pub geometric_altitude_m: Option<f64>,
|
||||
pub height_agl_m: Option<f64>,
|
||||
pub pilot_position: Option<[f64; 2]>,
|
||||
/// Server assessment captured when writing history; never trusted from receiver input.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub flight_status: Option<String>,
|
||||
pub utc_raw: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"><link data-trunk rel="copy-file" href="public/map-tile-buffer.js"><link data-trunk rel="copy-file" href="public/geofences.css"><link rel="stylesheet" href="/geofences.css"><link data-trunk rel="copy-file" href="public/geofence-map-adapter.js"><link data-trunk rel="copy-file" href="public/appearance.css"><link rel="stylesheet" href="/appearance.css"><link data-trunk rel="copy-file" href="public/receivers.css"><link rel="stylesheet" href="/receivers.css"><link data-trunk rel="copy-file" href="public/receivers.js"><script type="module" src="/receivers.js"></script><link data-trunk rel="copy-file" href="public/history.css"><link rel="stylesheet" href="/history.css"><link data-trunk rel="copy-file" href="public/history-map-adapter.js"></head><body></body></html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"><link data-trunk rel="copy-file" href="public/map-tile-buffer.js"><link data-trunk rel="copy-file" href="public/geofences.css"><link rel="stylesheet" href="/geofences.css"><link data-trunk rel="copy-file" href="public/geofence-map-adapter.js"><link data-trunk rel="copy-file" href="public/appearance.css"><link rel="stylesheet" href="/appearance.css"><link data-trunk rel="copy-file" href="public/receivers.css"><link rel="stylesheet" href="/receivers.css"><link data-trunk rel="copy-file" href="public/receivers.js"><script type="module" src="/receivers.js"></script><link data-trunk rel="copy-file" href="public/history.css"><link rel="stylesheet" href="/history.css"><link data-trunk rel="copy-file" href="public/history-map-adapter.js"><link rel="stylesheet" href="/workbench/embedded.css"><script type="module" src="/workbench/embedded.js"></script><link rel="stylesheet" href="/workbench/drone-marker.css"></head><body></body></html>
|
||||
|
||||
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 11 KiB |
@@ -3,7 +3,8 @@ import * as ml from './vendor/maplibre-gl.mjs';
|
||||
import {attachTileBuffer} from './map-tile-buffer.js';
|
||||
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
|
||||
let map,buffer,observer,marker,points=[],index=0,fitPending=false,kind='imagery';
|
||||
let map,buffer,observer,marker,points=[],projected=[],index=0,progress=0,fitPending=false,kind='imagery';
|
||||
let labels = true, registered, registrationGeneration = 0;
|
||||
const layers={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
|
||||
const url=i=>`/api/maps/tile/${layers[kind][i]}/{z}/{x}/{y}`;
|
||||
function coordinate(point){
|
||||
@@ -30,19 +31,70 @@ function paint(){
|
||||
fitPending=false;
|
||||
}
|
||||
}
|
||||
function paintMarker(){
|
||||
const position=coordinate(points[index]);
|
||||
if(!map||!position){marker?.remove();marker=null;return;}
|
||||
if(!marker)marker=new ml.Marker({color:'#82c5ff',anchor:'center'}).setLngLat(position).addTo(map);
|
||||
else marker.setLngLat(position);
|
||||
const angleDelta = (from, to) => ((to - from + 540) % 360) - 180;
|
||||
|
||||
function makeDroneMarker() {
|
||||
const element = window.ridDroneMap.createMarker(window.ridDroneMap.registrationColors(registered));
|
||||
return new ml.Marker({element, anchor:'center', rotationAlignment:'map', pitchAlignment:'map', subpixelPositioning:true});
|
||||
}
|
||||
|
||||
function pointAlongEdge(from, to, fraction) {
|
||||
const east = to.x - from.x;
|
||||
const dx = Math.abs(east) > 0.5 ? east - Math.sign(east) : east;
|
||||
return new ml.MercatorCoordinate(from.x + dx * fraction, from.y + (to.y - from.y) * fraction, 0)
|
||||
.toLngLat().toArray();
|
||||
}
|
||||
|
||||
function paintMarker() {
|
||||
const current = points[index];
|
||||
const from = coordinate(current);
|
||||
if (!map || !from) {
|
||||
marker?.remove();
|
||||
marker = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const next = points[index + 1];
|
||||
const to = !next?.segmentStart && next?.timeMs > current.timeMs ? coordinate(next) : null;
|
||||
const previous = !current.segmentStart ? coordinate(points[index - 1]) : null;
|
||||
const direction = (a, b) => window.ridDroneMap.trackHeading(a[1], a[0], b[1], b[0]);
|
||||
const course = to ? direction(from, to) : previous ? direction(previous, from) : undefined;
|
||||
const heading = Number.isFinite(current.headingDeg) ? current.headingDeg : course ?? 0;
|
||||
const destinationHeading = to && Number.isFinite(next.headingDeg) ? next.headingDeg : heading;
|
||||
const angle = heading + angleDelta(heading, destinationHeading) * progress;
|
||||
const position = to && progress > 0
|
||||
? pointAlongEdge(projected[index], projected[index + 1], progress)
|
||||
: from;
|
||||
|
||||
if (!marker) marker = makeDroneMarker().setLngLat(position).setRotation(angle).addTo(map);
|
||||
else {
|
||||
if (marker.getRotation() !== angle) marker.setRotation(angle);
|
||||
const previousPosition = marker.getLngLat();
|
||||
if (previousPosition.lng !== position[0] || previousPosition.lat !== position[1]) {
|
||||
marker.setLngLat(position);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function setMapOptions(options) {
|
||||
const next = options.basemap === 'road' ? 'road' : 'imagery';
|
||||
if (next !== kind) {
|
||||
kind = next;
|
||||
map?.getSource('base')?.setTiles([url(0)]);
|
||||
map?.getSource('labels')?.setTiles([url(1)]);
|
||||
buffer?.schedule();
|
||||
}
|
||||
labels = options.labels !== false;
|
||||
if (map?.getLayer('labels')) map.setLayoutProperty('labels', 'visibility', labels ? 'visible' : 'none');
|
||||
}
|
||||
|
||||
export function open(p){
|
||||
setMapOptions(p);
|
||||
if(map){map.resize();return;}
|
||||
kind=p.basemap==='road'?'road':'imagery';
|
||||
try{
|
||||
map=new ml.Map({container:'history-map',center:[p.longitude,p.latitude],zoom:p.zoom??15,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,attributionControl:false,
|
||||
style:{version:8,sources:{base:{type:'raster',tiles:[url(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[url(1)],tileSize:256,maxzoom:18}},
|
||||
layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'}]}});
|
||||
layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels',layout:{visibility:labels?'visible':'none'}}]}});
|
||||
buffer=attachTileBuffer(map,()=>kind);observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('history-map'));
|
||||
map.addControl(new ml.NavigationControl({showCompass:false}),'bottom-right');
|
||||
map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 历史轨迹',compact:true}),'bottom-right');
|
||||
@@ -51,7 +103,38 @@ export function open(p){
|
||||
map.on('error',e=>{if(!['base','labels'].includes(e.sourceId))window.dispatchEvent(new Event('rid-history-map-error'));});
|
||||
}catch{close();window.dispatchEvent(new Event('rid-history-map-error'));}
|
||||
}
|
||||
export function setPoints(value){points=Array.isArray(value)?value:[];index=0;fitPending=true;paint();}
|
||||
export function setIndex(value){index=Math.max(0,Math.min(points.length-1,Number(value)||0));paintMarker();}
|
||||
export function setPoints(value, target) {
|
||||
points = Array.isArray(value) ? value : [];
|
||||
registered = undefined;
|
||||
marker?.remove();
|
||||
marker = null;
|
||||
const generation = ++registrationGeneration;
|
||||
if (target && points.length) {
|
||||
fetch('/api/target-registration-status?' + new URLSearchParams({ids:target}), {cache:'no-store'})
|
||||
.then(response => response.ok ? response.json() : null).then(result => {
|
||||
if (generation !== registrationGeneration || !result?.entries?.length) return;
|
||||
registered = result.entries[0].registered;
|
||||
const element = marker?.getElement();
|
||||
if (element) {
|
||||
const {fill, glow} = window.ridDroneMap.registrationColors(registered);
|
||||
element.style.setProperty('--rid-drone-fill', fill);
|
||||
element.style.setProperty('--rid-drone-glow', glow);
|
||||
}
|
||||
}).catch(() => {});
|
||||
}
|
||||
projected = points.map(point => {
|
||||
const position = coordinate(point);
|
||||
return position ? ml.MercatorCoordinate.fromLngLat(position) : null;
|
||||
});
|
||||
index = 0;
|
||||
progress = 0;
|
||||
fitPending = true;
|
||||
paint();
|
||||
}
|
||||
export function setCursor(value, fraction) {
|
||||
index = Math.max(0, Math.min(points.length - 1, Number(value) || 0));
|
||||
progress = Math.max(0, Math.min(1, Number(fraction) || 0));
|
||||
paintMarker();
|
||||
}
|
||||
export function close(){buffer?.destroy();buffer=null;observer?.disconnect();observer=null;marker?.remove();marker=null;map?.remove();map=null;}
|
||||
export function metrics(){return {ready:!!map?.getSource('history-track'),points:points.length,index};}
|
||||
|
||||
@@ -30,3 +30,9 @@ body.b.theme-white .history-list button[aria-pressed=true]{background:#dcebf7;bo
|
||||
body.b.theme-white .history-warning{color:var(--mc-warning)!important}
|
||||
body.b.theme-white .history-divider{background:var(--work-line)}
|
||||
body.b.theme-white :is(.track-playback-controls button,.history-sidebar button,.history-sidebar input,.history-playback input):focus-visible{outline-color:var(--mc-accent)}
|
||||
|
||||
.history-query:not([hidden]){display:contents}
|
||||
.history-record-details{display:grid;gap:5px;margin:0;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}
|
||||
.history-record-details dt{color:var(--work-muted);font-size:12px}
|
||||
.history-record-details dd{margin:0 0 7px}
|
||||
.history-osd:not([hidden]){display:flex;flex-wrap:wrap;gap:6px 16px;padding:8px 0;line-height:1.5;font-size:12px;font-variant-numeric:tabular-nums}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Load the map engine only for the approved realtime workspace.
|
||||
import '/workbench/drone-map.js';
|
||||
|
||||
// A separate, lazy map keeps configuration independent of the live receiver map.
|
||||
let settings, generation=0;
|
||||
@@ -15,13 +16,67 @@ window.ridGeofences={
|
||||
close(){fenceGeneration++;fences?.close();},render(p){fences?.render(p);},targets(p){fences?.targets(p);},tool(v){fences?.tool(v);},locate(){fences?.locate();},setBasemap(v){fences?.setBasemap(v);},metrics(){return fences?.metrics();}
|
||||
};
|
||||
|
||||
let history,historyGeneration=0,historyPoints=[],historyIndex=0;
|
||||
window.ridHistory={
|
||||
async open(p){const token=++historyGeneration;try{history??=await import('./history-map-adapter.js');if(token===historyGeneration){history.open(p);history.setPoints(historyPoints);history.setIndex(historyIndex);}}catch{window.dispatchEvent(new Event('rid-history-map-error'));}},
|
||||
close(){historyGeneration++;history?.close();},
|
||||
setPoints(value){historyPoints=Array.isArray(value)?value:[];historyIndex=0;history?.setPoints(historyPoints);},
|
||||
setIndex(value){historyIndex=value;history?.setIndex(value);},
|
||||
metrics(){return history?.metrics();}
|
||||
let history, historyGeneration = 0, historyPoints = [], historyIndex = 0, historyProgress = 0;
|
||||
let historyTarget, historyMapOptions;
|
||||
let playbackFrame, playbackTimestamp, playbackGeneration = 0;
|
||||
document.addEventListener('visibilitychange', () => { playbackTimestamp = undefined; });
|
||||
function stopHistoryClock() {
|
||||
playbackGeneration += 1;
|
||||
if (playbackFrame !== undefined) cancelAnimationFrame(playbackFrame);
|
||||
playbackFrame = undefined;
|
||||
playbackTimestamp = undefined;
|
||||
}
|
||||
window.ridHistory = {
|
||||
async open(p) {
|
||||
const token = ++historyGeneration;
|
||||
try {
|
||||
history ??= await import('./history-map-adapter.js');
|
||||
if (token === historyGeneration) {
|
||||
history.open({...p, ...historyMapOptions});
|
||||
history.setPoints(historyPoints, historyTarget);
|
||||
history.setCursor(historyIndex, historyProgress);
|
||||
}
|
||||
} catch {
|
||||
window.dispatchEvent(new Event('rid-history-map-error'));
|
||||
}
|
||||
},
|
||||
close() {
|
||||
historyGeneration += 1;
|
||||
stopHistoryClock();
|
||||
history?.close();
|
||||
},
|
||||
prepareTrack(value) { return window.ridDroneMap.prepareTrack(value); },
|
||||
setPoints(value, target) {
|
||||
historyPoints = Array.isArray(value) ? value : [];
|
||||
historyTarget = target;
|
||||
historyIndex = 0;
|
||||
historyProgress = 0;
|
||||
history?.setPoints(historyPoints, historyTarget);
|
||||
},
|
||||
setMapOptions(value) {
|
||||
historyMapOptions = value;
|
||||
if (value) history?.setMapOptions(value);
|
||||
},
|
||||
setCursor(index, progress) {
|
||||
historyIndex = index;
|
||||
historyProgress = progress;
|
||||
history?.setCursor(index, progress);
|
||||
},
|
||||
startClock(tick) {
|
||||
stopHistoryClock();
|
||||
const token = playbackGeneration;
|
||||
function frame(timestamp) {
|
||||
if (token !== playbackGeneration) return;
|
||||
const elapsed = playbackTimestamp === undefined ? 0 : Math.max(0, timestamp - playbackTimestamp);
|
||||
playbackTimestamp = timestamp;
|
||||
if (tick(elapsed) && token === playbackGeneration) {
|
||||
playbackFrame = requestAnimationFrame(frame);
|
||||
}
|
||||
}
|
||||
playbackFrame = requestAnimationFrame(frame);
|
||||
},
|
||||
stopClock: stopHistoryClock,
|
||||
metrics() { return history?.metrics(); }
|
||||
};
|
||||
|
||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
.rx-page{display:flex;flex-direction:column;box-sizing:border-box}
|
||||
.rx-surface{flex:1;min-height:calc(100dvh - 280px);padding:20px;border:1px solid var(--work-line,#bdd8ff22);border-radius:16px;background:color-mix(in srgb,var(--work-panel,#1a2a3bc9) 72%,transparent);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}
|
||||
.rx-surface .rx-cards{align-items:start}
|
||||
.rx-surface>.rx-footnote{margin-bottom:0}
|
||||
@media(max-width:650px){.rx-surface{padding:16px;min-height:360px}}
|
||||
|
||||
/* Compact receiver toolbar and single-screen connection form. */
|
||||
@@ -45,12 +44,6 @@
|
||||
.rx-page .rx-card .rx-actions button{background:color-mix(in srgb,var(--work-text) 8%,var(--glass-solid,#102235))}
|
||||
|
||||
/* Equal-height cards: seven fixed rows, so extra notices cannot change the height. */
|
||||
.rx-legend{display:flex;flex-wrap:wrap;gap:6px 14px;margin:0 0 12px;color:var(--work-muted,#9eb3c8);font-size:12px;line-height:1.4}
|
||||
.rx-legend span{display:inline-flex;align-items:center;min-width:0}
|
||||
.rx-dot{width:8px;height:8px;margin-right:5px;border-radius:99px;background:var(--work-muted,#9eb3c8);flex:none}
|
||||
.rx-dot.ok{background:var(--mc-success,#81d8af)}
|
||||
.rx-dot.info{background:var(--mc-accent,#8bbdff)}
|
||||
.rx-dot.warn{background:var(--mc-warning,#ffd08a)}
|
||||
.rx-cards{grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}
|
||||
.rx-card{display:grid;grid-template-rows:22px 16px 24px 20px 22px auto auto;gap:6px;align-content:start;padding:14px;border-left-width:3px;overflow:hidden}
|
||||
.rx-card>*{min-width:0;min-height:0}
|
||||
@@ -91,6 +84,3 @@
|
||||
.theme-white .rx-card.rx-warn{border-left-color:#875013}
|
||||
.theme-white .rx-pill.rx-info{color:#286299;background:#28629916}
|
||||
.theme-white .rx-card.rx-info{border-left-color:#286299}
|
||||
.theme-white .rx-dot.ok{background:#236647}
|
||||
.theme-white .rx-dot.warn{background:#875013}
|
||||
.theme-white .rx-dot.info{background:#286299}
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
// Device management is a view of server-owned receiver tasks, never their lifecycle owner.
|
||||
const $ = id => document.getElementById(id);
|
||||
let rows = [], selected = null, busy = false, pending = false, dirty = false, initialized = false;
|
||||
const defaults = {enabled:false,transport:'serial',format:'raw',uidIdentity:'source-scoped',serialPort:'',baudRate:115200,bindIp:'127.0.0.1',port:8788};
|
||||
const protocols = {'raw':'原始诊断','uid-json':'UID JSON','rid-device-json':'RID / uav','json-lines':'约定 JSON','postcard':'Postcard'};
|
||||
const pageSize = 8;
|
||||
let page = 0;
|
||||
const defaults = {enabled:false,transport:'serial',uidIdentity:'source-scoped',serialPort:'',baudRate:115200,bindIp:'127.0.0.1',port:8788,peerIp:''};
|
||||
const receiverFormat = format => !format || format === 'raw' ? 'rid-device-json' : format;
|
||||
function state(row) {
|
||||
const s=row.status||{};
|
||||
if(!row.config?.enabled)return !row.detector&&row.deviceKind?'其他串口 · 未当作侦测机':'未启用';
|
||||
if(s.state==='disconnected')return '连接失败 · 自动重试';
|
||||
if(s.state==='disconnected')return row.config.transport==='tcp-listen'?'监听失败 · 自动重试':'连接失败 · 自动重试';
|
||||
if(s.state==='connecting'||s.state==='stopped')return '正在连接';
|
||||
if(s.notice)return s.notice;
|
||||
if(!s.receivedBytes)return row.detector?'侦测串口已连接 · 还没有数据':'已连接 · 等待数据';
|
||||
if(s.state==='tcp-listening'&&(!s.lastDataMs||Date.now()-s.lastDataMs>15000))return '监听中 · 等待数据';
|
||||
if(!s.receivedBytes)return '已连接 · 等待数据';
|
||||
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return '连接中 · 暂无新数据';
|
||||
if(row.config.format==='raw')return '接收中 · 原始诊断';
|
||||
if(s.rejectedFrames&&!s.decodedFrames)return '收到数据 · 协议不匹配';
|
||||
if(!s.acceptedObservations)return '正在接收 · 暂无有效目标';
|
||||
if(!s.acceptedObservations)return s.heartbeatFrames?'正在接收 · 已收到设备心跳':'正在接收 · 暂无有效目标';
|
||||
return '正在接收 · 已解析目标';
|
||||
}
|
||||
const GB_NOTE='这台设备收到了报文,但帧头不符合它自己的 GB46750 要求,所以不会生成目标。';
|
||||
@@ -30,11 +33,15 @@ function tone(row){
|
||||
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return 'info';
|
||||
if(row.config.format==='raw')return 'ok';
|
||||
if(s.rejectedFrames&&!s.decodedFrames)return 'warn';
|
||||
if(!s.acceptedObservations)return 'info';
|
||||
if(!s.acceptedObservations)return s.heartbeatFrames?'ok':'info';
|
||||
return 'ok';
|
||||
}
|
||||
function cardStatus(row){return row.config?.enabled?state(row):'未启用';}
|
||||
function roleLabel(row){if(row.config.transport!=='serial')return '网络';if(row.detector)return '侦测机';if(row.deviceKind)return '其他串口';return '接收机';}
|
||||
function roleLabel(row){
|
||||
if(row.config.transport!=='serial')return '网络';
|
||||
if(row.status?.lastValidFrameMs != null)return '侦测机';
|
||||
return row.config.serialPort ? 'USB 串口' : '接收机';
|
||||
}
|
||||
function identity(row){
|
||||
const name=row.name||'未命名接收机',socket=row.devicePlace||'';
|
||||
if(socket&&(name===socket||name.endsWith(` · ${socket}`))){
|
||||
@@ -46,7 +53,7 @@ function identity(row){
|
||||
return {head:row.deviceKind,place:socket||rest||'—'};
|
||||
}
|
||||
if(socket)return {head:name,place:socket};
|
||||
if(row.config.transport!=='serial')return {head:name,place:'网络 · 手动添加'};
|
||||
if(row.config.transport!=='serial')return {head:name,place:row.networkDiscovered?'网络 · 自动登记':'网络 · 手动添加'};
|
||||
const cut=name.indexOf(' · ');
|
||||
return cut<0?{head:name,place:'—'}:{head:name.slice(0,cut),place:name.slice(cut+3)};
|
||||
}
|
||||
@@ -86,9 +93,16 @@ function render(){
|
||||
const focused=document.activeElement?.dataset.rxFocus;
|
||||
const query=$('rx-search').value.trim().toLowerCase();
|
||||
const list=rows.filter(r=>`${r.name} ${r.deviceKind||''} ${r.devicePlace||''} ${r.id} ${r.hardwareId||''} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
|
||||
const watching=rows.filter(r=>r.detector&&r.config.enabled).length;
|
||||
$('rx-summary').textContent=`${rows.length} 个串口 · ${watching} 台侦测机已启用`;
|
||||
$('rx-cards').replaceChildren(...list.map(row=>{
|
||||
const pageCount = Math.max(1, Math.ceil(list.length / pageSize));
|
||||
page = Math.min(page, pageCount - 1);
|
||||
const displayed = list.slice(page * pageSize, (page + 1) * pageSize);
|
||||
$('rx-page-summary').textContent = `共 ${list.length} 台 · 每页 ${pageSize} 台`;
|
||||
$('rx-page-number').textContent = `第 ${page + 1} / ${pageCount} 页`;
|
||||
$('rx-page-prev').disabled = page === 0;
|
||||
$('rx-page-next').disabled = page + 1 >= pageCount;
|
||||
const watching=rows.filter(r=>r.config.enabled).length;
|
||||
$('rx-summary').textContent=`${rows.length} 台接收器 · ${watching} 台已启用`;
|
||||
$('rx-cards').replaceChildren(...displayed.map(row=>{
|
||||
const idn=identity(row),toneName=tone(row),lines=faults(row);
|
||||
const c=el('article',undefined,`rx-card rx-${toneName}`);
|
||||
const title=el('h2',idn.head);title.title=row.name||idn.head;
|
||||
@@ -96,32 +110,49 @@ function render(){
|
||||
const pills=el('div',undefined,'rx-pills'),statusText=cardStatus(row);
|
||||
const status=el('span',statusText,`rx-pill rx-${toneName}`);status.title=statusText;
|
||||
pills.append(status,el('span',roleLabel(row),'rx-pill rx-role'));
|
||||
const meta=el('p',undefined,'rx-meta'),portText=endpoint(row),protocolText=protocols[row.config.format]||row.config.format;
|
||||
const port=el('span',portText);port.title=portText;meta.append(port,el('span',protocolText,'rx-protocol'));
|
||||
const meta=el('p',undefined,'rx-meta'),portText=endpoint(row);
|
||||
const port=el('span',portText);port.title=portText;meta.append(port);
|
||||
const alert=el('div',undefined,lines.length?'rx-alert':'rx-alert quiet');
|
||||
const alertText=el('span',lines.length?lines[0]:'—','rx-alert-text');alertText.title=lines.length?lines[0]:'没有额外提示';alert.append(alertText);
|
||||
if(lines.length>1){const more=el('button',`另 ${lines.length-1} 条`,'rx-more');more.type='button';more.dataset.rxFocus=row.id+'-alerts';more.dataset.rxAlerts=row.id;more.setAttribute('aria-label',`另 ${lines.length-1} 条提示`);more.onclick=event=>{event.stopPropagation();if(popFor===row.id&&!$('rx-pop').hidden)closePop();else openPop(row,more);};alert.append(more);}
|
||||
const metrics=el('div',undefined,'rx-metrics');for(const [label,value] of [['接收字节',row.status?.receivedBytes||0],['接受更新',row.status?.acceptedObservations||0]]){const m=el('div');m.append(el('strong',Number(value).toLocaleString()),el('span',label));metrics.append(m);}
|
||||
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');manage.type='button';toggle.type='button';manage.dataset.rxFocus=row.id+'-manage';toggle.dataset.rxFocus=row.id+'-toggle';manage.onclick=()=>open(row);toggle.disabled=busy;toggle.onclick=async()=>{await mutate(async()=>{await api(`/api/receivers/${row.id}`,'PUT',{name:row.name,config:{...row.config,enabled:!row.config.enabled}});});};actions.append(manage,toggle);c.append(title,place,pills,meta,alert,metrics,actions);return c;
|
||||
}));$('rx-empty').hidden=!!list.length;syncPop(list);
|
||||
const metrics = el('div', undefined, 'rx-metrics');
|
||||
const s = row.status || {};
|
||||
for (const [label, value] of [['接收字节', s.receivedBytes], ['有效目标更新', s.acceptedObservations]]) {
|
||||
const metric = el('div');
|
||||
metric.append(el('strong', Number(value ?? 0).toLocaleString()), el('span', label));
|
||||
metrics.append(metric);
|
||||
}
|
||||
const last = el('p', `最近接收 ${s.lastDataMs ? new Date(s.lastDataMs).toLocaleTimeString() : '—'}`, 'rx-place');
|
||||
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');manage.type='button';toggle.type='button';manage.dataset.rxFocus=row.id+'-manage';toggle.dataset.rxFocus=row.id+'-toggle';manage.onclick=()=>open(row);toggle.disabled=busy;toggle.onclick=async()=>{await mutate(async()=>{const config={...row.config,enabled:!row.config.enabled};if(config.enabled)config.format=receiverFormat(config.format);await api(`/api/receivers/${row.id}`,'PUT',{name:row.name,config});});};actions.append(manage,toggle);c.append(title,place,pills,meta,alert,metrics,last,actions);return c;
|
||||
}));$('rx-empty').hidden=!!list.length;syncPop(displayed);
|
||||
if(focused){for(const button of $('rx-cards').querySelectorAll('button')){if(button.dataset.rxFocus===focused){button.focus({preventScroll:true});break;}}}
|
||||
if(selected)diagnostics();
|
||||
}
|
||||
async function refresh(){if(pending||!$('rx-cards'))return;pending=true;try{const v=await api('/api/receivers');rows=v.receivers||[];$('rx-error').textContent=v.error||'';$('rx-error').hidden=!v.error;render();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;}finally{pending=false;}}
|
||||
async function mutate(action){if(busy)return;busy=true;render();try{await action();await refresh();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;if($('rx-drawer').open)$('rx-message').textContent=e.message;}finally{busy=false;render();}}
|
||||
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-uid-fields').hidden=f.elements.format.value!=='uid-json';$('rx-protocol-note').textContent=f.elements.format.value==='uid-json'?'UID 报文中的坐标系代码尚未核实:选中目标可查看原始位置,不参与围栏。':f.elements.format.value==='raw'?'原始诊断只接收字节,不生成无人机目标。':'协议必须与设备实际输出一致;未知报文不会猜测为位置。';}
|
||||
function selectedFormat() { return receiverFormat(rows.find(row => row.id === selected)?.config.format); }
|
||||
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-peer-fields').hidden=f.elements.transport.value!=='tcp-listen';$('rx-uid-fields').hidden=selectedFormat()!=='uid-json';}
|
||||
function tab(diagnostic){$('rx-form').hidden=diagnostic;$('rx-diagnostic').hidden=!diagnostic;$('rx-config-tab').setAttribute('aria-pressed',String(!diagnostic));$('rx-diagnostic-tab').setAttribute('aria-pressed',String(diagnostic));diagnostics();}
|
||||
function diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['设备种类',row.deviceKind||'—'],['插口位置',row.devicePlace||'—'],['设备 ID',row.hardwareId||row.id],['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无'],...(s.notice?[['帧头提示',s.notice]]:[])]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
||||
function open(row){closePop();selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config={...defaults,...row?.config};f.elements.name.value=row?.name||'';for(const [key,value] of Object.entries(config)){if(key==='enabled')f.elements[key].checked=value;else f.elements[key].value=value;}$('rx-delete').hidden=!selected||selected==='default';fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
|
||||
function diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['设备种类',row.deviceKind||'—'],['插口位置',row.devicePlace||'—'],['设备 ID',row.hardwareId||row.id],['来源 IP',s.lastPeerIp||'—'],['心跳帧',s.heartbeatFrames ?? 0],['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无'],...(s.notice?[['帧头提示',s.notice]]:[])]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
||||
function open(row){closePop();selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config={...defaults,...row?.config};f.elements.name.value=row?.name||'';for(const key of Object.keys(defaults)){if(key==='enabled')f.elements[key].checked=config[key];else f.elements[key].value=config[key] ?? '';}$('rx-delete').hidden=!selected;fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
|
||||
function close(){if(dirty&&!confirm('尚有未保存的配置,放弃修改并关闭?'))return;$('rx-drawer').close();selected=null;dirty=false;}
|
||||
function init(){if(initialized||!$('rx-cards'))return;initialized=true;$('rx-add').onclick=()=>open(null);$('rx-refresh').onclick=refresh;$('rx-search').oninput=render;$('rx-close').onclick=close;$('rx-drawer').addEventListener('cancel',e=>{e.preventDefault();close();});$('rx-form').oninput=()=>{dirty=true;fields();};$('rx-form').onchange=()=>{dirty=true;fields();};$('rx-config-tab').onclick=()=>tab(false);$('rx-diagnostic-tab').onclick=()=>tab(true);
|
||||
$('rx-form').onsubmit=async e=>{e.preventDefault();if(busy)return;const f=e.target,config={};for(const key of Object.keys(defaults))config[key]=key==='enabled'?f.elements[key].checked:['baudRate','port'].includes(key)?Number(f.elements[key].value):f.elements[key].value;await mutate(async()=>{const v=await api(selected?`/api/receivers/${selected}`:'/api/receivers',selected?'PUT':'POST',{name:f.elements.name.value,config});selected=v.receiver.id;dirty=false;$('rx-message').textContent='配置已保存。接收状态以实时诊断为准。';$('rx-title').textContent=v.receiver.name;$('rx-delete').hidden=selected==='default';});};
|
||||
$('rx-delete').onclick=()=>{if(!selected||!confirm('删除此接收机配置并停止该接收任务?其他接收机不受影响。'))return;mutate(async()=>{await api(`/api/receivers/${selected}`,'DELETE');dirty=false;close();});};
|
||||
$('rx-capture').onclick=async()=>{if(!selected)return;try{const v=await api(`/api/receivers/${selected}/capture`);const bytes=Uint8Array.from((v.data.match(/[0-9a-f]{2}/ig)||[]).map(x=>parseInt(x,16)));$('rx-raw').textContent=`UTF-8(损坏字节以替代符显示)\n${new TextDecoder().decode(bytes)}\n\nHEX\n${v.data||'尚无数据'}`;}catch(e){$('rx-message').textContent=e.message;}};
|
||||
function init(){if(initialized||!$('rx-cards'))return;initialized=true;$('rx-add').onclick=()=>open(null);$('rx-refresh').onclick=refresh;$('rx-close').onclick=close;$('rx-drawer').addEventListener('cancel',e=>{e.preventDefault();close();});$('rx-form').oninput=()=>{dirty=true;fields();};$('rx-form').onchange=()=>{dirty=true;fields();};$('rx-config-tab').onclick=()=>tab(false);$('rx-diagnostic-tab').onclick=()=>tab(true);
|
||||
$('rx-search').oninput = () => { page = 0; render(); };
|
||||
for (const [id, step] of [['rx-page-prev', -1], ['rx-page-next', 1]]) {
|
||||
const button = $(id);
|
||||
button.onclick = () => {
|
||||
page += step;
|
||||
render();
|
||||
if (button.disabled) $('rx-page-number').focus();
|
||||
};
|
||||
}
|
||||
$('rx-form').onsubmit=async e=>{e.preventDefault();if(busy)return;const f=e.target,config={format:selectedFormat()};for(const key of Object.keys(defaults))config[key]=key==='enabled'?f.elements[key].checked:['baudRate','port'].includes(key)?Number(f.elements[key].value):f.elements[key].value;config.peerIp=config.transport==='tcp-listen'?(config.peerIp.trim()||null):null;await mutate(async()=>{const v=await api(selected?`/api/receivers/${selected}`:'/api/receivers',selected?'PUT':'POST',{name:f.elements.name.value,config});selected=v.receiver.id;dirty=false;$('rx-message').textContent='配置已保存。接收状态以实时诊断为准。';$('rx-title').textContent=v.receiver.name;$('rx-delete').hidden=false;});};
|
||||
$('rx-delete').onclick=()=>{if(!selected||!confirm('删除此接收机配置?正常运行的 RID TCP 入口会继续接收,有效数据会触发重新登记。'))return;mutate(async()=>{await api(`/api/receivers/${selected}`,'DELETE');dirty=false;close();});};
|
||||
$('rx-capture').onclick=async()=>{if(!selected)return;try{const v=await api(`/api/receivers/${selected}/capture`);const bytes=Uint8Array.from((v.data.match(/[0-9a-f]{2}/ig)||[]).map(x=>parseInt(x,16)));const identities=(v.identitySamples||[]).map(sample=>`${sample.targetId} · ${sample.peerIp||sample.receiverId} · ${new Date(sample.receivedAtMs).toLocaleString()}\n协议 ${sample.format} · serial=${sample.telemetry?.serial||'—'} · ssid=${sample.telemetry?.ssid||'—'} · MAC=${sample.telemetry?.mac||'—'}\n${sample.raw}${sample.truncated?'\n(报文已截断)':''}`).join('\n\n');$('rx-raw').textContent=`UTF-8(损坏字节以替代符显示)\n${new TextDecoder().decode(bytes)}\n\nHEX\n${v.data||'尚无数据'}${identities?'\n\n本次接收的目标来源(最近 64 个身份的首帧)\n'+identities:''}`;}catch(e){$('rx-message').textContent=e.message;}};
|
||||
document.addEventListener('click',event=>{if(!popFor||event.target.closest('#rx-pop, [data-rx-alerts]'))return;closePop();});
|
||||
document.addEventListener('keydown',event=>{if(event.key==='Escape')closePop();});
|
||||
const movePop=()=>{if(!popFor)return;const anchor=document.querySelector(`[data-rx-alerts="${CSS.escape(popFor)}"]`);if(anchor)placePop(anchor);};
|
||||
window.addEventListener('resize',movePop);document.addEventListener('scroll',movePop,true);
|
||||
refresh();setInterval(()=>{if(document.body.dataset.screen==='receivers')refresh();},1500);
|
||||
refresh();setInterval(()=>{if(!document.hidden && $('rx-cards')?.getClientRects().length)refresh();},1000);
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
.registry-workspace #search-count{display:block;color:var(--work-muted);font-size:12px}.registry-workspace #search-count:empty{display:none}
|
||||
.registry-workspace #new-registration{margin:0;width:100%;min-height:42px}
|
||||
.registry-workspace .history-toolbar{display:flex;justify-content:space-between;gap:10px;align-items:center}
|
||||
.registry-workspace .archiveTools{display:flex;flex-direction:column;gap:12px}
|
||||
.registry-workspace #selection-toggle,.registry-workspace #export-toggle{font-size:12px;padding:7px 11px;min-height:34px}
|
||||
.registry-workspace .select-all{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--work-muted)}
|
||||
.registry-workspace .history-message,.registry-workspace .history-empty,.registry-workspace .archive-warning{margin:0;color:var(--work-muted);font-size:12px;line-height:1.8;overflow-wrap:anywhere}
|
||||
|
||||
@@ -5,9 +5,9 @@ use leptos::prelude::*;
|
||||
use serde_json::Value;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -28,6 +28,31 @@ struct State {
|
||||
speed: RwSignal<u32>,
|
||||
busy: RwSignal<bool>,
|
||||
status: RwSignal<String>,
|
||||
record: RwSignal<Option<ReplayRecord>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ReplayRecord {
|
||||
flight_key: String,
|
||||
target_id: String,
|
||||
start_ms: u64,
|
||||
end_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl ReplayRecord {
|
||||
fn from_event(event: &web_sys::CustomEvent) -> Option<Self> {
|
||||
let value: Value = serde_json::from_str(&event.detail().as_string()?).ok()?;
|
||||
let flight_key = value["flightKey"].as_str()?;
|
||||
if flight_key.len() != 32 || !flight_key.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
flight_key: flight_key.to_owned(),
|
||||
target_id: value["targetId"].as_str()?.to_owned(),
|
||||
start_ms: value["timeMs"].as_u64()?,
|
||||
end_ms: value["endMs"].as_u64(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
@@ -47,14 +72,40 @@ fn map_call(method: &str, args: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
function.apply(&api, &array)
|
||||
}
|
||||
|
||||
fn send_points(points: &[Value]) {
|
||||
fn send_points(points: &[Value], target: Option<&str>) {
|
||||
if let Ok(text) = serde_json::to_string(points)
|
||||
&& let Ok(value) = js_sys::JSON::parse(&text)
|
||||
{
|
||||
let _ = map_call("setPoints", &[value]);
|
||||
let _ = map_call(
|
||||
"setPoints",
|
||||
&[
|
||||
value,
|
||||
target.map(JsValue::from_str).unwrap_or(JsValue::UNDEFINED),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_points(points: &[Value]) -> Result<(Vec<Value>, u64, u64), String> {
|
||||
let invalid = || "无法处理轨迹数据".to_owned();
|
||||
let text = serde_json::to_string(points).map_err(|_| invalid())?;
|
||||
let samples = js_sys::JSON::parse(&text).map_err(|_| invalid())?;
|
||||
let prepared = map_call("prepareTrack", &[samples]).map_err(|_| invalid())?;
|
||||
let text: String = js_sys::JSON::stringify(&prepared)
|
||||
.map_err(|_| invalid())?
|
||||
.into();
|
||||
let mut value: Value = serde_json::from_str(&text).map_err(|_| invalid())?;
|
||||
let points = value["points"]
|
||||
.as_array_mut()
|
||||
.map(std::mem::take)
|
||||
.ok_or_else(invalid)?;
|
||||
Ok((
|
||||
points,
|
||||
value["skipped"].as_u64().unwrap_or(0),
|
||||
value["newSegments"].as_u64().unwrap_or(0),
|
||||
))
|
||||
}
|
||||
|
||||
fn visible() -> bool {
|
||||
web_sys::window()
|
||||
.and_then(|w| w.document())
|
||||
@@ -171,7 +222,7 @@ fn list(state: State, requests: Requests, append: bool) {
|
||||
state.index.set(0);
|
||||
state.next_offset.set(None);
|
||||
requests.points.fetch_add(1, Ordering::Relaxed);
|
||||
send_points(&[]);
|
||||
send_points(&[], None);
|
||||
(from, to, query, 0)
|
||||
};
|
||||
let generation = requests.targets.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
@@ -214,7 +265,7 @@ fn list(state: State, requests: Requests, append: bool) {
|
||||
});
|
||||
}
|
||||
|
||||
fn load_points(state: State, requests: Requests, id: String) {
|
||||
fn load_points(state: State, requests: Requests, id: String, flight_key: Option<String>) {
|
||||
let (from, to) = state.range.get_untracked();
|
||||
let generation = requests.points.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
state.selected.set(id.clone());
|
||||
@@ -223,15 +274,20 @@ fn load_points(state: State, requests: Requests, id: String) {
|
||||
state.playing.set(false);
|
||||
state.busy.set(true);
|
||||
state.status.set("正在读取轨迹…".into());
|
||||
send_points(&[]);
|
||||
send_points(&[], None);
|
||||
spawn_local(async move {
|
||||
let mut all = Vec::new();
|
||||
let mut after = 0u64;
|
||||
let result = loop {
|
||||
let url = format!(
|
||||
"/api/history/points?targetId={}&fromMs={from}&toMs={to}&limit=5000&after={after}",
|
||||
js_sys::encode_uri_component(&id)
|
||||
);
|
||||
let url = match &flight_key {
|
||||
Some(key) => {
|
||||
format!("/api/history/flight-points?flightKey={key}&limit=5000&after={after}")
|
||||
}
|
||||
None => format!(
|
||||
"/api/history/points?targetId={}&fromMs={from}&toMs={to}&limit=5000&after={after}",
|
||||
js_sys::encode_uri_component(&id)
|
||||
),
|
||||
};
|
||||
let value = match fetch(&url).await {
|
||||
Ok(value) => value,
|
||||
Err(error) => break Err(error),
|
||||
@@ -256,18 +312,27 @@ fn load_points(state: State, requests: Requests, id: String) {
|
||||
return;
|
||||
}
|
||||
state.busy.set(false);
|
||||
match result {
|
||||
Ok(()) => {
|
||||
if let Some(time) = all.first().and_then(|p| p["timeMs"].as_u64()) {
|
||||
match result.and_then(|()| prepare_points(&all)) {
|
||||
Ok((points, skipped, new_segments)) => {
|
||||
if let Some(time) = points.first().and_then(|p| p["timeMs"].as_u64()) {
|
||||
state.play_time.set(time as f64);
|
||||
}
|
||||
send_points(&all);
|
||||
let count = all.len();
|
||||
state.points.set(all);
|
||||
send_points(&points, Some(&id));
|
||||
let count = points.len();
|
||||
state.points.set(points);
|
||||
state
|
||||
.playing
|
||||
.set(flight_key.is_some() && count > 1 && visible());
|
||||
state.status.set(if count == 0 {
|
||||
"该时段没有轨迹点。".into()
|
||||
if flight_key.is_some() {
|
||||
"这条记录暂无有效定位,当前无法回放。".into()
|
||||
} else {
|
||||
"该时段没有轨迹点。".into()
|
||||
}
|
||||
} else if skipped > 0 || new_segments > 0 {
|
||||
format!("已加载 {count} 个采样点。已略过 {skipped} 个异常点,另有 {new_segments} 处采样间隔或定位跳变已断开。")
|
||||
} else {
|
||||
format!("已加载 {count} 个采样点;位置丢失和接收来源切换处会断开轨迹。")
|
||||
format!("已加载 {count} 个采样点。定位中断和接收来源切换处会断开轨迹。")
|
||||
});
|
||||
}
|
||||
Err(error) => state.status.set(error),
|
||||
@@ -275,6 +340,79 @@ fn load_points(state: State, requests: Requests, id: String) {
|
||||
});
|
||||
}
|
||||
|
||||
fn playback_number(value: &Value, precision: usize, unit: &str) -> String {
|
||||
value
|
||||
.as_f64()
|
||||
.map(|number| format!("{number:.precision$} {unit}"))
|
||||
.unwrap_or_else(|| "—".into())
|
||||
}
|
||||
|
||||
fn point_progress(points: &[Value], index: usize, time: f64) -> f64 {
|
||||
let Some(from) = points.get(index).and_then(|point| point["timeMs"].as_f64()) else {
|
||||
return 0.0;
|
||||
};
|
||||
match points
|
||||
.get(index + 1)
|
||||
.and_then(|point| point["timeMs"].as_f64())
|
||||
{
|
||||
Some(to) if to > from => ((time - from) / (to - from)).clamp(0.0, 1.0),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn advance_playback(state: State, elapsed: f64) -> bool {
|
||||
let current = state.index.get_untracked();
|
||||
let next = state.play_time.get_untracked() + elapsed * f64::from(state.speed.get_untracked());
|
||||
let (index, time, finished) = state.points.with_untracked(|points| {
|
||||
let Some(last) = points.last() else {
|
||||
return (0, 0.0, true);
|
||||
};
|
||||
let mut index = current.min(points.len() - 1);
|
||||
let mut time = next;
|
||||
while let Some(following) = points.get(index + 1) {
|
||||
let current_time = points[index]["timeMs"].as_f64().unwrap_or(time);
|
||||
let following_time = following["timeMs"].as_f64().unwrap_or(current_time);
|
||||
if following_time < current_time {
|
||||
// A wall-clock change begins a new playback segment.
|
||||
time = following_time;
|
||||
} else if following_time > time {
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
let end = last["timeMs"].as_f64().unwrap_or(time);
|
||||
let finished = index + 1 == points.len() && time >= end;
|
||||
(index, if finished { end } else { time }, finished)
|
||||
});
|
||||
state.play_time.set(time);
|
||||
if index != current {
|
||||
state.index.set(index);
|
||||
}
|
||||
if finished {
|
||||
state.playing.set(false);
|
||||
}
|
||||
!finished
|
||||
}
|
||||
|
||||
fn seek_playback(state: State, value: f64) {
|
||||
state.playing.set(false);
|
||||
let (index, time) = state.points.with_untracked(|points| {
|
||||
let value = value.clamp(0.0, points.len().saturating_sub(1) as f64);
|
||||
let index = value.floor() as usize;
|
||||
let from = points
|
||||
.get(index)
|
||||
.and_then(|point| point["timeMs"].as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let to = points
|
||||
.get(index + 1)
|
||||
.and_then(|point| point["timeMs"].as_f64())
|
||||
.unwrap_or(from);
|
||||
(index, from + (to - from).max(0.0) * value.fract())
|
||||
});
|
||||
state.index.set(index);
|
||||
state.play_time.set(time);
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn History() -> impl IntoView {
|
||||
let now = js_sys::Date::now();
|
||||
@@ -295,70 +433,43 @@ pub fn History() -> impl IntoView {
|
||||
speed: RwSignal::new(1),
|
||||
busy: RwSignal::new(false),
|
||||
status: RwSignal::new(String::new()),
|
||||
record: RwSignal::new(None),
|
||||
};
|
||||
let requests = Requests::default();
|
||||
list(state, requests.clone(), false);
|
||||
Effect::new(move |_| {
|
||||
let _ = map_call("setIndex", &[JsValue::from_f64(state.index.get() as f64)]);
|
||||
let cursor = Memo::new(move |_| {
|
||||
let index = state.index.get();
|
||||
let time = state.play_time.get();
|
||||
let progress = state
|
||||
.points
|
||||
.with(|points| point_progress(points, index, time));
|
||||
(index, progress)
|
||||
});
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let end = stopped.clone();
|
||||
on_cleanup(move || end.store(true, Ordering::Relaxed));
|
||||
spawn_local(async move {
|
||||
let mut last = None;
|
||||
while !stopped.load(Ordering::Relaxed) {
|
||||
TimeoutFuture::new(200).await;
|
||||
if stopped.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if !visible() {
|
||||
state.playing.set(false);
|
||||
last = None;
|
||||
continue;
|
||||
}
|
||||
if !state.playing.get_untracked() {
|
||||
last = None;
|
||||
continue;
|
||||
}
|
||||
let now = js_sys::Date::now();
|
||||
let elapsed = last
|
||||
.map(|previous: f64| (now - previous).max(0.0))
|
||||
.unwrap_or(0.0);
|
||||
last = Some(now);
|
||||
let next =
|
||||
state.play_time.get_untracked() + elapsed * f64::from(state.speed.get_untracked());
|
||||
let (index, time, finished) = state.points.with_untracked(|points| {
|
||||
if points.is_empty() {
|
||||
return (0, 0.0, true);
|
||||
}
|
||||
let mut index = state.index.get_untracked().min(points.len() - 1);
|
||||
let mut time = next;
|
||||
while index + 1 < points.len() {
|
||||
let current = points[index]["timeMs"].as_f64().unwrap_or(time);
|
||||
let following = points[index + 1]["timeMs"].as_f64().unwrap_or(current);
|
||||
if following < current {
|
||||
// A wall-clock adjustment starts a new segment.
|
||||
index += 1;
|
||||
time = following;
|
||||
} else if following <= time {
|
||||
index += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = points
|
||||
.last()
|
||||
.and_then(|p| p["timeMs"].as_f64())
|
||||
.unwrap_or(time);
|
||||
let finished = index + 1 == points.len() && time >= end;
|
||||
(index, if finished { end } else { time }, finished)
|
||||
});
|
||||
state.play_time.set(time);
|
||||
state.index.set(index);
|
||||
if finished {
|
||||
state.playing.set(false);
|
||||
}
|
||||
Effect::new(move |_| {
|
||||
let (index, progress) = cursor.get();
|
||||
let _ = map_call(
|
||||
"setCursor",
|
||||
&[JsValue::from_f64(index as f64), JsValue::from_f64(progress)],
|
||||
);
|
||||
});
|
||||
Effect::new(move |_| {
|
||||
if !state.playing.get() {
|
||||
let _ = map_call("stopClock", &[]);
|
||||
return;
|
||||
}
|
||||
let frame = Closure::<dyn FnMut(f64) -> bool>::new(move |elapsed: f64| {
|
||||
if !visible() || !state.playing.get_untracked() {
|
||||
state.playing.set(false);
|
||||
return false;
|
||||
}
|
||||
advance_playback(state, elapsed)
|
||||
});
|
||||
if map_call("startClock", &[frame.into_js_value()]).is_err() {
|
||||
state.playing.set(false);
|
||||
}
|
||||
});
|
||||
on_cleanup(|| {
|
||||
let _ = map_call("stopClock", &[]);
|
||||
});
|
||||
let error = window_event_listener(
|
||||
leptos::ev::Custom::new("rid-history-map-error"),
|
||||
@@ -373,19 +484,81 @@ pub fn History() -> impl IntoView {
|
||||
let view = window_event_listener(
|
||||
leptos::ev::Custom::new("rid-workspace-view"),
|
||||
move |_: web_sys::Event| {
|
||||
if visible() && state.auto_range.get_untracked() {
|
||||
if !visible() {
|
||||
if state.playing.get_untracked() {
|
||||
state.playing.set(false);
|
||||
}
|
||||
if state.record.get_untracked().is_some() {
|
||||
view_requests.points.fetch_add(1, Ordering::Relaxed);
|
||||
state.record.set(None);
|
||||
state.selected.set(String::new());
|
||||
state.points.set(vec![]);
|
||||
state.busy.set(false);
|
||||
send_points(&[], None);
|
||||
}
|
||||
} else if state.auto_range.get_untracked() && state.record.get_untracked().is_none() {
|
||||
list(state, view_requests.clone(), false);
|
||||
}
|
||||
},
|
||||
);
|
||||
on_cleanup(move || view.remove());
|
||||
let record_requests = requests.clone();
|
||||
let record_event = window_event_listener(
|
||||
leptos::ev::Custom::new("rid-history-record"),
|
||||
move |event: web_sys::Event| {
|
||||
if !visible() {
|
||||
return;
|
||||
}
|
||||
let record = event
|
||||
.dyn_into::<web_sys::CustomEvent>()
|
||||
.ok()
|
||||
.as_ref()
|
||||
.and_then(ReplayRecord::from_event);
|
||||
if let Some(record) = record {
|
||||
record_requests.targets.fetch_add(1, Ordering::Relaxed);
|
||||
state.record.set(Some(record.clone()));
|
||||
load_points(
|
||||
state,
|
||||
record_requests.clone(),
|
||||
record.target_id,
|
||||
Some(record.flight_key),
|
||||
);
|
||||
if let Some(heading) = web_sys::window()
|
||||
.and_then(|w| w.document())
|
||||
.and_then(|document| document.get_element_by_id("history-playback-title"))
|
||||
.and_then(|element| element.dyn_into::<web_sys::HtmlElement>().ok())
|
||||
{
|
||||
let _ = heading.focus();
|
||||
}
|
||||
} else if state.record.get_untracked().is_some() {
|
||||
state.record.set(None);
|
||||
list(state, record_requests.clone(), false);
|
||||
}
|
||||
},
|
||||
);
|
||||
on_cleanup(move || record_event.remove());
|
||||
let search_requests = requests.clone();
|
||||
let more_requests = requests.clone();
|
||||
let target_requests = requests.clone();
|
||||
view! {
|
||||
<div class="history-workspace">
|
||||
<aside class="history-sidebar" aria-label="历史轨迹查询">
|
||||
<h1>"历史轨迹"</h1><p>"按目标和时间范围查找已保存的位置。"</p>
|
||||
<h1 id="history-playback-title" tabindex="-1">{move||if state.record.with(Option::is_some){"轨迹回放"}else{"历史轨迹"}}</h1>
|
||||
<Show when=move||state.record.with(Option::is_some)>
|
||||
<button type="button" on:click=move |_|{
|
||||
if let Some(window)=web_sys::window()
|
||||
&& let Ok(event)=web_sys::Event::new("rid-history-return-records") {
|
||||
let _ = window.dispatch_event(&event);
|
||||
}
|
||||
}>"返回记录查询"</button>
|
||||
<dl class="history-record-details">
|
||||
<dt>"UAS ID"</dt><dd>{move||state.record.with(|r|r.as_ref().map(|r|r.target_id.clone()).unwrap_or_default())}</dd>
|
||||
<dt>"开始时间"</dt><dd>{move||state.record.with(|r|r.as_ref().map(|r|display_time(r.start_ms)).unwrap_or_default())}</dd>
|
||||
<dt>"结束时间"</dt><dd>{move||state.record.with(|r|r.as_ref().and_then(|r|r.end_ms).map(display_time).unwrap_or_else(||"接收中".into()))}</dd>
|
||||
</dl>
|
||||
</Show>
|
||||
<div class="history-query" hidden=move||state.record.with(Option::is_some)>
|
||||
<p>"按目标和时间范围查找已保存的位置。"</p>
|
||||
<label>"目标标识"<input type="search" placeholder="搜索目标标识" prop:value=move||state.query.get() on:input=move|e|state.query.set(event_target_value(&e))/></label>
|
||||
<label>"开始时间"<input type="datetime-local" step="1" prop:value=move||state.from.get() on:input=move|e|{state.auto_range.set(false);state.from.set(event_target_value(&e));}/></label>
|
||||
<label>"结束时间"<input type="datetime-local" step="1" prop:value=move||state.to.get() on:input=move|e|{state.auto_range.set(false);state.to.set(event_target_value(&e));}/></label>
|
||||
@@ -398,14 +571,15 @@ pub fn History() -> impl IntoView {
|
||||
let first=entry["firstMs"].as_u64().map(display_time).unwrap_or_default();
|
||||
let last=entry["lastMs"].as_u64().map(display_time).unwrap_or_default();
|
||||
let count=entry["pointCount"].as_u64().unwrap_or(0);
|
||||
view!{<button type="button" disabled=move||state.busy.get() aria-pressed=move||(state.selected.get()==selected_id).to_string() on:click=move |_|load_points(state,requests.clone(),request_id.clone())><strong>{id}</strong><small>{format!("{first} — {last}")}</small><small>{format!("{count} 个采样点")}</small></button>}
|
||||
view!{<button type="button" disabled=move||state.busy.get() aria-pressed=move||(state.selected.get()==selected_id).to_string() on:click=move |_|load_points(state,requests.clone(),request_id.clone(),None)><strong>{id}</strong><small>{format!("{first} — {last}")}</small><small>{format!("{count} 个采样点")}</small></button>}
|
||||
}/>
|
||||
</div>
|
||||
<button hidden=move||state.next_offset.get().is_none() disabled=move||state.busy.get() on:click=move |_|list(state,more_requests.clone(),true)>"加载更多目标"</button>
|
||||
</div>
|
||||
<p class="history-status" role="status">{move||state.status.get()}</p>
|
||||
</aside>
|
||||
<section class="history-main" aria-label="轨迹地图与回放">
|
||||
<div class="history-map-shell"><div id="history-map" aria-label="历史轨迹地图"></div><span class="history-map-banner">{move||if state.selected.get().is_empty(){"历史轨迹".into()}else{format!("{} · 历史轨迹",state.selected.get())}}</span><div class="history-map-empty" hidden=move||!state.points.get().is_empty()>"选择目标后显示历史轨迹"</div></div>
|
||||
<div class="history-map-shell"><div id="history-map" aria-label="历史轨迹地图"></div><span class="history-map-banner">{move||if state.selected.get().is_empty(){"历史轨迹".into()}else{format!("{} · 历史轨迹",state.selected.get())}}</span><div class="history-map-empty" hidden=move||!state.points.get().is_empty()>{move||if state.busy.get(){"正在读取轨迹…"}else if state.record.with(Option::is_some){"暂无可显示的轨迹点"}else{"选择目标后显示历史轨迹"}}</div></div>
|
||||
<div class="track-playback-controls">
|
||||
<div class="track-playback-controls-head"><h2>"回放控制"</h2><span class="history-space"></span><p class="history-warning">"历史画面,不代表实时位置;未核实坐标不记录。"</p></div>
|
||||
<div class="history-playback">
|
||||
@@ -416,13 +590,49 @@ pub fn History() -> impl IntoView {
|
||||
state.playing.update(|v| *v = !*v);
|
||||
}>{move||if state.playing.get(){"暂停"}else{"播放"}}</button>
|
||||
<span class="history-time">{move||state.points.with(|p|p.get(state.index.get()).and_then(|p|p["timeMs"].as_u64()).map(display_time).unwrap_or_else(||"—".into()))}</span>
|
||||
<input type="range" min="0" max=move||state.points.with(|p|p.len().saturating_sub(1).to_string()) prop:value=move||state.index.get().to_string() disabled=move||state.points.with(Vec::is_empty) aria-label="回放进度" on:input=move|e|{
|
||||
let index=event_target_value(&e).parse::<usize>().unwrap_or(0);
|
||||
state.playing.set(false);state.index.set(index);
|
||||
if let Some(t)=state.points.with_untracked(|p|p.get(index).and_then(|p|p["timeMs"].as_f64())){state.play_time.set(t);}
|
||||
<input type="range" min="0" step="0.01" max=move||state.points.with(|p|p.len().saturating_sub(1).to_string()) prop:value=move||{
|
||||
let (index, progress)=cursor.get();
|
||||
format!("{:.2}",index as f64 + progress)
|
||||
} disabled=move||state.points.with(Vec::is_empty) aria-label="回放进度" on:input=move|e|{
|
||||
if let Ok(value)=event_target_value(&e).parse::<f64>() && value.is_finite() {
|
||||
seek_playback(state, value);
|
||||
}
|
||||
}/>
|
||||
<button on:click=move |_|state.speed.update(|v|*v=match *v{1=>4,4=>16,16=>64,_=>1}) aria-label="切换回放速度">{move||format!("{}×",state.speed.get())}</button>
|
||||
</div>
|
||||
<div class="history-osd" hidden=move||state.points.with(Vec::is_empty) aria-label="轨迹点 OSD">
|
||||
{move||state.points.with(|points| points.get(state.index.get()).map(|point| {
|
||||
let osd = &point["osd"];
|
||||
let mut heights = [
|
||||
("椭球高", &point["altitudeM"]),
|
||||
("几何高度", &osd["geometricAltitudeM"]),
|
||||
("气压高度", &osd["pressureAltitudeM"]),
|
||||
(if osd["relativeHeightM"].is_number() {"离地高度"} else {"相对高度"}, &osd["heightAglM"]),
|
||||
("相对高度", &osd["relativeHeightM"]),
|
||||
].into_iter()
|
||||
.filter(|(_, value)| value.is_number())
|
||||
.map(|(label, value)| format!("{label} {}", playback_number(value, 1, "m")))
|
||||
.collect::<Vec<_>>();
|
||||
if heights.is_empty() { heights.push("高度 未记录".into()); }
|
||||
let position = match (point["latitude"].as_f64(), point["longitude"].as_f64()) {
|
||||
(Some(lat), Some(lon)) => format!("{lat:.6}, {lon:.6}"),
|
||||
_ => "—".into(),
|
||||
};
|
||||
let pilot = osd["pilotPosition"].as_array().and_then(|coords| {
|
||||
let [lon, lat] = coords.as_slice() else { return None };
|
||||
Some(format!("{:.6}, {:.6}", lat.as_f64()?, lon.as_f64()?))
|
||||
});
|
||||
view! {
|
||||
<span>"坐标 "{position}</span>
|
||||
{heights.into_iter().map(|height|view!{<span>{height}</span>}).collect::<Vec<_>>()}
|
||||
<span>"速度 "{playback_number(&osd["speedMps"], 1, "m/s")}</span>
|
||||
<span>"升降速度 "{playback_number(&osd["verticalSpeedMps"], 1, "m/s")}</span>
|
||||
<span>"航向 "{playback_number(&point["headingDeg"], 0, "°")}</span>
|
||||
<span>"RSSI "{playback_number(&osd["rssi"], 0, "dBm")}</span>
|
||||
{pilot.map(|position|view!{<span>"飞手坐标 "{position}</span>})}
|
||||
}
|
||||
}))}
|
||||
</div>
|
||||
<p>"每个目标通常每秒保存一个点;数据仅保存在本机,不自动删除。"</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -10,17 +10,20 @@ mod target_lists;
|
||||
mod workspace;
|
||||
|
||||
fn main() {
|
||||
let realtime = web_sys::window()
|
||||
let path = web_sys::window()
|
||||
.unwrap()
|
||||
.location()
|
||||
.pathname()
|
||||
.unwrap_or_default()
|
||||
== "/realtime";
|
||||
.unwrap_or_default();
|
||||
let embedded = path == "/workbench/module.html";
|
||||
let realtime = path == "/realtime";
|
||||
mount_to_body(move || {
|
||||
let lists = target_lists::Lists::new();
|
||||
view! {
|
||||
<div inner_html=include_str!("workspace.html")/>
|
||||
<section id="geofence-view" class="workspace-pane" tabindex="-1" aria-label="电子围栏" hidden inner_html=include_str!("geofences.html")/>
|
||||
{(!embedded).then(|| view!{
|
||||
<div inner_html=include_str!("workspace.html")/>
|
||||
<section id="geofence-view" class="workspace-pane" tabindex="-1" aria-label="电子围栏" hidden inner_html=include_str!("geofences.html")/>
|
||||
})}
|
||||
<section id="map-settings-view" class="workspace-pane" tabindex="-1" aria-label="地图配置" hidden inner_html=include_str!("map_settings.html")/>
|
||||
<section id="target-lists-view" class="workspace-pane" tabindex="-1" aria-label="黑白名单管理" hidden><target_lists::Manager lists=lists/></section>
|
||||
<section id="receivers-view" class="workspace-pane" tabindex="-1" aria-label="设备管理" hidden inner_html=include_str!("receivers.html")/>
|
||||
@@ -32,8 +35,12 @@ fn main() {
|
||||
}
|
||||
});
|
||||
map_settings::init();
|
||||
geofences::init();
|
||||
workspace::init(realtime);
|
||||
if embedded {
|
||||
workspace::init_embedded();
|
||||
} else {
|
||||
geofences::init();
|
||||
workspace::init(realtime);
|
||||
}
|
||||
if !realtime {
|
||||
registry::init();
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<div class="map-settings-scroll">
|
||||
<section id="map-step-region" tabindex="-1" aria-label="选择区域"><h3 class="map-section-title">选择下载区域</h3><p class="map-settings-small">先确定范围,再设置图层与精度。</p><label class="map-settings-label">常用区域<select id="map-region"><option value="">选择已保存的区域…</option></select></label><button class="map-current" data-map-action="box">在地图上框选范围</button><p id="map-bounds-summary" class="map-range-summary">尚未选择范围</p><details class="map-advanced"><summary>精确坐标与常用区域管理</summary><div class="map-settings-fields"><label class="map-settings-label">西侧经度<input id="map-west" type="number" min="-180" max="180" step="0.000001"></label><label class="map-settings-label">南侧纬度<input id="map-south" type="number" min="-85.051128" max="85.051128" step="0.000001"></label><label class="map-settings-label">东侧经度<input id="map-east" type="number" min="-180" max="180" step="0.000001"></label><label class="map-settings-label">北侧纬度<input id="map-north" type="number" min="-85.051128" max="85.051128" step="0.000001"></label></div><label class="map-settings-label">常用区域名称<input id="map-region-name" maxlength="40" placeholder="填写区域名称"></label><div class="map-settings-actions"><button data-map-action="region-save">加入常用</button><button data-map-action="region-delete">移除所选</button></div><button id="map-region-persist" data-map-action="save-regions" disabled>保存区域更改</button><div id="map-region-message" class="map-settings-message" role="status" aria-live="polite">区域编辑后需保存到本机。</div></details></section>
|
||||
<section id="map-step-layers" tabindex="-1" aria-label="图层与精度" hidden><h3 class="map-section-title">图层与精度</h3><p class="map-settings-small">层级越高,细节越丰富,下载量也越大。</p><div class="map-settings-fields"><label class="map-settings-label">起始层级<input id="map-min-zoom" type="number" min="0" max="18" value="10"></label><label class="map-settings-label">结束层级<input id="map-max-zoom" type="number" min="0" max="18" value="14"></label></div><div class="map-layer-choices"><label><input type="checkbox" id="map-download-road" checked> 路网与标注</label><label><input type="checkbox" id="map-download-imagery" checked> 影像与标注</label></div><p class="map-settings-small">单次最多 20000 张瓦片,核算成功后才能开始下载。</p></section>
|
||||
<section id="map-step-review" tabindex="-1" aria-label="核算与下载" hidden><h3 class="map-section-title">确认下载任务</h3><p id="map-download-summary" class="map-range-summary"></p><p class="map-settings-small" id="map-estimate-message">尚未核算。</p><button id="map-estimate" data-map-action="estimate">重新核算</button><progress id="map-download-progress" value="0" max="1" aria-label="离线地图下载进度"></progress><p class="map-settings-small">仅手动开始下载。已完成瓦片可复用;失败或取消不视为完整离线包,实际大小以下载结果为准。</p></section>
|
||||
<section id="map-step-review" tabindex="-1" aria-label="核算与下载" hidden><h3 class="map-section-title">确认下载任务</h3><p id="map-download-summary" class="map-range-summary"></p><p class="map-settings-small" id="map-estimate-message">尚未核算。</p><button id="map-estimate" data-map-action="estimate">重新核算</button><progress id="map-download-progress" value="0" max="1" aria-label="离线地图下载进度"></progress><p class="map-settings-small">瓦片保存到数据目录下的 <code>map_cache</code>。将该文件夹放在 EXE 旁,程序启动后会自动读取。失败或取消后可重试,已完成的瓦片会复用。</p></section>
|
||||
</div>
|
||||
<footer class="map-panel-footer"><div id="map-step-message" class="map-settings-message" role="status" aria-live="polite"></div><div id="map-download-message" class="map-settings-message" role="status" aria-live="polite">暂无下载任务</div><div class="map-footer-actions"><button id="map-step-back" data-map-action="previous" hidden>上一步</button><button id="map-step-next" class="primary" data-map-action="next">下一步</button><button class="primary" id="map-download-start" data-map-action="start" disabled hidden>开始下载</button><button id="map-download-cancel" data-map-action="cancel" disabled hidden>取消任务</button></div></footer>
|
||||
</section>
|
||||
|
||||
@@ -322,13 +322,13 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
continue;
|
||||
}
|
||||
let target = entry["target_id"].as_str().unwrap_or("");
|
||||
let message = if entry["event_type"] == "blacklist" {
|
||||
format!("黑名单命中:{target}")
|
||||
} else {
|
||||
format!(
|
||||
let message = match entry["event_type"].as_str() {
|
||||
Some("blacklist") => format!("黑名单命中:{target}"),
|
||||
Some("unregistered") => format!("未登记无人机:{target}"),
|
||||
_ => format!(
|
||||
"围栏进入:{target} · {}",
|
||||
entry["fence_name"].as_str().unwrap_or("")
|
||||
)
|
||||
),
|
||||
};
|
||||
log_event_at(events, message, entry["occurred_at_ms"].as_u64());
|
||||
cursor = cursor.max(id);
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
<div class="rx-toolbar"><label>查找设备 <input id="rx-search" type="search" placeholder="名称、串口或接收机 ID"></label><span id="rx-summary" role="status">正在加载接收机…</span><button class="primary" id="rx-add">+ 添加接收机</button><button id="rx-refresh">刷新</button></div>
|
||||
<section class="rx-surface" aria-label="接收机列表区域">
|
||||
<p id="rx-error" class="rx-error" role="alert" hidden></p>
|
||||
<p class="rx-legend"><span><i class="rx-dot ok" aria-hidden="true"></i>正在接收</span><span><i class="rx-dot info" aria-hidden="true"></i>连接中或等待</span><span><i class="rx-dot warn" aria-hidden="true"></i>失败、不匹配或待核实</span><span><i class="rx-dot idle" aria-hidden="true"></i>未启用</span><span>身份用描边标记,和连接状态分开</span></p>
|
||||
<div id="rx-cards" class="rx-cards"></div><p id="rx-empty" hidden>没有匹配的接收机。</p>
|
||||
<p class="rx-footnote">卡片标题用芯片和 USB 插口区分设备。两只相同的 CH340,看「集线器 · 端口」对应哪个插口。乐鑫调试口等其他串口默认停用,需要时再启用。蓝牙串口不会自动加入。</p>
|
||||
<nav class="rid-pager" aria-label="接收器诊断分页">
|
||||
<span id="rx-page-summary" class="rid-page-summary"></span>
|
||||
<div class="rid-pager-actions"><button id="rx-page-prev" type="button" disabled>上一页</button><span id="rx-page-number" class="rid-page-number" tabindex="-1" aria-live="polite"></span><button id="rx-page-next" type="button" disabled>下一页</button></div>
|
||||
</nav>
|
||||
</section>
|
||||
<div id="rx-pop" class="rx-pop" role="dialog" aria-label="其余提示" hidden></div>
|
||||
</div>
|
||||
@@ -14,9 +16,9 @@
|
||||
<label>连接方式<select name="transport"><option value="serial">USB 串口</option><option value="udp">UDP 接收监听</option><option value="tcp-listen">TCP 接收监听</option></select></label>
|
||||
<div id="rx-serial-fields"><label>串口<input name="serialPort" list="rx-port-options" placeholder="例如 COM16"><datalist id="rx-port-options"></datalist></label><label>波特率<input name="baudRate" type="number" min="1200" max="4000000" value="115200"></label></div>
|
||||
<div id="rx-network-fields" hidden><label>监听 IP<input name="bindIp" value="127.0.0.1"></label><label>监听端口<input name="port" type="number" min="1" max="65535" value="8788"></label></div>
|
||||
<label>报文协议<select name="format"><option value="raw">原始诊断(不生成目标)</option><option value="uid-json">UID / ua_* JSON</option><option value="rid-device-json">RID 设备 JSON(message / uav)</option><option value="json-lines">约定 JSON / JSON Lines</option><option value="postcard">约定 Postcard</option></select></label>
|
||||
<label id="rx-peer-fields" hidden>允许来源 IP<input name="peerIp" maxlength="45" placeholder="设备 IP,可留空"></label>
|
||||
<div id="rx-uid-fields" hidden><label>UID 身份范围<select name="uidIdentity"><option value="source-scoped">按接收机隔离(默认)</option><option value="global-device">跨接收机合并(已确认 UID 唯一)</option></select></label><p class="rx-note">仅在设备协议确认 UID 唯一对应无人机时启用合并。切换身份范围后,原有人工关联和名单不会自动迁移;同一接收机发出相同 UID 且没有其他身份字段时无法区分多架飞机。</p></div>
|
||||
<p id="rx-protocol-note" class="rx-note"></p><p class="rx-footnote">只读接收;修改连接参数会重启当前接收任务。</p>
|
||||
<p class="rx-footnote">只读接收;修改连接参数会重启当前接收任务。</p>
|
||||
<div class="rx-actions"><button class="primary" id="rx-save" type="submit">保存配置</button><button id="rx-delete" type="button">删除接收机</button></div>
|
||||
</form>
|
||||
<section id="rx-diagnostic" hidden><p id="rx-status-label"></p><dl id="rx-stats"></dl><button id="rx-capture" type="button">读取最新原始报文</button><pre id="rx-raw">尚未读取。最多显示最近 4 KiB。</pre></section>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<div class="registry-workspace">
|
||||
<aside class="history-panel" aria-labelledby="history-title"><header class="history-heading"><h2 id="history-title">本地档案</h2><button id="refresh-list" type="button" aria-label="刷新记录" title="刷新记录">↻</button></header><div class="history-content">
|
||||
<div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号或机型"><span id="search-count" aria-live="polite"></span></div>
|
||||
<div class="archiveTools"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号或机型"><span id="search-count" aria-live="polite"></span></div>
|
||||
<button id="new-registration" type="button" class="primary">+ 新建设备登记</button>
|
||||
<div class="history-toolbar"><button id="selection-toggle" type="button" aria-pressed="false">选择</button><div class="export-controls"><button id="export-toggle" type="button" disabled aria-expanded="false" aria-controls="export-options">导出⌄</button><div id="export-options" class="registry-popup" hidden><button id="export-archive" type="button" disabled>导出档案包</button><button id="export-excel" type="button" disabled>导出 Excel</button><p>仅导出当前页已选档案</p></div></div></div>
|
||||
<div id="selection-controls" hidden><label class="select-all"><input id="select-all" type="checkbox">全选当前页 <span id="selected-count">(0)</span></label></div>
|
||||
</div><div id="selection-controls" hidden><label class="select-all"><input id="select-all" type="checkbox">全选当前页 <span id="selected-count">(0)</span></label></div>
|
||||
<p class="history-message" id="history-message" role="status"></p><div id="history-empty" class="history-empty">正在读取档案…</div><div id="history-cards" class="history-cards"></div>
|
||||
</div><nav class="pagination" aria-label="档案分页"><span id="page-status" aria-live="polite"></span><div><button id="previous-page" type="button">上一页</button><button id="next-page" type="button">下一页</button></div></nav>
|
||||
</div><nav id="page-status" class="pagination rid-pager" aria-label="档案分页"><span id="page-count" class="rid-page-summary"></span><div class="rid-pager-actions"><button id="previous-page" type="button">上一页</button><span id="archive-page-number" class="rid-page-number" aria-live="polite"></span><button id="next-page" type="button">下一页</button></div></nav>
|
||||
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p></aside>
|
||||
<section class="registration-editor" aria-labelledby="register-title"><header class="registration-heading"><div><h1 id="register-title">新建设备登记</h1><p>填写设备信息,生成本机登记二维码</p></div><span></span></header>
|
||||
<form id="register-form" aria-labelledby="register-title" novalidate><div class="registration-fields-scroll"><section class="registry-group"><div class="registry-group-heading"><h2>设备身份</h2><span>仅模块 SN 必填</span></div><div class="registration-fields"><div class="registration-field full"><label for="serial-no">模块 SN <span aria-hidden="true">*</span></label><input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" pattern="[A-Za-z0-9\-]{6,40}" aria-describedby="serial-no-hint serial-no-error" placeholder="输入完整模块序列号"><p id="serial-no-hint" class="registry-help">6–40 位英文字母、数字或半角连字符 -;请填写设备实际 SN,不支持中文名称。</p><p id="serial-no-error" class="form-message error" role="alert" hidden></p></div><div class="registration-field"><label for="model-name">机型 <small>选填</small></label><input id="model-name" name="modelName" maxlength="60" placeholder="例如:5 寸穿越机"></div><div class="registration-field"><label for="owner-name">登记人 / 备注 <small>选填</small></label><input id="owner-name" name="ownerName" maxlength="40" placeholder="方便后续查找"></div></div><p class="registry-help">SN 需与上位机模块一致;相同 SN 再次保存将更新原档案。</p></section>
|
||||
@@ -13,7 +13,7 @@
|
||||
<section class="registry-group"><div class="registry-group-heading"><h2>设备照片</h2><span>选填 · 最多 2 张</span></div><div class="registration-photos"><div class="photo-slot"><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="0" hidden><button type="button" class="photo-pick" data-photo-choose="0" aria-label="添加照片 1"><img id="slot-preview-0" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 1</strong><span id="slot-name-0">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="0" id="slot-remove-0" hidden>移除照片</button></div><button type="button" data-photo-keep="0" id="slot-keep-0" hidden>保留原选择</button><p id="slot-status-0" class="photo-status" role="status"></p></div><div class="photo-slot"><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="1" hidden><button type="button" class="photo-pick" data-photo-choose="1" aria-label="添加照片 2"><img id="slot-preview-1" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 2</strong><span id="slot-name-1">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="1" id="slot-remove-1" hidden>移除照片</button></div><button type="button" data-photo-keep="1" id="slot-keep-1" hidden>保留原选择</button><p id="slot-status-1" class="photo-status" role="status"></p></div></div><p class="registry-help">JPG、PNG、WebP · 每张不超过 5 MB · 仅保存在本机档案</p></section>
|
||||
<p class="form-message" id="form-message" role="status"></p></div><div class="registration-savebar"><span id="draft-state">保存时校验 SN 与编号</span><button class="primary" id="register-button" type="submit">保存登记并生成二维码 →</button></div></form></section><section class="result-panel registry-group" aria-labelledby="result-title" id="registration-result" tabindex="-1"><header class="result-heading"><h2 id="result-title">二维码与核验</h2><button id="close-archive-detail" type="button" hidden>返回列表</button></header>
|
||||
<div id="empty-result" class="empty-state"><div class="empty-glyph"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M3 3h6v6H3z M15 3h6v6h-6z M3 15h6v6H3z M14 14h3v3h4v4h-7z"/></svg></div><div><b>等待完成登记</b><p>保存后自动生成二维码,供本地版上位机读取和核验。</p></div><ol><li>填写模块 SN</li><li>保存登记并生成二维码</li><li>在本地版上位机核验</li></ol></div><div id="record-result" class="record-result" hidden>
|
||||
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
|
||||
<div class="qr-stage" id="qr-stage" aria-label="可离线扫描的无人机登记标签码"></div>
|
||||
<div class="record-kicker" id="result-context" role="status"></div>
|
||||
<p class="result-fpv-label">FPV 编号</p>
|
||||
<div class="uas-display" id="display-uas"></div>
|
||||
@@ -22,10 +22,12 @@
|
||||
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
|
||||
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
|
||||
</div>
|
||||
<div class="url-box"><span>二维码内容</span><code id="display-url"></code></div>
|
||||
<div class="result-actions"><button id="download-qr" class="secondary" type="button">下载二维码 PNG</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
|
||||
<p class="result-tip">扫码读取登记编号、模块 SN、机型和登记信息。修改档案后可重新打印标签。</p>
|
||||
<div class="result-actions"><button id="print-label" class="primary" type="button">打印标签</button><button id="download-qr" class="secondary" type="button">下载标签码 PNG</button></div>
|
||||
<p id="label-feedback" class="form-message" role="status"></p>
|
||||
<div class="url-box"><span>本机档案核验链接</span><code id="display-url"></code></div>
|
||||
<div class="result-actions"><button id="download-local-qr" class="secondary" type="button">下载本机档案码</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
|
||||
<div class="result-actions"><a id="open-card" class="secondary action-link" target="_blank" rel="noopener">打开档案卡</a><a id="download-card" class="ghost action-link">下载离线档案卡</a></div>
|
||||
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
mod photos;
|
||||
use gloo_net::http::Request;
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use qrcodegen::{QrCode, QrCodeEcc};
|
||||
use qrcodegen::{QrCode, QrCodeEcc, QrSegment};
|
||||
use rid_shared::target_lists::{ListKind, Snapshot, valid_target_id};
|
||||
use serde_json::{Value, json};
|
||||
use std::{cell::RefCell, collections::HashSet, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
@@ -15,6 +16,8 @@ use web_sys::{
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
rows: Vec<Value>,
|
||||
lists: Option<Snapshot>,
|
||||
can_edit_lists: bool,
|
||||
selected: HashSet<String>,
|
||||
active: Option<Value>,
|
||||
editing: Option<Value>,
|
||||
@@ -54,6 +57,52 @@ fn value(id: &str) -> String {
|
||||
fn field<'a>(v: &'a Value, name: &str) -> &'a str {
|
||||
v[name].as_str().unwrap_or("")
|
||||
}
|
||||
|
||||
fn label_code(record: &Value) -> Result<QrCode> {
|
||||
let mut payload = String::from("无人机登记");
|
||||
for (title, key) in [
|
||||
("登记编号", "uasCode"),
|
||||
("模块 SN", "serialNo"),
|
||||
("机型", "modelName"),
|
||||
("登记人/备注", "ownerName"),
|
||||
("登记日期", "createdAt"),
|
||||
] {
|
||||
let raw = field(record, key);
|
||||
let value = if key == "createdAt" {
|
||||
raw.get(..10).unwrap_or(raw)
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let line = value.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if !line.is_empty() {
|
||||
payload.push_str(&format!("\n{title}:{line}"));
|
||||
}
|
||||
}
|
||||
QrCode::encode_segments(
|
||||
&[
|
||||
QrSegment::make_eci(26),
|
||||
QrSegment::make_bytes(payload.as_bytes()),
|
||||
],
|
||||
QrCodeEcc::Medium,
|
||||
)
|
||||
.map_err(|_| "标签二维码生成失败".into())
|
||||
}
|
||||
|
||||
fn qr_svg(qr: &QrCode) -> String {
|
||||
let extent = qr.size() + 8;
|
||||
let mut svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\" shape-rendering=\"crispEdges\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><path fill=\"black\" d=\""
|
||||
);
|
||||
for y in 0..qr.size() {
|
||||
for x in 0..qr.size() {
|
||||
if qr.get_module(x, y) {
|
||||
svg.push_str(&format!("M{} {}h1v1h-1z", x + 4, y + 4));
|
||||
}
|
||||
}
|
||||
}
|
||||
svg.push_str("\"/></svg>");
|
||||
svg
|
||||
}
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
@@ -98,6 +147,7 @@ async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
|
||||
let req = match method {
|
||||
"POST" => Request::post(url),
|
||||
"PATCH" => Request::patch(url),
|
||||
"PUT" => Request::put(url),
|
||||
"DELETE" => Request::delete(url),
|
||||
_ => Request::get(url),
|
||||
};
|
||||
@@ -115,6 +165,128 @@ async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
|
||||
Err(payload["error"].as_str().unwrap_or("请求失败").to_owned())
|
||||
}
|
||||
}
|
||||
// Use the same SN-keyed, revision-checked list store as the list manager.
|
||||
async fn refresh_lists(state: &Shared) -> Result<()> {
|
||||
let result = async {
|
||||
let payload = api("/api/target-lists", "GET", None).await?;
|
||||
let snapshot: Snapshot =
|
||||
serde_json::from_value(payload).map_err(|_| "名单响应无效,请刷新后重试".to_owned())?;
|
||||
let auth = api("/api/auth/status", "GET", None).await?;
|
||||
Ok::<_, String>((
|
||||
snapshot,
|
||||
matches!(field(&auth, "role"), "admin" | "operator"),
|
||||
))
|
||||
}
|
||||
.await;
|
||||
let mut s = state.borrow_mut();
|
||||
match result {
|
||||
Ok((snapshot, allowed)) => {
|
||||
s.lists = Some(snapshot);
|
||||
s.can_edit_lists = allowed;
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
s.lists = None;
|
||||
s.can_edit_lists = false;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn list_actions(s: &State, sn: &str) -> String {
|
||||
if !s.can_edit_lists || !valid_target_id(sn) {
|
||||
return String::new();
|
||||
}
|
||||
let Some(snapshot) = &s.lists else {
|
||||
return String::new();
|
||||
};
|
||||
let current = snapshot
|
||||
.entries
|
||||
.iter()
|
||||
.find(|entry| entry.target_id == sn)
|
||||
.map(|entry| entry.list_kind);
|
||||
let revision = snapshot.revision;
|
||||
[
|
||||
(ListKind::White, "white", "白名单"),
|
||||
(ListKind::Black, "black", "黑名单"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(kind, wire, label)| {
|
||||
let verb = if current == Some(kind) {
|
||||
"移除"
|
||||
} else {
|
||||
"加入"
|
||||
};
|
||||
let operation = if current == Some(kind) {
|
||||
"remove"
|
||||
} else {
|
||||
"add"
|
||||
};
|
||||
format!(
|
||||
r#"<button type="button" data-action="list-{operation}-{wire}" data-list-revision="{revision}">{verb}{label}</button>"#
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
async fn change_list(
|
||||
state: &Shared,
|
||||
row: &Value,
|
||||
action: &str,
|
||||
expected_revision: u64,
|
||||
) -> Result<()> {
|
||||
let sn = field(row, "serialNo");
|
||||
let (revision, note) = {
|
||||
let s = state.borrow();
|
||||
if !s.can_edit_lists {
|
||||
return Err("当前账号不能修改黑白名单".into());
|
||||
}
|
||||
let snapshot = s.lists.as_ref().ok_or("请刷新后重试")?;
|
||||
if snapshot.revision != expected_revision {
|
||||
return Err("名单已更新,请重新打开菜单后重试".into());
|
||||
}
|
||||
let entry = snapshot.entries.iter().find(|entry| entry.target_id == sn);
|
||||
(
|
||||
snapshot.revision,
|
||||
entry.map(|entry| entry.note.clone()).unwrap_or_default(),
|
||||
)
|
||||
};
|
||||
let path = format!("/api/target-lists/{}", js_sys::encode_uri_component(sn));
|
||||
let removing = action.starts_with("list-remove-");
|
||||
let kind = if action.ends_with("-white") {
|
||||
"white"
|
||||
} else {
|
||||
"black"
|
||||
};
|
||||
let payload = if removing {
|
||||
api(&format!("{path}?revision={revision}"), "DELETE", None).await?
|
||||
} else {
|
||||
// PUT atomically replaces the previous kind; never delete then insert.
|
||||
api(
|
||||
&path,
|
||||
"PUT",
|
||||
Some(json!({"list_kind":kind,"note":note,"expected_revision":revision})),
|
||||
)
|
||||
.await?
|
||||
};
|
||||
state.borrow_mut().lists = Some(
|
||||
serde_json::from_value(payload)
|
||||
.map_err(|_| "名单已提交,响应无效,请刷新核对".to_owned())?,
|
||||
);
|
||||
message(
|
||||
"history-message",
|
||||
&format!(
|
||||
"{}已{}{}",
|
||||
sn,
|
||||
if removing { "移除" } else { "加入" },
|
||||
if kind == "white" {
|
||||
"白名单"
|
||||
} else {
|
||||
"黑名单"
|
||||
}
|
||||
),
|
||||
false,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn archive_status(payload: &Value) {
|
||||
if payload["archiveStatus"] == "pending" {
|
||||
hidden("archive-warning", false);
|
||||
@@ -214,7 +386,8 @@ fn render_rows(state: &Shared) {
|
||||
let current = s.active.as_ref().is_some_and(|r| r["id"] == row["id"]);
|
||||
let date = field(row, "createdAt");
|
||||
let short = date.get(..10).unwrap_or(date).replace('-', ".");
|
||||
html.push_str(&format!(r#"<article class="archive-card{}{}" data-id="{id}"><label class="archive-select"><input id="select-{id}" type="checkbox" data-action="select" aria-label="选择档案 {sn}" {}>选择导出</label><div class="archive-card-head"><h3>{sn}</h3><button id="more-{id}" type="button" class="archive-more" data-action="more" aria-label="{sn} 更多操作" aria-expanded="false" aria-controls="actions-{id}">···</button></div><strong>{}</strong><p>{} · {}</p><div class="archive-card-foot"><time datetime="{}" title="{}">{}</time><button id="view-{id}" type="button" data-action="view">查看档案 →</button></div><div id="actions-{id}" class="registry-popup" hidden><button type="button" data-action="edit">编辑资料 / 照片</button><a href="{}" target="_blank" rel="noopener">打开档案卡</a><a href="{}">下载离线档案卡</a><button type="button" data-action="qr">查看二维码</button><button type="button" class="delete-record" data-action="delete">删除档案</button></div></article>"#, if selected {" selected"} else {""}, if current {" is-current"} else {""}, if selected {"checked"} else {""}, escape(field(row,"uasCode")), escape(field(row,"modelName")), escape(field(row,"ownerName")), escape(date), escape(date), escape(&short), escape(field(row,"archiveUrl")), escape(field(row,"downloadArchiveUrl"))));
|
||||
let list_actions = list_actions(&s, field(row, "serialNo"));
|
||||
html.push_str(&format!(r#"<article class="archive-card{}{}" data-id="{id}"><label class="archive-select"><input id="select-{id}" type="checkbox" data-action="select" aria-label="选择档案 {sn}" {}>选择导出</label><div class="archive-card-head"><h3>{sn}</h3><button id="more-{id}" type="button" class="archive-more" data-action="more" aria-label="{sn} 更多操作" aria-expanded="false" aria-controls="actions-{id}">···</button></div><strong>{}</strong><p>{} · {}</p><div class="archive-card-foot"><time datetime="{}" title="{}">{}</time><button id="view-{id}" type="button" data-action="view">查看档案 →</button></div><div id="actions-{id}" class="registry-popup" hidden><a href="/workbench/platform.html?module=flight-plans&record={id}" target="_top">申请飞行报备</a>{list_actions}<button type="button" data-action="edit">编辑资料 / 照片</button><a href="{}" target="_blank" rel="noopener">打开档案卡</a><a href="{}">下载离线档案卡</a><button type="button" data-action="qr">查看二维码</button><button type="button" class="delete-record" data-action="delete">删除档案</button></div></article>"#, if selected {" selected"} else {""}, if current {" is-current"} else {""}, if selected {"checked"} else {""}, escape(field(row,"uasCode")), escape(field(row,"modelName")), escape(field(row,"ownerName")), escape(date), escape(date), escape(&short), escape(field(row,"archiveUrl")), escape(field(row,"downloadArchiveUrl"))));
|
||||
}
|
||||
el("history-cards").set_inner_html(&html);
|
||||
hidden("history-empty", !s.rows.is_empty());
|
||||
@@ -264,12 +437,12 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
|
||||
s.selected.retain(|id| ids.contains(id));
|
||||
}
|
||||
text(
|
||||
"page-status",
|
||||
&format!(
|
||||
"第 {page} / {} 页 · 共 {} 条",
|
||||
pages.max(1),
|
||||
payload["total"]
|
||||
),
|
||||
"archive-page-number",
|
||||
&format!("第 {page} / {} 页", pages.max(1)),
|
||||
);
|
||||
text(
|
||||
"page-count",
|
||||
&format!("共 {} 条 · 每页 20 条", payload["total"]),
|
||||
);
|
||||
text(
|
||||
"search-count",
|
||||
@@ -287,6 +460,13 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
|
||||
"没有找到匹配的档案。"
|
||||
},
|
||||
);
|
||||
let lists_result = refresh_lists(&state).await;
|
||||
if state.borrow().generation != generation {
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(error) = lists_result {
|
||||
message("history-message", &error, true);
|
||||
}
|
||||
render_rows(&state);
|
||||
page_buttons(&state);
|
||||
return Ok(());
|
||||
@@ -390,26 +570,11 @@ fn draw(state: &Shared, record: Value) {
|
||||
.set_attribute("src", &format!("{url}?v={}", js_sys::Date::now()));
|
||||
}
|
||||
hidden("saved-photos", !has_photos);
|
||||
if let Ok(qr) = QrCode::encode_text(field(&record, "qrUrl"), QrCodeEcc::Medium) {
|
||||
let size = qr.size();
|
||||
let extent = size + 8;
|
||||
let mut svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><g fill=\"black\">"
|
||||
);
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
if qr.get_module(x, y) {
|
||||
svg.push_str(&format!(
|
||||
"<rect x=\"{}\" y=\"{}\" width=\"1\" height=\"1\"/>",
|
||||
x + 4,
|
||||
y + 4
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
svg.push_str("</g></svg>");
|
||||
el("qr-stage").set_inner_html(&svg);
|
||||
match label_code(&record) {
|
||||
Ok(qr) => el("qr-stage").set_inner_html(&qr_svg(&qr)),
|
||||
Err(error) => text("qr-stage", &error),
|
||||
}
|
||||
text("label-feedback", "");
|
||||
state.borrow_mut().active = Some(record);
|
||||
render_rows(state);
|
||||
el("registration-result").scroll_into_view();
|
||||
@@ -662,46 +827,85 @@ async fn export(state: Shared, kind: &str) -> Result<()> {
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn download_qr(state: &Shared) -> Result<()> {
|
||||
fn download_qr(state: &Shared, local: bool) -> Result<()> {
|
||||
let row = state.borrow().active.clone().ok_or("请先登记")?;
|
||||
let qr = QrCode::encode_text(field(&row, "qrUrl"), QrCodeEcc::Medium)
|
||||
.map_err(|_| "二维码生成失败")?;
|
||||
let qr = if local {
|
||||
QrCode::encode_text(field(&row, "qrUrl"), QrCodeEcc::Medium)
|
||||
.map_err(|_| "本机二维码生成失败")?
|
||||
} else {
|
||||
label_code(&row)?
|
||||
};
|
||||
let canvas: HtmlCanvasElement = document()
|
||||
.create_element("canvas")
|
||||
.map_err(err)?
|
||||
.unchecked_into();
|
||||
canvas.set_width(640);
|
||||
canvas.set_height(640);
|
||||
let extent = qr.size() + 8;
|
||||
let cell = 640 / extent;
|
||||
let side = (extent * cell) as u32;
|
||||
canvas.set_width(side);
|
||||
canvas.set_height(side);
|
||||
let context: web_sys::CanvasRenderingContext2d = canvas
|
||||
.get_context("2d")
|
||||
.map_err(err)?
|
||||
.ok_or("Canvas 不可用")?
|
||||
.unchecked_into();
|
||||
context.set_fill_style_str("white");
|
||||
context.fill_rect(0.0, 0.0, 640.0, 640.0);
|
||||
context.fill_rect(0.0, 0.0, side.into(), side.into());
|
||||
context.set_fill_style_str("black");
|
||||
let cell = 640.0 / f64::from(qr.size() + 8);
|
||||
for y in 0..qr.size() {
|
||||
for x in 0..qr.size() {
|
||||
if qr.get_module(x, y) {
|
||||
let left = (f64::from(x + 4) * cell).floor();
|
||||
let top = (f64::from(y + 4) * cell).floor();
|
||||
let right = (f64::from(x + 5) * cell).ceil();
|
||||
let bottom = (f64::from(y + 5) * cell).ceil();
|
||||
context.fill_rect(left, top, right - left, bottom - top);
|
||||
context.fill_rect(
|
||||
((x + 4) * cell).into(),
|
||||
((y + 4) * cell).into(),
|
||||
cell.into(),
|
||||
cell.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
download(
|
||||
&canvas.to_data_url().map_err(err)?,
|
||||
&format!(
|
||||
"{}-{}-LOCAL.png",
|
||||
"{}-{}-{}.png",
|
||||
field(&row, "serialNo"),
|
||||
field(&row, "uasCode")
|
||||
field(&row, "uasCode"),
|
||||
if local { "LOCAL" } else { "LABEL" }
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_label(state: &Shared) -> Result<()> {
|
||||
let row = state.borrow().active.clone().ok_or("请先登记")?;
|
||||
let qr = label_code(&row)?;
|
||||
let page = window()
|
||||
.open_with_url_and_target("about:blank", "_blank")
|
||||
.map_err(err)?
|
||||
.ok_or("请允许打开标签打印预览")?;
|
||||
let doc = page.document().ok_or("无法生成打印预览")?;
|
||||
doc.set_title(&format!("无人机登记标签 · {}", field(&row, "uasCode")));
|
||||
doc.body()
|
||||
.ok_or("无法生成打印预览")?
|
||||
.set_inner_html(include_str!("registry_label.html"));
|
||||
for (id, key) in [("label-number", "uasCode"), ("label-serial", "serialNo")] {
|
||||
doc.get_element_by_id(id)
|
||||
.ok_or("标签字段不可用")?
|
||||
.set_text_content(Some(field(&row, key)));
|
||||
}
|
||||
doc.get_element_by_id("label-code")
|
||||
.ok_or("标签二维码不可用")?
|
||||
.set_inner_html(&qr_svg(&qr));
|
||||
let print = Closure::<dyn FnMut(Event)>::new(move |_| {
|
||||
let _ = page.print();
|
||||
});
|
||||
doc.get_element_by_id("label-print")
|
||||
.ok_or("打印按钮不可用")?
|
||||
.add_event_listener_with_callback("click", print.as_ref().unchecked_ref())
|
||||
.map_err(err)?;
|
||||
print.forget();
|
||||
Ok(())
|
||||
}
|
||||
fn listen(name: &str, handler: impl Fn(Event) + 'static) {
|
||||
let closure = Closure::<dyn Fn(Event)>::new(handler);
|
||||
document()
|
||||
@@ -725,6 +929,14 @@ pub fn init() {
|
||||
..State::default()
|
||||
}));
|
||||
for event in ["rid-workspace-view", "focus"] {
|
||||
// Entering the iframe also fires focus before the user's pagination click.
|
||||
if event == "focus"
|
||||
&& document()
|
||||
.body()
|
||||
.is_some_and(|body| body.class_name() == "rid-embedded")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let state = state.clone();
|
||||
let refresh = Closure::<dyn FnMut(Event)>::new(move |_| {
|
||||
let screen = document()
|
||||
@@ -1013,9 +1225,19 @@ pub fn init() {
|
||||
dialog().close();
|
||||
return;
|
||||
}
|
||||
if id == "download-qr" {
|
||||
if let Err(e) = download_qr(&state) {
|
||||
message("form-message", &e, true);
|
||||
if matches!(
|
||||
id.as_str(),
|
||||
"download-qr" | "download-local-qr" | "print-label"
|
||||
) {
|
||||
let result = if id == "print-label" {
|
||||
print_label(&state)
|
||||
} else {
|
||||
download_qr(&state, id == "download-local-qr")
|
||||
};
|
||||
if let Err(e) = result {
|
||||
message("label-feedback", &e, true);
|
||||
} else {
|
||||
text("label-feedback", "");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1036,14 +1258,63 @@ pub fn init() {
|
||||
.cloned();
|
||||
let Some(row) = row else { return };
|
||||
if action == "more" {
|
||||
toggle_menu(
|
||||
&state,
|
||||
&format!("actions-{record_id}"),
|
||||
&format!("more-{record_id}"),
|
||||
);
|
||||
if state
|
||||
.borrow()
|
||||
.menu
|
||||
.as_ref()
|
||||
.is_some_and(|(popup, _)| popup == &format!("actions-{record_id}"))
|
||||
{
|
||||
close_menu(&state, true);
|
||||
return;
|
||||
}
|
||||
state.borrow_mut().busy = true;
|
||||
spawn_local(async move {
|
||||
let result = refresh_lists(&state).await;
|
||||
state.borrow_mut().busy = false;
|
||||
render_rows(&state);
|
||||
if let Err(error) = result {
|
||||
message("history-message", &error, true);
|
||||
}
|
||||
if document()
|
||||
.get_element_by_id(&format!("actions-{record_id}"))
|
||||
.is_some()
|
||||
{
|
||||
toggle_menu(
|
||||
&state,
|
||||
&format!("actions-{record_id}"),
|
||||
&format!("more-{record_id}"),
|
||||
);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
close_menu(&state, true);
|
||||
if matches!(
|
||||
action.as_str(),
|
||||
"list-add-white" | "list-add-black" | "list-remove-white" | "list-remove-black"
|
||||
) {
|
||||
let Some(revision) = t
|
||||
.get_attribute("data-list-revision")
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
state.borrow_mut().busy = true;
|
||||
saving_controls(&state, true);
|
||||
spawn_local(async move {
|
||||
let result = change_list(&state, &row, &action, revision).await;
|
||||
if let Err(error) = result {
|
||||
let _ = refresh_lists(&state).await;
|
||||
message("history-message", &error, true);
|
||||
}
|
||||
state.borrow_mut().busy = false;
|
||||
saving_controls(&state, false);
|
||||
render_rows(&state);
|
||||
page_buttons(&state);
|
||||
focus(&format!("more-{record_id}"));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if action == "edit" {
|
||||
state.borrow_mut().edit_return = format!("more-{record_id}");
|
||||
edit(&state, row);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<style>
|
||||
@page { size: 60mm 40mm; margin: 0; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; color: #111; background: #edf0f3; font: 14px system-ui, sans-serif; }
|
||||
.controls { padding: 16px; text-align: center; }
|
||||
.controls button { font: inherit; padding: 6px 20px; }
|
||||
.asset-label {
|
||||
width: 60mm; height: 40mm; padding: 1mm; background: #fff; display: grid;
|
||||
grid-template-columns: 29mm minmax(0, 1fr); align-items: center; gap: .6mm;
|
||||
margin: 0 auto; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.asset-label svg { width: 100%; height: auto; display: block; }
|
||||
.asset-label h1 { margin: 0 0 1mm; font-size: 9pt; }
|
||||
.asset-label p { margin: .8mm 0 0; font-size: 6.5pt; overflow-wrap: anywhere; }
|
||||
.asset-label strong { font-size: 8pt; overflow-wrap: anywhere; }
|
||||
@media print {
|
||||
body { background: #fff; }
|
||||
.controls { display: none; }
|
||||
.asset-label { margin: 0; }
|
||||
}
|
||||
</style>
|
||||
<header class="controls"><button id="label-print" type="button">打印标签</button><p>纸张 60 × 40 mm,缩放 100%</p></header>
|
||||
<main class="asset-label" aria-label="无人机登记标签">
|
||||
<div id="label-code" aria-label="设备信息二维码"></div>
|
||||
<div><h1>无人机登记</h1><strong id="label-number"></strong><p>模块 SN</p><p id="label-serial"></p></div>
|
||||
</main>
|
||||
@@ -5,6 +5,7 @@ use rid_shared::target_lists::{
|
||||
Entry, ListKind, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -415,21 +416,84 @@ pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
||||
.get()
|
||||
.min(rows.get().len().div_ceil(50).max(1) - 1)
|
||||
});
|
||||
let page_ids = Memo::new(move |_| {
|
||||
rows.get()
|
||||
.into_iter()
|
||||
.skip(page.get() * 50)
|
||||
.take(50)
|
||||
.map(|entry| entry.target_id)
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let registrations = RwSignal::new(HashMap::<String, bool>::new());
|
||||
Effect::new(move |_| {
|
||||
if !lists.open.get() {
|
||||
return;
|
||||
}
|
||||
let ids = page_ids.get();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
spawn_local(async move {
|
||||
let url = format!("/api/target-registration-status?ids={}", ids.join(","));
|
||||
let Ok(response) = Request::get(&url).send().await else {
|
||||
return;
|
||||
};
|
||||
if !response.ok() {
|
||||
return;
|
||||
}
|
||||
let Ok(value) = response.json::<Value>().await else {
|
||||
return;
|
||||
};
|
||||
if !lists.open.get_untracked() || page_ids.get_untracked() != ids {
|
||||
return;
|
||||
}
|
||||
let Some(entries) = value["entries"].as_array() else {
|
||||
return;
|
||||
};
|
||||
registrations.set(
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
Some((
|
||||
row["targetId"].as_str()?.to_owned(),
|
||||
row["registered"].as_bool()?,
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
});
|
||||
});
|
||||
view! {
|
||||
<section id="rt-list-manager" tabindex="-1" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get()>
|
||||
<header class="rt-list-manager-head"><div><h2>"黑白名单管理"</h2><p>"按目标标识精确匹配,区分大小写。名单与设备登记档案独立。"</p></div><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.editor_open.set(true);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="返回工作区" on:click=move |_|lists.close()>"返回工作区"</button></header>
|
||||
<header class="rt-list-manager-head"><div><h2>"黑白名单管理"</h2><p>"用实时目标列表里的 RID 标识添加条目,区分大小写。设备登记仅建立档案,白名单在这里手动添加。"</p></div><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.editor_open.set(true);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="返回工作区" on:click=move |_|lists.close()>"返回工作区"</button></header>
|
||||
<div class="rt-list-manager-body">
|
||||
<aside class="rt-list-category-panel" aria-label="名单分类"><h3>"名单分类"</h3><div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div><div class="rt-list-policy"><h3>"标记与告警规则"</h3><p>"白名单标记为可信,围栏免告警。黑名单突出显示并记录告警。所有目标继续接收和显示。"</p><p>"移除后恢复为未分类,保留遥测与登记档案。"</p></div></aside>
|
||||
<aside class="rt-list-category-panel" aria-label="名单分类"><h3>"名单分类"</h3><div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div><div class="rt-list-policy"><h3>"告警规则"</h3><p><strong>"白名单"</strong>" · 进入围栏时免围栏告警。设备未登记时,仍会产生未登记告警。"</p><p><strong>"黑名单"</strong>" · 发现目标时产生黑名单告警。"</p><p><strong>"设备登记"</strong>" · 用于识别已登记设备,地图上显示绿色。"</p></div></aside>
|
||||
<section class="rt-list-table-panel" aria-label="名单目录">
|
||||
<div class="rt-list-table-toolbar">
|
||||
<label class="rt-list-search"><span class="rt-list-search-label">"搜索名单"</span><input placeholder="搜索目标标识或备注" prop:value=move||lists.query.get() on:input=move|event|{lists.query.set(event_target_value(&event));lists.manager_page.set(0);}/></label></div>
|
||||
<p class="rt-list-help" hidden=move||lists.ready.get()>"正在读取本机名单…"</p>
|
||||
<p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
|
||||
<div class="rt-list-rows"><table aria-label="黑白名单条目"><thead><tr><th scope="col">"目标标识"</th><th scope="col">"分类"</th><th scope="col">"备注"</th><th scope="col">"操作"</th></tr></thead><tbody><Show when=move||lists.editor_open.get()&&(!lists.editing.get()||!rows.get().iter().skip(page.get()*50).take(50).any(|e|e.target_id==lists.draft_id.get()))><tr class="rt-inline-editor-row"><td colspan="4"><ListEditor lists=lists/></td></tr></Show><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
|
||||
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();let note_id=entry.target_id.clone();let selected_id=entry.target_id.clone();let editor_id=entry.target_id.clone();
|
||||
view!{<tr class="rt-list-row" class:selected=move||lists.editing.get()&&lists.draft_id.get()==selected_id data-target-id=entry.target_id.clone()><td class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong></td><td><Badge lists=lists target=badge_id/></td><td class="rt-list-row-note"><p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==note_id).map(|entry|entry.note.clone()).unwrap_or_default())}</p></td><td class="rt-list-row-actions"><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></td></tr><Show when=move||lists.editor_open.get()&&lists.editing.get()&&lists.draft_id.get()==editor_id><tr class="rt-inline-editor-row"><td colspan="4"><ListEditor lists=lists/></td></tr></Show>}
|
||||
<div class="rt-list-rows"><table aria-label="黑白名单条目"><thead><tr><th scope="col">"RID 标识"</th><th scope="col">"名单类型"</th><th scope="col">"设备登记"</th><th scope="col">"名单备注"</th><th scope="col">"操作"</th></tr></thead><tbody><Show when=move||lists.editor_open.get()&&(!lists.editing.get()||!page_ids.get().contains(&lists.draft_id.get()))><tr class="rt-inline-editor-row"><td colspan="5"><ListEditor lists=lists/></td></tr></Show><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
|
||||
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();let note_id=entry.target_id.clone();let selected_id=entry.target_id.clone();let editor_id=entry.target_id.clone();let registration_id=entry.target_id.clone();
|
||||
view!{
|
||||
<tr class="rt-list-row" class:selected=move||lists.editing.get()&&lists.draft_id.get()==selected_id data-target-id=entry.target_id.clone()>
|
||||
<td class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong></td>
|
||||
<td><Badge lists=lists target=badge_id/></td>
|
||||
<td>{move||registrations.with(|items|match items.get(®istration_id){Some(true)=>"已登记",Some(false)=>"未登记",None=>"待核验"})}</td>
|
||||
<td class="rt-list-row-note"><p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==note_id).map(|entry|if entry.note.is_empty(){"—".into()}else{entry.note.clone()}).unwrap_or_default())}</p></td>
|
||||
<td class="rt-list-row-actions"><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></td>
|
||||
</tr>
|
||||
<Show when=move||lists.editor_open.get()&&lists.editing.get()&&lists.draft_id.get()==editor_id><tr class="rt-inline-editor-row"><td colspan="5"><ListEditor lists=lists/></td></tr></Show>
|
||||
}
|
||||
}/></tbody></table><p class="rt-list-help" hidden=move||!lists.ready.get()||!rows.get().is_empty()>"暂无匹配条目,可点击新增条目。"</p></div>
|
||||
<nav class="rt-list-pagination" aria-label="名单分页"><span>{move||format!("共 {} 条",rows.get().len())}</span><button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button><span>{move||format!("{} / {}",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span><button type="button" disabled={move||(page.get()+1)*50>=rows.get().len()} on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button></nav>
|
||||
<nav class="rt-list-pagination rid-pager" aria-label="名单分页">
|
||||
<span class="rid-page-summary">{move||format!("共 {} 条 · 每页 50 条",rows.get().len())}</span>
|
||||
<div class="rid-pager-actions">
|
||||
<button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button>
|
||||
<span class="rid-page-number" aria-live="polite">{move||format!("第 {} / {} 页",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span>
|
||||
<button type="button" disabled={move||(page.get()+1)*50>=rows.get().len()} on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button>
|
||||
</div>
|
||||
</nav>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
@@ -443,7 +507,7 @@ fn ListEditor(lists: Lists) -> impl IntoView {
|
||||
view! {
|
||||
<form id="rt-list-entry-form" on:submit=move |event|{event.prevent_default();lists.save(lists.draft_id.get_untracked().trim().to_owned(),lists.draft_kind.get_untracked(),lists.draft_note.get_untracked());}>
|
||||
<div class="rt-inline-editor-heading"><h3>{move||if lists.editing.get(){"编辑名单条目"}else{"新增名单条目"}}</h3><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.editor_open.set(false)>"收起编辑"</button></div>
|
||||
<label for="rt-list-entry-id">"目标标识"<input id="rt-list-entry-id" required maxlength="64" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/></label>
|
||||
<label for="rt-list-entry-id">"RID 标识"<input id="rt-list-entry-id" required maxlength="64" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() aria-describedby="rid-list-id-hint" prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/><small id="rid-list-id-hint">"在实时目标列表点击「复制 RID」获取。"</small></label>
|
||||
<label for="rt-list-entry-kind">"名单类型"<select id="rt-list-entry-kind" disabled=move||lists.busy.get() prop:value=move||match lists.draft_kind.get(){ListKind::White=>"white",ListKind::Black=>"black"} on:change=move|event|lists.draft_kind.set(if event_target_value(&event)=="white"{ListKind::White}else{ListKind::Black})><option value="white">"白名单"</option><option value="black">"黑名单"</option></select></label>
|
||||
<label for="rt-list-entry-note" class="rt-inline-note">"备注(最多200字)"<textarea id="rt-list-entry-note" maxlength="200" disabled=move||lists.busy.get() prop:value=move||lists.draft_note.get() on:input=move|event|lists.draft_note.set(event_target_value(&event))></textarea></label>
|
||||
<div class="rt-inline-editor-actions"><button class="primary" type="submit" disabled=move||!lists.ready.get()||lists.busy.get()>{move||if lists.busy.get(){"正在保存…"}else{"保存名单条目"}}</button></div>
|
||||
|
||||
@@ -317,7 +317,45 @@ fn queue_save(state: Shared) {
|
||||
}
|
||||
});
|
||||
}
|
||||
fn embedded_view(view: &str) -> &str {
|
||||
match view {
|
||||
"register" | "archives" | "maps" | "target-lists" | "receivers" | "history" => view,
|
||||
_ => "home",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn init_embedded() {
|
||||
if let Some(body) = document().body() {
|
||||
body.set_class_name("rid-embedded");
|
||||
}
|
||||
let Some(window) = web_sys::window() else {
|
||||
return;
|
||||
};
|
||||
let navigate =
|
||||
Closure::<dyn FnMut(web_sys::CustomEvent)>::new(|event: web_sys::CustomEvent| {
|
||||
if let Some(view) = event.detail().as_string() {
|
||||
show(embedded_view(&view), false);
|
||||
}
|
||||
});
|
||||
let _ = window.add_event_listener_with_callback(
|
||||
"rid-embedded-navigate",
|
||||
navigate.as_ref().unchecked_ref(),
|
||||
);
|
||||
navigate.forget();
|
||||
show("home", false);
|
||||
if let Ok(event) = Event::new("rid-embedded-ready") {
|
||||
let _ = window.dispatch_event(&event);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn navigate(view: &str) {
|
||||
if document()
|
||||
.body()
|
||||
.is_some_and(|body| body.class_name() == "rid-embedded")
|
||||
{
|
||||
show(embedded_view(view), false);
|
||||
return;
|
||||
}
|
||||
let realtime = web_sys::window()
|
||||
.is_some_and(|w| w.location().pathname().unwrap_or_default() == "/realtime");
|
||||
show(view, realtime);
|
||||
@@ -645,6 +683,8 @@ pub fn init(realtime: bool) {
|
||||
"receivers"
|
||||
} else if search.contains("app=target-lists") {
|
||||
"target-lists"
|
||||
} else if search.contains("app=maps") {
|
||||
"maps"
|
||||
} else if realtime {
|
||||
"realtime"
|
||||
} else if search.contains("app=geofences") {
|
||||
|
||||
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 2.5 MiB |
|
After Width: | Height: | Size: 30 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"/>
|
||||
|
After Width: | Height: | Size: 89 B |
@@ -0,0 +1,89 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const MAX_LINK_GAP_MS = 30000;
|
||||
const BASE_JUMP_M = 260;
|
||||
const MAX_SPEED_MPS = 120;
|
||||
const TO_RAD = Math.PI / 180;
|
||||
|
||||
function registrationColors(registered) {
|
||||
if (registered === true) return {fill:'#26ad72', glow:'rgba(38,210,133,.82)'};
|
||||
if (registered === false) return {fill:'#ec4361', glow:'rgba(255,64,96,.86)'};
|
||||
return {fill:'#637c91', glow:'rgba(128,158,180,.45)'};
|
||||
}
|
||||
|
||||
function createMarker({heading = 0, fill = 'rgba(255,211,90,.96)', glow = 'rgba(255,211,90,.86)', opacity = 1} = {}) {
|
||||
const badge = document.createElement('div');
|
||||
badge.className = 'rid-drone-marker';
|
||||
badge.setAttribute('aria-hidden', 'true');
|
||||
badge.style.setProperty('--rid-drone-fill', fill);
|
||||
badge.style.setProperty('--rid-drone-glow', glow);
|
||||
badge.style.opacity = opacity;
|
||||
const plane = document.createElement('span');
|
||||
plane.className = 'rid-drone-plane';
|
||||
plane.style.transform = 'rotate(' + heading + 'deg)';
|
||||
badge.append(plane);
|
||||
return badge;
|
||||
}
|
||||
|
||||
function validPosition(point) {
|
||||
return Number.isFinite(point?.longitude) && Math.abs(point.longitude) <= 180
|
||||
&& Number.isFinite(point?.latitude) && Math.abs(point.latitude) <= 90
|
||||
&& Number.isFinite(point?.timeMs);
|
||||
}
|
||||
|
||||
function jumping(from, to) {
|
||||
const dy = Math.sin((to.latitude - from.latitude) * TO_RAD / 2);
|
||||
const dx = Math.sin((to.longitude - from.longitude) * TO_RAD / 2);
|
||||
const latitude = Math.cos(from.latitude * TO_RAD) * Math.cos(to.latitude * TO_RAD);
|
||||
const metres = 12742000 * Math.asin(Math.sqrt(Math.min(1, dy * dy + latitude * dx * dx)));
|
||||
const seconds = Math.max(0.5, (to.timeMs - from.timeMs) / 1000);
|
||||
return metres > BASE_JUMP_M + MAX_SPEED_MPS * seconds;
|
||||
}
|
||||
|
||||
function shortInterval(from, to) {
|
||||
const elapsed = to.timeMs - from.timeMs;
|
||||
return elapsed >= 0 && elapsed < MAX_LINK_GAP_MS;
|
||||
}
|
||||
|
||||
function trackHeading(fromLat, fromLng, toLat, toLng) {
|
||||
const east = (((toLng - fromLng + 540) % 360) - 180) * Math.cos((fromLat + toLat) * TO_RAD / 2);
|
||||
const north = toLat - fromLat;
|
||||
return east || north ? (Math.atan2(east, north) / TO_RAD + 360) % 360 : null;
|
||||
}
|
||||
|
||||
function prepareTrack(samples) {
|
||||
const points = [];
|
||||
let pendingBreak = false;
|
||||
let skipped = 0;
|
||||
let newSegments = 0;
|
||||
for (let index = 0; index < samples.length; index += 1) {
|
||||
const point = samples[index];
|
||||
if (!validPosition(point)) {
|
||||
pendingBreak = true;
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = points.at(-1);
|
||||
const next = samples[index + 1];
|
||||
const connectedBefore = previous && !point.segmentStart && !pendingBreak && shortInterval(previous, point);
|
||||
// Discard an isolated out-and-back spike only when the adjacent run is still continuous.
|
||||
if (connectedBefore && validPosition(next) && !next.segmentStart && shortInterval(previous, next)
|
||||
&& shortInterval(point, next) && jumping(previous, point) && jumping(point, next) && !jumping(previous, next)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (previous && !point.segmentStart && (!connectedBefore || jumping(previous, point))) {
|
||||
points.push({...point, segmentStart: true});
|
||||
newSegments += 1;
|
||||
} else {
|
||||
points.push(point);
|
||||
}
|
||||
pendingBreak = false;
|
||||
}
|
||||
return {points, skipped, newSegments};
|
||||
}
|
||||
|
||||
window.ridDroneMap = Object.freeze({createMarker, prepareTrack, trackHeading, registrationColors, MAX_LINK_GAP_MS});
|
||||
})();
|
||||
@@ -0,0 +1,61 @@
|
||||
.rid-drone-marker {
|
||||
box-sizing: border-box;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 2px solid rgb(255 255 255 / 92%);
|
||||
border-radius: 50%;
|
||||
background: var(--rid-drone-fill);
|
||||
box-shadow: 0 0 18px var(--rid-drone-glow);
|
||||
}
|
||||
|
||||
.rid-drone-plane {
|
||||
width: 21px;
|
||||
height: 21px;
|
||||
background: #fff;
|
||||
clip-path: polygon(50% 2%, 57% 9%, 58% 34%, 95% 59%, 95% 68%, 58% 57%,
|
||||
57% 79%, 72% 91%, 72% 98%, 50% 90%, 28% 98%, 28% 91%,
|
||||
43% 79%, 42% 57%, 5% 68%, 5% 59%, 42% 34%, 43% 9%);
|
||||
}
|
||||
|
||||
.rid-pilot-marker {
|
||||
box-sizing: border-box;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 2px solid #fff1c5;
|
||||
border-radius: 9px;
|
||||
background: #ffd35a;
|
||||
box-shadow: 0 2px 7px #081726bb;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.rid-pair-label {
|
||||
position: absolute;
|
||||
bottom: calc(100% + 5px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
box-sizing: border-box;
|
||||
width: max-content;
|
||||
max-width: 240px;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid #80b5d8;
|
||||
border-radius: 6px;
|
||||
background: #0b2034f2;
|
||||
color: #eff8ff;
|
||||
font: 600 12px/1.25 "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
box-shadow: 0 2px 5px #06101b9c;
|
||||
}
|
||||
|
||||
.rid-pilot-marker .rid-pair-label {
|
||||
top: calc(100% + 5px + var(--rid-pilot-label-offset));
|
||||
bottom: auto;
|
||||
border-color: #dcaf4b;
|
||||
}
|
||||
|
||||
.mapWrap[data-hide-models] .rid-pair-label { display: none; }
|
||||
@@ -0,0 +1,62 @@
|
||||
@import url('/workbench/pagination.css');
|
||||
|
||||
body.rid-embedded {
|
||||
--work-text: #e6f5ff;
|
||||
--work-muted: #b2cada;
|
||||
--work-line: #36536a;
|
||||
--work-panel: #102438;
|
||||
--work-input: #091a2c;
|
||||
--glass-surface: #102438;
|
||||
--glass-solid: #102438;
|
||||
--mc-accent: #69ccff;
|
||||
--mc-accent-blue: #1e88ff;
|
||||
background: #0b1d2e;
|
||||
}
|
||||
body.rid-embedded > .workspace-pane {
|
||||
inset: 0;
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
}
|
||||
body.rid-embedded .registry-workspace {
|
||||
height: 100dvh;
|
||||
}
|
||||
body.rid-embedded .rt-list-manager-head button[aria-label="返回工作区"] {
|
||||
display: none;
|
||||
}
|
||||
body.rid-embedded :is(.history-panel, .track-playback-controls, .rx-surface, .registry-group) {
|
||||
border-color: var(--work-line);
|
||||
}
|
||||
body.rid-embedded :is(button, input, select, textarea, summary):focus-visible {
|
||||
outline: 2px solid #7ddcff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
/* Archive lists fill the workspace; cards retain their responsive grid width. */
|
||||
body.rid-embedded[data-screen=archives]:not([data-archive-detail=open]) .registry-workspace {
|
||||
width:100%; max-width:none; margin-inline:0; box-sizing:border-box;
|
||||
}
|
||||
body.rid-embedded[data-screen=archives]:not([data-archive-detail=open]) .registry-workspace .history-panel {
|
||||
height:100%; min-height:0; border-radius:8px; box-shadow:none;
|
||||
}
|
||||
body.rid-embedded[data-screen=archives] .archiveTools { flex-flow:row wrap; align-items:center; gap:10px 12px; margin-bottom:18px; }
|
||||
body.rid-embedded[data-screen=archives] .archiveTools .history-search { flex:1 1 240px; max-width:520px; margin:0; }
|
||||
body.rid-embedded[data-screen=archives] .archiveTools #new-registration { width:auto; min-height:40px; }
|
||||
body.rid-embedded[data-screen=archives] .archiveTools .history-toolbar { margin:0 0 0 auto; gap:8px; }
|
||||
body.rid-embedded[data-screen=archives] .archiveTools :is(#selection-toggle,#export-toggle) { min-height:40px; }
|
||||
body.rid-embedded[data-screen=archives] .archive-card { border-radius:8px; padding:16px; }
|
||||
body.rid-embedded[data-screen=archives] .archive-card .archive-more { flex:none; min-width:28px; }
|
||||
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools { flex-direction:column; align-items:stretch; }
|
||||
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools .history-search { flex:none; }
|
||||
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools .history-toolbar { margin:0; }
|
||||
@media (max-width: 760px) {
|
||||
body.rid-embedded .registry-workspace {
|
||||
height: auto;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
body.rid-embedded .rx-cards {
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr));
|
||||
}
|
||||
body.rid-embedded .rt-list-manager-head {
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
const modulePath = '/workbench/module.html';
|
||||
|
||||
if (location.pathname === modulePath) {
|
||||
if (window.parent === window) {
|
||||
location.replace('/workbench/platform.html');
|
||||
} else {
|
||||
const available = new Set(['home', 'register', 'archives', 'target-lists', 'maps', 'history', 'receivers']);
|
||||
let navigating = false;
|
||||
|
||||
function send(type, view) {
|
||||
window.parent.postMessage({ type, view }, location.origin);
|
||||
}
|
||||
|
||||
function ready() {
|
||||
send('rid-embedded-ready');
|
||||
}
|
||||
|
||||
window.addEventListener('rid-embedded-ready', ready);
|
||||
if (document.body?.className === 'rid-embedded') ready();
|
||||
|
||||
window.addEventListener('message', event => {
|
||||
if (event.origin !== location.origin || event.source !== window.parent ||
|
||||
event.data?.type !== 'rid-embedded-navigate' || !available.has(event.data.view)) return;
|
||||
navigating = true;
|
||||
try {
|
||||
const { view, record, mapOptions } = event.data;
|
||||
if (view === 'history') window.ridHistory?.setMapOptions(mapOptions);
|
||||
if (document.body.dataset.screen !== view) {
|
||||
window.dispatchEvent(new CustomEvent('rid-embedded-navigate', { detail: view }));
|
||||
}
|
||||
if (view === 'history') {
|
||||
window.dispatchEvent(new CustomEvent('rid-history-record', {
|
||||
detail: record ? JSON.stringify(record) : null
|
||||
}));
|
||||
}
|
||||
} finally {
|
||||
navigating = false;
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('rid-history-return-records', () => send('rid-embedded-return-records'));
|
||||
|
||||
window.addEventListener('rid-workspace-view', () => {
|
||||
const view = document.body.dataset.screen;
|
||||
if (!navigating && available.has(view)) send('rid-embedded-view', view);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// The reference markup uses data attributes for both static and generated controls.
|
||||
// Only these named actions are callable. Arguments are data, never JavaScript.
|
||||
const actions = Object.freeze(Object.fromEntries(`
|
||||
cancelDrawZone clearAllTrackLayers clearCurrentAlerts copyDroneRid deleteZone deleteCenterAlarm finishDrawZone
|
||||
fitAll focusAlertOnMap focusStationByKey focusZoneByKey logout
|
||||
mapSetViewWgs84 markAlarmHandled openModule renameZone setBaseMap
|
||||
shareDroneLocation shareStationLocation startDrawZone testAlarm
|
||||
toggleMapLabels toggleSidePanel toggleZone trackDrone unlockDroneTracking
|
||||
`.trim().split(/\s+/).map(name => [name, window[name]])));
|
||||
|
||||
function argument(element, value) {
|
||||
if (value === '@value') return element.value;
|
||||
if (value === '@checked') return element.checked;
|
||||
if (value === '@number') return Number(element.value);
|
||||
if (value === '@true') return true;
|
||||
if (value.startsWith('@n:')) return Number(value.slice(3));
|
||||
return value;
|
||||
}
|
||||
|
||||
function run(event, element, kind) {
|
||||
const name = element.getAttribute(`data-rid-${kind}`);
|
||||
const args = [];
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const value = element.getAttribute(`data-rid-arg${index}`);
|
||||
if (value !== null) args.push(argument(element, value));
|
||||
}
|
||||
if (name === 'stop') {
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (Object.hasOwn(actions, name)) return actions[name](...args);
|
||||
}
|
||||
|
||||
for (const kind of ['click', 'change', 'input']) {
|
||||
document.addEventListener(kind, event => {
|
||||
const control = event.target.closest?.(`[data-rid-${kind}]`);
|
||||
if (control) Promise.resolve().then(() => run(event, control, kind)).catch(error => {
|
||||
const feedback = document.getElementById('rid-workbench-status');
|
||||
feedback.textContent = error.message || '操作失败,请重试';
|
||||
feedback.hidden = false;
|
||||
clearTimeout(feedback.hideTimer);
|
||||
feedback.hideTimer = setTimeout(() => { feedback.hidden = true; }, 4500);
|
||||
});
|
||||
});
|
||||
}
|
||||
for (const control of document.querySelectorAll('.tool[data-rid-click]')) {
|
||||
control.setAttribute('role', 'button');
|
||||
control.tabIndex = 0;
|
||||
}
|
||||
document.addEventListener('keydown', event => {
|
||||
const control = event.target.closest?.('div[role="button"][data-rid-click]');
|
||||
if (control && (event.key === ' ' || event.key === 'Enter')) {
|
||||
event.preventDefault();
|
||||
control.click();
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,16 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const types = Object.freeze({
|
||||
whitelist: {label:'白名单',tone:'ok',fill:'#27b888',rank:4},
|
||||
authorized: {label:'已报备',tone:'ok',fill:'#27b888',rank:5},
|
||||
unregistered: {label:'未登记告警',tone:'danger',fill:'#cc3c48',rank:2},
|
||||
unfiled: {label:'未报备告警',tone:'warning',fill:'#ca921e',rank:3},
|
||||
geofence_enter: {label:'防控区告警',tone:'danger',fill:'#cc3c48',rank:0},
|
||||
blacklist: {label:'黑名单告警',tone:'danger',fill:'#cc3c48',rank:1},
|
||||
unknown: {label:'待核验',tone:'muted',fill:'#929eaa',rank:6}
|
||||
});
|
||||
const meta = code => types[code] || types.unknown;
|
||||
const tag = code => {const value=meta(code);return `<span class="flightTag ${value.tone}">${value.label}</span>`;};
|
||||
const tags = values => (values?.length ? [...new Set(values)] : ['unknown']).sort((a,b)=>meta(a).rank-meta(b).rank).map(tag).join(' ');
|
||||
window.ridFlightStatus=Object.freeze({types,meta,tag,tags,colors:code=>({fill:meta(code).fill,glow:meta(code).fill+'88'})});
|
||||
})();
|
||||
@@ -0,0 +1,704 @@
|
||||
.nav button:focus-visible,
|
||||
.moduleNav button:focus-visible,
|
||||
.tool[role="button"]:focus-visible {
|
||||
outline: 2px solid #65d8ff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
#app .top { z-index: 2300; }
|
||||
body { color-scheme: dark; }
|
||||
#app .top .nav { align-items: center; flex-wrap: nowrap; }
|
||||
#app .top .nav .btn { margin: 0; flex: 0 0 auto; }
|
||||
.overview-totals { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
|
||||
.overview-totals span { color: #b9d6e8; font-size: 12px; padding: 4px 8px; border: 1px solid #294a60; border-radius: 5px; background: #102639; }
|
||||
.overview-totals strong { margin-inline-start: 3px; color: #f0f9ff; font-variant-numeric: tabular-nums; }
|
||||
.mapDisplayOptions {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
padding-top: 5px;
|
||||
border-top: 1px solid #36546a;
|
||||
color: #e1f2ff;
|
||||
}
|
||||
.mapDisplayOptions label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-height: 22px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mapDisplayOptions input {
|
||||
flex: none;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
margin: 0;
|
||||
accent-color: #74bfff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mapDisplayOptions input:focus-visible {
|
||||
outline: 2px solid #7ddcff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.nav-account {
|
||||
flex: 0 0 auto;
|
||||
max-width: 130px;
|
||||
margin-inline: 4px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: #a5c9de;
|
||||
}
|
||||
#workbenchNav button[aria-current="page"] {
|
||||
border-color: #67bdff;
|
||||
background: #123c60;
|
||||
color: #e7f7ff;
|
||||
}
|
||||
.moduleNav {
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
flex-wrap: wrap;
|
||||
gap: 3px 12px;
|
||||
padding: 6px 14px 0;
|
||||
border-bottom: 1px solid #28455b;
|
||||
background: #0a1b2d;
|
||||
}
|
||||
.moduleNav[hidden] { display: none; }
|
||||
.moduleNav button {
|
||||
margin: 0;
|
||||
padding: 7px 8px;
|
||||
min-height: 34px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
color: #b2cbdd;
|
||||
font-size: 13px;
|
||||
}
|
||||
.moduleNav button:hover { color: #e9f6ff; }
|
||||
.moduleNav button[aria-current="page"] { color: #e9f6ff; border-bottom-color: #69c2ff; }
|
||||
@media (max-width: 2240px) {
|
||||
#app .top .nav { gap: 5px !important; }
|
||||
#app .top .nav .btn { padding-inline: 7px !important; font-size: 12px !important; }
|
||||
.nav-account { max-width: 110px; }
|
||||
}
|
||||
|
||||
@media (max-width: 1700px) {
|
||||
#app .top { height: 102px; align-items: flex-start; padding-top: 13px !important; }
|
||||
#app .top .titleBox {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 31px;
|
||||
margin: 0;
|
||||
transform: translate(-50%, -50%);
|
||||
max-width: calc(100% - 32px);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
#app .top .title { overflow: hidden; text-overflow: ellipsis; }
|
||||
#app .top .nav {
|
||||
position: absolute;
|
||||
inset: auto 14px 8px;
|
||||
max-width: none;
|
||||
justify-content: safe center;
|
||||
overflow-x: auto;
|
||||
padding: 3px;
|
||||
}
|
||||
#app .main { top: 102px; }
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
#app .top { height: 122px; }
|
||||
#app .top .brand { display: flex; position: absolute; left: 50%; top: 49px; transform: translateX(-50%); }
|
||||
#app .top .brandLogo { display: none; }
|
||||
#app .main { top: 122px; }
|
||||
}
|
||||
|
||||
#rid-workbench-status {
|
||||
position: fixed;
|
||||
z-index: 4000;
|
||||
inset: auto 1rem 1rem auto;
|
||||
max-width: min(420px, calc(100vw - 2rem));
|
||||
margin: 0;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid #2b6894;
|
||||
border-radius: 10px;
|
||||
background: #0b2035;
|
||||
color: #e6f6ff;
|
||||
}
|
||||
|
||||
.rid-module-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin-bottom: 14px;
|
||||
color: #b2cada;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.rid-module-editor:empty { display: none; }
|
||||
.rid-module-feedback { padding: 9px 12px; margin-bottom: 10px; color: #9ff3d9; border: 1px solid #266977; border-radius: 8px; }
|
||||
.rid-module-feedback.dangerText { color: #ffc4cb; border-color: #864555; }
|
||||
.moduleBody :focus-visible,
|
||||
.mapWrap :is(button, select):focus-visible,
|
||||
.centerLoginPanel button:focus-visible { outline: 2px solid #7ddcff; outline-offset: 2px; }
|
||||
.rid-admin-form, .rid-admin-form fieldset, .rid-admin-fields {
|
||||
display: flex; flex-wrap: wrap; align-items: end; gap: 10px;
|
||||
}
|
||||
.rid-admin-form fieldset { border: 0; margin: 0; padding: 0; min-width: 0; }
|
||||
.rid-admin-form label, .rid-period label { display: grid; gap: 5px; color: #c7e5f6; font-size: 13px; }
|
||||
.rid-admin-form .rid-check { display: flex; flex-direction: row; align-items: center; min-height: 34px; }
|
||||
.rid-module-page [hidden] { display: none !important; }
|
||||
.rid-module-page button:disabled { opacity: .55; cursor: default; }
|
||||
|
||||
.moduleBody {
|
||||
padding: clamp(12px, 1.5vw, 24px);
|
||||
background: #0b1d2e;
|
||||
}
|
||||
.moduleBody .rid-period {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: end;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
border-color: #29465c;
|
||||
background: #102438;
|
||||
}
|
||||
.rid-period label { min-width: 0; flex: 0 1 190px; }
|
||||
.rid-period label:first-child:has(input:not([type])) { flex: 1 1 220px; max-width: 380px; }
|
||||
#alarmFilters label:has(select) { flex-basis: 135px; }
|
||||
.moduleBody :is(input:not([type=checkbox]), select) { min-width: 0; min-height: 36px; }
|
||||
.moduleBody input::placeholder { color: #8ea9bd; }
|
||||
.moduleBody button:not(.red):not(:disabled) { background: #1b63a6; }
|
||||
.moduleBody button:not(.red):not(:disabled):hover { background: #2376be; }
|
||||
.moduleBody :is(.rid-period, .rid-module-toolbar, .rid-admin-form) button { min-height: 36px; padding-inline: 14px; }
|
||||
.moduleBody .rid-module-toolbar button[data-action="refresh-rx"],
|
||||
.moduleBody .rid-admin-form button[data-action="cancel-edit"],
|
||||
.moduleBody .dataTable button:not(.red):not(:disabled) {
|
||||
box-shadow: inset 0 0 0 1px #365973;
|
||||
background: #18324a;
|
||||
}
|
||||
.moduleBody .dataTable :is(th, td) { vertical-align: middle; }
|
||||
.moduleBody .dataTable td { overflow-wrap: anywhere; }
|
||||
.moduleBody .dataTable th { background: #132d43; }
|
||||
.moduleBody .dataTable tbody tr:last-child td { border-bottom: 0; }
|
||||
.moduleBody .dataTable td .smallBtn { margin: 2px; padding: 5px 8px; }
|
||||
.moduleBody .resultCount { font-size: 13px; color: #bed3e1; font-variant-numeric: tabular-nums; }
|
||||
.moduleBody .moduleEmpty {
|
||||
min-height: 116px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
color: #aac2d4;
|
||||
}
|
||||
.moduleBody .moduleSplit {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.moduleBody .moduleSplit .dataTable { min-width: 0; }
|
||||
.moduleBody .moduleSplit .dataTable :is(th, td) { white-space: normal; }
|
||||
.moduleBody .moduleSplit .dataTable :is(th, td):last-child {
|
||||
text-align: end;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.moduleBody .stateTag.neutral { background: #223b51; color: #c1d4e3; }
|
||||
.moduleBody .stateTag { white-space: normal; max-width: 240px; }
|
||||
.moduleBody .dataTableWrap { max-height: max(180px, calc(100dvh - 350px)); }
|
||||
.moduleBody:not([hidden]):has(#alarmResult), #alarmResult {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
#alarmResult { flex: 1 1 auto; }
|
||||
#alarmFilters, #alarmResult > :is(.resultCount, .rid-pager) { flex: none; }
|
||||
#alarmResult > .dataTableWrap { min-height: 0; }
|
||||
@media (max-width: 560px), (max-height: 620px) {
|
||||
#alarmResult { flex: none; }
|
||||
#alarmResult > .dataTableWrap { max-height: 52dvh; }
|
||||
}
|
||||
.moduleBody .rid-pager .rid-pager-actions button:not(:disabled) { background: #18344c; }
|
||||
.moduleBody .rid-pager .rid-pager-actions button:hover:not(:disabled) { background: #254f70; }
|
||||
[data-module="configs"] { max-width: 780px; }
|
||||
.rid-config-form fieldset { display: grid; width: 100%; gap: 14px; }
|
||||
.rid-config-form input[name="name"] { max-width: 410px; }
|
||||
.rid-config-form button { justify-self: start; }
|
||||
.rid-config-options { display: flex; flex-wrap: wrap; column-gap: 20px; }
|
||||
.rid-admin-form :is(label, .rid-admin-fields) { max-width: 100%; }
|
||||
.rid-admin-form input[type="checkbox"] { width: 16px; height: 16px; accent-color: #489be5; }
|
||||
.rid-admin-form .btnrow { flex-wrap: wrap; }
|
||||
@media (max-width: 760px) {
|
||||
.moduleBody .moduleSplit { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
#app .top .nav { inset-inline: 8px; }
|
||||
.nav-account { max-width: 64px; }
|
||||
#app .moduleBody .rid-period {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
|
||||
}
|
||||
.rid-period label:has(input:not([type])),
|
||||
.rid-period label:has(select),
|
||||
.rid-period button { grid-column: 1 / -1; }
|
||||
.rid-period label:has(input:not([type])) { max-width: none; }
|
||||
.rid-period button { justify-self: end; }
|
||||
}
|
||||
@media (max-width: 410px) {
|
||||
.nav-account { display: none; }
|
||||
#app .moduleBody .rid-period { grid-template-columns: 1fr !important; }
|
||||
}
|
||||
|
||||
.loginCenterMountain .centerLoginScene {
|
||||
display: grid;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
gap: 24px;
|
||||
min-height: 100dvh;
|
||||
padding: clamp(18px, 3vw, 42px);
|
||||
}
|
||||
.loginCenterMountain .centerLoginHeader,
|
||||
.loginCenterMountain .centerLoginPanel,
|
||||
.loginCenterMountain .centerLoginFooter { position: relative; inset: auto; }
|
||||
.loginCenterMountain .centerLoginBg { animation: none; }
|
||||
.loginCenterMountain .centerLoginPanel {
|
||||
place-self: center;
|
||||
transform: none;
|
||||
width: min(100%, 410px);
|
||||
padding: clamp(20px, 3vw, 36px);
|
||||
border-radius: 14px;
|
||||
border-color: #365976;
|
||||
box-shadow: 0 16px 50px #0006;
|
||||
background: #0b2035f2;
|
||||
}
|
||||
.centerLoginPanel::before,
|
||||
.centerLoginSubmit::before { display: none; }
|
||||
.centerPanelHeading h1 { margin: 0 0 24px; font-size: 24px; color: #f4f9ff; }
|
||||
.centerLoginPanel .centerField input { padding-inline: 13px; }
|
||||
.centerLoginPanel .centerLoginSubmit {
|
||||
height: 44px;
|
||||
letter-spacing: 0;
|
||||
font-size: 15px;
|
||||
background: #1a69ad;
|
||||
border: 1px solid #3d8ac8;
|
||||
box-shadow: none;
|
||||
}
|
||||
.centerLoginPanel .centerLoginSubmit:hover { transform: none; }
|
||||
.centerLoginPanel .centerLoginState { text-align: center; color: #b0c9dc; }
|
||||
.centerLoginFooter { color: #b0c5d7; }
|
||||
|
||||
#moduleTitle {
|
||||
position: absolute;
|
||||
inset: 0 auto auto 0;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
#moduleBody[hidden], #moduleEmbed [hidden], #moduleEmbed[hidden] { display: none; }
|
||||
.moduleEmbed { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.moduleEmbed iframe { flex: 1; min-height: 0; width: 100%; border: 0; }
|
||||
#moduleEmbedStatus { margin: 18px 20px; color: #bfddf2; }
|
||||
#moduleEmbedRetry { align-self: start; margin: 0 20px; }
|
||||
|
||||
#app .left { overflow: hidden; }
|
||||
#app .left .deviceListPanel,
|
||||
#app .left .targetListPanel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
#app .left .p-title { flex: 0 0 auto; }
|
||||
#app .left #stationList,
|
||||
#app .left #droneList {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
overflow: auto;
|
||||
padding-inline-end: 3px;
|
||||
}
|
||||
#app .right { overflow: hidden; }
|
||||
#app .right > :is(.zonePanel, .alertPanel) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
#app .right .p-title { flex: 0 0 auto; }
|
||||
#app .right :is(.zonePanelContent, #alertList) {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
overflow: auto;
|
||||
padding-inline-end: 3px;
|
||||
}
|
||||
#app .main > :is(.left, .right) { max-width: 100%; }
|
||||
@media (max-width: 1100px) {
|
||||
#app .main { grid-template-columns: minmax(0, 1fr) !important; }
|
||||
#app .main > :is(.left, .right) { top: 62px; bottom: 12px; max-height: none; }
|
||||
#app .sideToggle { top: 12px; transform: none; height: 36px; border-radius: 7px; }
|
||||
#app .main .sideToggle.leftToggle { left: 9px; }
|
||||
#app .main .sideToggle.rightToggle { right: 9px; }
|
||||
}
|
||||
.zonePanelContent [hidden] { display: none; }
|
||||
.zoneCoordinateEntry {
|
||||
border: 1px solid #284a61;
|
||||
border-radius: 6px;
|
||||
background: #0c2136;
|
||||
}
|
||||
.zoneCoordinateEntry > summary {
|
||||
padding: 8px 10px;
|
||||
color: #cae7f6;
|
||||
cursor: pointer;
|
||||
}
|
||||
.zoneCoordinateEntry > summary:hover { background: #132c42; }
|
||||
.zoneCoordinateEntry form,
|
||||
.zoneCoordinateEntry form label { display: grid; gap: 5px; min-width: 0; }
|
||||
.zoneCoordinateEntry form { gap: 8px; border-top: 1px solid #284a61; padding: 9px; font-size: 12px; }
|
||||
.zoneFormFields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(86px, .64fr); gap: 7px; }
|
||||
.zoneCoordinateEntry :is(input, select, textarea) { width: 100%; min-width: 0; }
|
||||
.zoneCoordinateEntry textarea {
|
||||
border: 1px solid #325671;
|
||||
border-radius: 5px;
|
||||
padding: 7px 8px;
|
||||
background: #091a2d;
|
||||
color: #dcecf6;
|
||||
resize: vertical;
|
||||
font: 12px/1.5 ui-monospace, monospace;
|
||||
}
|
||||
.zoneCoordinateEntry form button { justify-self: end; }
|
||||
#zoneCoordinateHelp, .zoneDrawEditor p { margin: 0; color: #a8c7dc; font-size: 12px; }
|
||||
.zoneDrawEditor {
|
||||
margin-top: 8px;
|
||||
padding: 8px;
|
||||
border: 1px solid #284a61;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.zoneDrawActions { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; margin-top: 7px; }
|
||||
.zoneDrawActions input { width: 100%; }
|
||||
.zoneDrawActions button { white-space: nowrap; }
|
||||
.zoneFeedback { flex: 0 0 auto; margin: 0 0 8px; color: #a3dfca; font-size: 12px; }
|
||||
.zoneFeedback.error { color: #ffadb7; }
|
||||
.zoneList { list-style: none; margin: 10px 0 0; padding: 0; }
|
||||
.zoneListItem, .workbenchAlert { padding: 9px 10px; border: 1px solid #244359; border-radius: 6px; background: #0c2032; }
|
||||
.zoneListItem + .zoneListItem, .workbenchAlert + .workbenchAlert { margin-top: 7px; }
|
||||
.zoneListHead, .workbenchAlertHead, .workbenchAlertTarget {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 3px 8px;
|
||||
}
|
||||
.zoneListHead b, .workbenchAlertHead b, .workbenchAlertId { overflow-wrap: anywhere; }
|
||||
.zoneListMeta { margin: 4px 0; color: #a8c7dc; font-size: 12px; }
|
||||
.zoneListItem .zoneActions { margin-top: 7px; }
|
||||
#zoneList .zoneFocus {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
color: inherit;
|
||||
text-align: start;
|
||||
}
|
||||
#zoneList .zoneFocus:hover b { text-decoration: underline; color: #98d7ff; }
|
||||
#zoneList .zoneFocus:focus-visible { outline: 2px solid #65d8ff; outline-offset: 3px; }
|
||||
#zoneList .zoneFocus .zoneListMeta { display: block; font-weight: 400; }
|
||||
.workbenchAlert { border-width: 2px; }
|
||||
.workbenchAlertHead { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; }
|
||||
.workbenchAlertHead b { font-size: 14px; }
|
||||
.workbenchAlertMeta { position: relative; display: inline-flex; align-items: center; padding-inline-end: 13px; }
|
||||
.workbenchAlertHead time { color: #a8c7dc; font-size: 11px; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.workbenchAlertId { display: block; margin-top: 5px; color: #cfe5f3; font-size: 12px; }
|
||||
.workbenchAlertTarget { margin-top: 5px; }
|
||||
.workbenchAlertPosition { color: #a8c7dc; font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.panel .panelCount { margin-inline-start: auto; color: #b5d4e5; font-size: 12px; font-weight: 500; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.alert-unread-dot { position: absolute; inset-inline-end: 0; top: 50%; transform: translateY(-50%); width: 7px; height: 7px; border-radius: 50%; background: #ff5b74; }
|
||||
.rid-station-marker { position: relative; box-sizing: border-box; display: grid; place-items: center; width: 31px; height: 31px; border: 2px solid #bcdfff; border-radius: 7px; background: #28639f; color: white; box-shadow: 0 1px 6px #081725b0; }
|
||||
.rid-station-marker.waiting { background: #6b4b26; border-color: #f4cc8c; }
|
||||
.rid-station-marker.offline { background: #344453; border-color: #acbcc8; }
|
||||
.alertPanel .alarmSettingRow {
|
||||
flex: 0 0 auto;
|
||||
margin-top: 8px;
|
||||
padding: 8px 0 0;
|
||||
border-top: 1px solid #244359;
|
||||
}
|
||||
|
||||
#stationList .stationCard {
|
||||
margin: 0 0 8px;
|
||||
border: 1px solid #22435d;
|
||||
border-radius: 8px;
|
||||
background: #0c2136;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
#stationList .stationCard.offline { background: #0a1b2d; }
|
||||
.stationCardHead {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 2px 9px;
|
||||
padding: 8px 10px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.stationCardHead::-webkit-details-marker { display: none; }
|
||||
.stationCardHead::before {
|
||||
content: "";
|
||||
grid-column: 1;
|
||||
grid-row: 1 / 3;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-right: 1px solid #a8c7dc;
|
||||
border-bottom: 1px solid #a8c7dc;
|
||||
transform: rotate(-45deg);
|
||||
}
|
||||
.stationCard[open] .stationCardHead::before { transform: rotate(45deg); }
|
||||
.stationCardHead:hover { background: #142c41; }
|
||||
.stationCardHead:focus-visible { outline: 2px solid #65d8ff; outline-offset: -2px; }
|
||||
.stationName { grid-column: 2; grid-row: 1; overflow-wrap: anywhere; font-size: 13px; }
|
||||
.stationTransport { grid-column: 2; grid-row: 2; color: #a8c7dc; }
|
||||
.stationCardHead .tag { grid-column: 3; grid-row: 1 / 3; white-space: nowrap; }
|
||||
.stationCardBody { padding: 6px 10px 9px; border-top: 1px solid #22435d; }
|
||||
.stationAddress {
|
||||
overflow-wrap: anywhere;
|
||||
margin-top: 3px;
|
||||
color: #9dc1d9;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.stationFix, .stationExtra { margin: 5px 0 0; color: #a8c7dc; }
|
||||
.stationFix.fixed { color: #92e6be; }
|
||||
.stationMetrics {
|
||||
display: grid;
|
||||
grid-template-columns: 1.3fr 1fr 1fr;
|
||||
gap: 5px;
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
.stationMetrics div {
|
||||
min-width: 0;
|
||||
background: #102942;
|
||||
border-radius: 5px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
.stationMetrics dt { font-size: 11px; color: #a8c7dc; }
|
||||
.stationMetrics dd { color: #e4f5ff; font-variant-numeric: tabular-nums; margin: 1px 0 0; }
|
||||
.stationPosition { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; margin-top: 6px; }
|
||||
.stationPosition span { flex-basis: 100%; font-variant-numeric: tabular-nums; }
|
||||
.stationPosition .smallBtn:focus-visible { outline: 2px solid #65d8ff; outline-offset: 2px; }
|
||||
|
||||
.targetCard button:focus-visible { outline: 2px solid #65d8ff; outline-offset: 2px; }
|
||||
.targetCard {
|
||||
background: #0c2136; border: 1px solid #22435d; border-left: 3px solid var(--target-accent);
|
||||
border-radius: 8px; padding: 9px 10px; margin: 0 0 8px; font-size: 12px; line-height: 1.4;
|
||||
}
|
||||
.targetCard.active { border-color: #5ecbff; border-left-color: var(--target-accent); }
|
||||
.targetCardHead, .targetIdentity, .targetTelemetry {
|
||||
display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px;
|
||||
}
|
||||
.targetCardHead strong { font-size: 14px; min-width: 0; overflow-wrap: anywhere; }
|
||||
.targetIdentity { color: #b4d4e9; margin-top: 3px; }
|
||||
.targetIdentity code { min-width: 0; overflow-wrap: anywhere; }
|
||||
.targetIdentity .tag, .targetCardHead .tag { flex: none; }
|
||||
.targetTelemetry { margin-top: 8px; padding: 5px 7px; border-radius: 5px; background: #102942; }
|
||||
.targetSecondary { margin: 4px 0 0; color: #a8c7dc; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
|
||||
.targetActions { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 8px; }
|
||||
|
||||
/* Shared flight classification across live cards, records and filings. */
|
||||
.flightTag { display:inline-flex; align-items:center; gap:5px; padding:2px 7px; border:1px solid; border-radius:4px; font-size:12px; line-height:1.5; font-weight:600; white-space:nowrap; }
|
||||
.flightTag.warning { color:#ffe29a; background:#554016; border-color:#b88624; }
|
||||
.flightTag.danger { color:#ffd0d4; background:#531f2a; border-color:#b83d4b; }
|
||||
.flightTag.ok { color:#9ce9c7; background:#153e32; border-color:#287757; }
|
||||
.flightTag.white { color:#a6e4fa; background:#163a4c; border-color:#3085a3; }
|
||||
.flightTag.muted { color:#c3ccd5; background:#263540; border-color:#536575; }
|
||||
.workbenchAlert.warning { border-color:#a67720; background:#2d291c; }
|
||||
.workbenchAlert.danger { border-color:#ab3948; background:#311e28; }
|
||||
.workbenchAlert.warning .alert-unread-dot { background:#efbd49; }
|
||||
.workbenchAlert.danger .alert-unread-dot { background:#ff6172; }
|
||||
.alertClassification { margin:6px 0 2px; }
|
||||
.workbenchAlertTarget { flex-wrap:wrap; gap:6px; }
|
||||
.workbenchAlertPosition { flex:1 1 100%; }
|
||||
.panelCount { display:inline-flex; flex-wrap:wrap; justify-content:flex-end; gap:8px; font-size:11px; }
|
||||
.countOk { color:#6bd5a5; } .countWarning { color:#ecc66a; } .countMuted { color:#a2b2bf; }
|
||||
.dot.flightWarning { background:#ca921e; } .dot.flightDanger { background:#cc3c48; }
|
||||
/* Reserve the Leaflet zoom column and attribution strip. The remaining controls share one grid. */
|
||||
.mapWrap { container: live-map / size; }
|
||||
.mapDock {
|
||||
position: absolute;
|
||||
inset: auto 14px 24px 60px;
|
||||
z-index: 4;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
align-items: end;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.mapDock > :is(.legend, .toolbar, .mapSourceBox) {
|
||||
position: static;
|
||||
inset: auto !important;
|
||||
transform: none !important;
|
||||
min-width: 0;
|
||||
max-width: 100% !important;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.mapDock > .legend {
|
||||
justify-self: start;
|
||||
display: block !important;
|
||||
width: min(328px, 100%) !important;
|
||||
}
|
||||
.mapLegendToggle { display: none; }
|
||||
.mapLegendContent { display: grid; gap: 8px; }
|
||||
.mapDock > .toolbar {
|
||||
justify-self: center;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 4px !important;
|
||||
padding: 5px 7px !important;
|
||||
width: min(292px, 100%);
|
||||
}
|
||||
.mapDock .toolbar .tool {
|
||||
flex: 1 1 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 0 !important;
|
||||
min-height: 32px;
|
||||
padding: 2px !important;
|
||||
}
|
||||
.mapDock > .mapSourceBox {
|
||||
justify-self: end;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.mapWrap .leaflet-bottom.leaflet-left {
|
||||
left: 12px !important;
|
||||
bottom: 24px !important;
|
||||
}
|
||||
|
||||
@container live-map (max-width: 1060px) or (max-height: 370px) {
|
||||
.mapDock > .legend {
|
||||
width: fit-content !important;
|
||||
padding: 4px 7px !important;
|
||||
}
|
||||
.mapDock > .legend:has(> .mapLegendToggle[aria-expanded="true"]) {
|
||||
width: min(328px, 100%) !important;
|
||||
}
|
||||
.mapLegendToggle {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
padding: 3px 6px;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
line-height: 1.35;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mapLegendArrow {
|
||||
flex: 0 0 auto;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border: solid currentColor;
|
||||
border-width: 0 1px 1px 0;
|
||||
transform: translateY(1px) rotate(225deg);
|
||||
}
|
||||
.mapLegendToggle[aria-expanded="true"] .mapLegendArrow { transform: translateY(-2px) rotate(45deg); }
|
||||
.mapLegendToggle[aria-expanded="false"] + .mapLegendContent { display: none; }
|
||||
.mapLegendContent {
|
||||
max-height: clamp(58px, 32cqh, 180px);
|
||||
overflow: auto;
|
||||
padding: 6px 4px 3px;
|
||||
}
|
||||
}
|
||||
@container live-map (max-width: 810px) {
|
||||
.mapDock { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.mapDock > .legend { grid-column: 1 / -1; }
|
||||
.mapDock > .toolbar { justify-self: start; }
|
||||
.mapLegendContent { max-height: clamp(36px, calc(100cqh - 148px), 180px); }
|
||||
}
|
||||
@container live-map (max-width: 430px) {
|
||||
.mapDock { grid-template-columns: minmax(0, 1fr); inset-inline: 52px 10px; }
|
||||
.mapLegendContent { max-height: clamp(24px, calc(100cqh - 168px), 180px); }
|
||||
.mapDock > :is(.toolbar, .mapSourceBox) { justify-self: start; }
|
||||
.mapDock > .legend { max-width: calc(100% - 40px) !important; }
|
||||
}
|
||||
@container live-map (max-height: 320px) {
|
||||
#app .main .mapWrap > .sideToggle {
|
||||
top: 12px;
|
||||
transform: none;
|
||||
height: 36px;
|
||||
}
|
||||
}
|
||||
.legendStatus { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:7px 12px; }
|
||||
.legend .legendStatus span { min-width:0; align-items:flex-start !important; white-space:normal !important; line-height:1.5 !important; }
|
||||
.legend .legendStatus .dot { margin-top:4px; }
|
||||
.legendStatus em { min-width:0; overflow-wrap:anywhere; }
|
||||
.legendSymbols { display:flex; flex-wrap:wrap; align-items:center; gap:8px 16px; }
|
||||
.legend .mapDisplayOptions { gap:6px 12px; padding-top:8px; }
|
||||
.legend .mapDisplayOptions label { white-space:nowrap; min-height:24px; }
|
||||
/* Fill the workspace; keep pagination below the independently scrolling list. */
|
||||
.moduleBody:has(> [data-module="flight-plans"]) { display:flex; flex-direction:column; overflow:hidden; }
|
||||
[data-module="flight-plans"] { width:100%; max-width:none; flex:1; min-height:0; display:flex; flex-direction:column; }
|
||||
[data-module="flight-plans"] > .rid-module-feedback { flex:none; }
|
||||
[data-module="flight-plans"] > .rid-module-content { flex:1; min-height:0; display:flex; flex-direction:column; gap:12px; }
|
||||
[data-module="flight-plans"] .rid-module-toolbar { flex:none; margin:0; }
|
||||
[data-module="flight-plans"] .rid-module-editor:empty { display:none; }
|
||||
[data-module="flight-plans"] .rid-module-editor { flex:0 1 auto; min-height:0; max-height:65%; overflow:auto; }
|
||||
[data-module="flight-plans"] .rid-module-editor > :last-child { margin-bottom:0; }
|
||||
[data-module="flight-plans"] .planResults { flex:1; min-height:120px; display:flex; flex-direction:column; gap:10px; }
|
||||
.moduleBody [data-module="flight-plans"] .planResults > .dataTableWrap { flex:1; min-height:0; max-height:none; overflow:auto; }
|
||||
.moduleBody [data-module="flight-plans"] .planResults > .moduleEmpty { flex:1; min-height:0; display:grid; place-items:center; margin:0; }
|
||||
[data-module="flight-plans"] .planResults > .rid-pager { flex:none; margin:0; }
|
||||
[data-module="flight-plans"] .dataTable th { position:sticky; top:0; z-index:1; }
|
||||
@media (max-height:540px) {
|
||||
.moduleBody:has(> [data-module="flight-plans"]) { overflow:auto; }
|
||||
[data-module="flight-plans"] { flex:none; min-height:100%; }
|
||||
[data-module="flight-plans"] .rid-module-editor { flex:none; max-height:none; overflow:visible; }
|
||||
[data-module="flight-plans"] .planResults { flex:none; min-height:220px; }
|
||||
.moduleBody [data-module="flight-plans"] .planResults > .dataTableWrap { flex:none; max-height:50dvh; }
|
||||
}
|
||||
[data-module="flight-plans"] .rid-module-toolbar { padding:12px 14px; border:1px solid #29465c; border-radius:8px; background:#102438; }
|
||||
.flightPlanForm { width:100%; max-width:none; box-sizing:border-box; }
|
||||
[data-module="flight-plans"] .planSearch { flex:1 1 260px; width:auto; max-width:520px; }
|
||||
[data-module="flight-plans"] .rid-module-toolbar > label { display:flex; align-items:center; gap:8px; }
|
||||
[data-module="flight-plans"] .rid-module-toolbar select { width:auto; min-width:150px; }
|
||||
.planFormHeader { margin-bottom:18px; border-bottom:1px solid #29465c; padding-bottom:14px; }
|
||||
.planFormHeader h3 { margin:0 0 6px; font-size:16px; }
|
||||
.planFormHeader p,.planFieldGroup p { margin:0; font-size:12px; line-height:1.7; }
|
||||
.planEditorColumns { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:24px; }
|
||||
.planFieldGroup { min-width:0; }
|
||||
.planFieldGroup h4 { margin:0 0 14px; font-size:13px; font-weight:600; color:#c7e5f6; }
|
||||
.planFormGrid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px 14px; }
|
||||
.flightPlanForm label,.planReviewForm label { display:flex; min-width:0; flex-direction:column; gap:6px; margin-bottom:12px; font-size:13px; line-height:1.5; }
|
||||
.flightPlanForm :is(input,select),.planReviewForm select { width:100%; box-sizing:border-box; min-width:0; }
|
||||
.flightPlanForm textarea,.planReviewForm textarea { width:100%; box-sizing:border-box; padding:10px; border:1px solid #35566c; border-radius:6px; color:#d9e9f3; background:#091b2a; font:inherit; resize:vertical; }
|
||||
.flightPlanForm .btnrow,.planReviewForm .btnrow { display:flex; justify-content:flex-end; gap:8px; margin-top:18px; padding-top:14px; border-top:1px solid #29465c; }
|
||||
.moduleBody [data-module="flight-plans"] button[data-action="cancel-edit"],.moduleBody [data-module="flight-plans"] button[data-action="refresh-plans"] { background:#18324a; border:1px solid #365973; }
|
||||
.planDetails { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; }
|
||||
.planDetails dd { margin:0; } .planDetails pre,[data-module="flight-plans"] pre { white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||
[data-module="flight-plans"] .dataTable td:last-child { min-width:170px; }
|
||||
[data-module="flight-plans"] .smallBtn { margin:2px; }
|
||||
@media(max-width:1000px) { .planEditorColumns {grid-template-columns:1fr; gap:8px;} }
|
||||
@media(max-width:600px) { .planFormGrid {grid-template-columns:1fr; gap:0;} .planDetails {grid-template-columns:1fr;} [data-module="flight-plans"] .planSearch {max-width:none; flex-basis:100%; order:1;} }
|
||||
|
||||
/* The create/edit form lives in the browser top layer, without resizing the list. */
|
||||
.flightPlanDialog { width:min(1040px,calc(100vw - 40px)); max-width:none; max-height:calc(100dvh - 40px); box-sizing:border-box; margin:auto; padding:0; border:1px solid #365973; border-radius:12px; background:#0b1d2e; color:#d9e9f3; box-shadow:0 20px 70px #0008; overflow:auto; color-scheme:dark; }
|
||||
.flightPlanDialog::backdrop { background:rgba(2,10,18,.7); }
|
||||
.flightPlanDialog .flightPlanForm { margin:0; padding:24px; border:0; border-radius:0; background:none; }
|
||||
.flightPlanDialog .planFormHeader { position:relative; padding-right:42px; }
|
||||
.flightPlanDialog .planFormHeader h3 { font-size:18px; }
|
||||
.moduleBody .flightPlanDialog .planDialogClose { position:absolute; top:-6px; right:-6px; display:grid; place-items:center; width:32px; height:32px; padding:0; border:1px solid transparent; border-radius:6px; background:transparent; color:#bcd1e0; font-size:24px; font-weight:400; line-height:1; }
|
||||
.moduleBody .flightPlanDialog .planDialogClose:hover { background:#1a344a; color:#fff; }
|
||||
.flightPlanDialog .planDialogFeedback { margin-bottom:16px; }
|
||||
.flightPlanDialog:has(button[type="submit"]:disabled) :is(.planDialogClose,[data-action="cancel-edit"]) { opacity:.5; cursor:wait; }
|
||||
@media(max-width:600px) { .flightPlanDialog { width:calc(100vw - 24px); max-height:calc(100dvh - 24px); } .flightPlanDialog .flightPlanForm { padding:18px; } }
|
||||
@@ -0,0 +1,26 @@
|
||||
BSD 2-Clause License
|
||||
|
||||
Copyright (c) 2010-2023, Volodymyr Agafonkin
|
||||
Copyright (c) 2010-2011, CloudMade
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 696 B |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 618 B |
@@ -0,0 +1,661 @@
|
||||
/* required styles */
|
||||
|
||||
.leaflet-pane,
|
||||
.leaflet-tile,
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow,
|
||||
.leaflet-tile-container,
|
||||
.leaflet-pane > svg,
|
||||
.leaflet-pane > canvas,
|
||||
.leaflet-zoom-box,
|
||||
.leaflet-image-layer,
|
||||
.leaflet-layer {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
.leaflet-container {
|
||||
overflow: hidden;
|
||||
}
|
||||
.leaflet-tile,
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow {
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
/* Prevents IE11 from highlighting tiles in blue */
|
||||
.leaflet-tile::selection {
|
||||
background: transparent;
|
||||
}
|
||||
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
|
||||
.leaflet-safari .leaflet-tile {
|
||||
image-rendering: -webkit-optimize-contrast;
|
||||
}
|
||||
/* hack that prevents hw layers "stretching" when loading new tiles */
|
||||
.leaflet-safari .leaflet-tile-container {
|
||||
width: 1600px;
|
||||
height: 1600px;
|
||||
-webkit-transform-origin: 0 0;
|
||||
}
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow {
|
||||
display: block;
|
||||
}
|
||||
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
|
||||
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
|
||||
.leaflet-container .leaflet-overlay-pane svg {
|
||||
max-width: none !important;
|
||||
max-height: none !important;
|
||||
}
|
||||
.leaflet-container .leaflet-marker-pane img,
|
||||
.leaflet-container .leaflet-shadow-pane img,
|
||||
.leaflet-container .leaflet-tile-pane img,
|
||||
.leaflet-container img.leaflet-image-layer,
|
||||
.leaflet-container .leaflet-tile {
|
||||
max-width: none !important;
|
||||
max-height: none !important;
|
||||
width: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.leaflet-container img.leaflet-tile {
|
||||
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
|
||||
mix-blend-mode: plus-lighter;
|
||||
}
|
||||
|
||||
.leaflet-container.leaflet-touch-zoom {
|
||||
-ms-touch-action: pan-x pan-y;
|
||||
touch-action: pan-x pan-y;
|
||||
}
|
||||
.leaflet-container.leaflet-touch-drag {
|
||||
-ms-touch-action: pinch-zoom;
|
||||
/* Fallback for FF which doesn't support pinch-zoom */
|
||||
touch-action: none;
|
||||
touch-action: pinch-zoom;
|
||||
}
|
||||
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
|
||||
-ms-touch-action: none;
|
||||
touch-action: none;
|
||||
}
|
||||
.leaflet-container {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
.leaflet-container a {
|
||||
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
|
||||
}
|
||||
.leaflet-tile {
|
||||
filter: inherit;
|
||||
visibility: hidden;
|
||||
}
|
||||
.leaflet-tile-loaded {
|
||||
visibility: inherit;
|
||||
}
|
||||
.leaflet-zoom-box {
|
||||
width: 0;
|
||||
height: 0;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
z-index: 800;
|
||||
}
|
||||
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
|
||||
.leaflet-overlay-pane svg {
|
||||
-moz-user-select: none;
|
||||
}
|
||||
|
||||
.leaflet-pane { z-index: 400; }
|
||||
|
||||
.leaflet-tile-pane { z-index: 200; }
|
||||
.leaflet-overlay-pane { z-index: 400; }
|
||||
.leaflet-shadow-pane { z-index: 500; }
|
||||
.leaflet-marker-pane { z-index: 600; }
|
||||
.leaflet-tooltip-pane { z-index: 650; }
|
||||
.leaflet-popup-pane { z-index: 700; }
|
||||
|
||||
.leaflet-map-pane canvas { z-index: 100; }
|
||||
.leaflet-map-pane svg { z-index: 200; }
|
||||
|
||||
.leaflet-vml-shape {
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
.lvml {
|
||||
behavior: url(#default#VML);
|
||||
display: inline-block;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
|
||||
/* control positioning */
|
||||
|
||||
.leaflet-control {
|
||||
position: relative;
|
||||
z-index: 800;
|
||||
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
|
||||
pointer-events: auto;
|
||||
}
|
||||
.leaflet-top,
|
||||
.leaflet-bottom {
|
||||
position: absolute;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
}
|
||||
.leaflet-top {
|
||||
top: 0;
|
||||
}
|
||||
.leaflet-right {
|
||||
right: 0;
|
||||
}
|
||||
.leaflet-bottom {
|
||||
bottom: 0;
|
||||
}
|
||||
.leaflet-left {
|
||||
left: 0;
|
||||
}
|
||||
.leaflet-control {
|
||||
float: left;
|
||||
clear: both;
|
||||
}
|
||||
.leaflet-right .leaflet-control {
|
||||
float: right;
|
||||
}
|
||||
.leaflet-top .leaflet-control {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.leaflet-bottom .leaflet-control {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.leaflet-left .leaflet-control {
|
||||
margin-left: 10px;
|
||||
}
|
||||
.leaflet-right .leaflet-control {
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
|
||||
/* zoom and fade animations */
|
||||
|
||||
.leaflet-fade-anim .leaflet-popup {
|
||||
opacity: 0;
|
||||
-webkit-transition: opacity 0.2s linear;
|
||||
-moz-transition: opacity 0.2s linear;
|
||||
transition: opacity 0.2s linear;
|
||||
}
|
||||
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
|
||||
opacity: 1;
|
||||
}
|
||||
.leaflet-zoom-animated {
|
||||
-webkit-transform-origin: 0 0;
|
||||
-ms-transform-origin: 0 0;
|
||||
transform-origin: 0 0;
|
||||
}
|
||||
svg.leaflet-zoom-animated {
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.leaflet-zoom-anim .leaflet-zoom-animated {
|
||||
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
}
|
||||
.leaflet-zoom-anim .leaflet-tile,
|
||||
.leaflet-pan-anim .leaflet-tile {
|
||||
-webkit-transition: none;
|
||||
-moz-transition: none;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.leaflet-zoom-anim .leaflet-zoom-hide {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
|
||||
/* cursors */
|
||||
|
||||
.leaflet-interactive {
|
||||
cursor: pointer;
|
||||
}
|
||||
.leaflet-grab {
|
||||
cursor: -webkit-grab;
|
||||
cursor: -moz-grab;
|
||||
cursor: grab;
|
||||
}
|
||||
.leaflet-crosshair,
|
||||
.leaflet-crosshair .leaflet-interactive {
|
||||
cursor: crosshair;
|
||||
}
|
||||
.leaflet-popup-pane,
|
||||
.leaflet-control {
|
||||
cursor: auto;
|
||||
}
|
||||
.leaflet-dragging .leaflet-grab,
|
||||
.leaflet-dragging .leaflet-grab .leaflet-interactive,
|
||||
.leaflet-dragging .leaflet-marker-draggable {
|
||||
cursor: move;
|
||||
cursor: -webkit-grabbing;
|
||||
cursor: -moz-grabbing;
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
/* marker & overlays interactivity */
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow,
|
||||
.leaflet-image-layer,
|
||||
.leaflet-pane > svg path,
|
||||
.leaflet-tile-container {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.leaflet-marker-icon.leaflet-interactive,
|
||||
.leaflet-image-layer.leaflet-interactive,
|
||||
.leaflet-pane > svg path.leaflet-interactive,
|
||||
svg.leaflet-image-layer.leaflet-interactive path {
|
||||
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
/* visual tweaks */
|
||||
|
||||
.leaflet-container {
|
||||
background: #ddd;
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.leaflet-container a {
|
||||
color: #0078A8;
|
||||
}
|
||||
.leaflet-zoom-box {
|
||||
border: 2px dotted #38f;
|
||||
background: rgba(255,255,255,0.5);
|
||||
}
|
||||
|
||||
|
||||
/* general typography */
|
||||
.leaflet-container {
|
||||
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
|
||||
font-size: 12px;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
/* general toolbar styles */
|
||||
|
||||
.leaflet-bar {
|
||||
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.leaflet-bar a {
|
||||
background-color: #fff;
|
||||
border-bottom: 1px solid #ccc;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
line-height: 26px;
|
||||
display: block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
color: black;
|
||||
}
|
||||
.leaflet-bar a,
|
||||
.leaflet-control-layers-toggle {
|
||||
background-position: 50% 50%;
|
||||
background-repeat: no-repeat;
|
||||
display: block;
|
||||
}
|
||||
.leaflet-bar a:hover,
|
||||
.leaflet-bar a:focus {
|
||||
background-color: #f4f4f4;
|
||||
}
|
||||
.leaflet-bar a:first-child {
|
||||
border-top-left-radius: 4px;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
.leaflet-bar a:last-child {
|
||||
border-bottom-left-radius: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
border-bottom: none;
|
||||
}
|
||||
.leaflet-bar a.leaflet-disabled {
|
||||
cursor: default;
|
||||
background-color: #f4f4f4;
|
||||
color: #bbb;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-bar a {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.leaflet-touch .leaflet-bar a:first-child {
|
||||
border-top-left-radius: 2px;
|
||||
border-top-right-radius: 2px;
|
||||
}
|
||||
.leaflet-touch .leaflet-bar a:last-child {
|
||||
border-bottom-left-radius: 2px;
|
||||
border-bottom-right-radius: 2px;
|
||||
}
|
||||
|
||||
/* zoom control */
|
||||
|
||||
.leaflet-control-zoom-in,
|
||||
.leaflet-control-zoom-out {
|
||||
font: bold 18px 'Lucida Console', Monaco, monospace;
|
||||
text-indent: 1px;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
|
||||
/* layers control */
|
||||
|
||||
.leaflet-control-layers {
|
||||
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
|
||||
background: #fff;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.leaflet-control-layers-toggle {
|
||||
background-image: url(images/layers.png);
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.leaflet-retina .leaflet-control-layers-toggle {
|
||||
background-image: url(images/layers-2x.png);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
.leaflet-touch .leaflet-control-layers-toggle {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
}
|
||||
.leaflet-control-layers .leaflet-control-layers-list,
|
||||
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
|
||||
display: none;
|
||||
}
|
||||
.leaflet-control-layers-expanded .leaflet-control-layers-list {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
.leaflet-control-layers-expanded {
|
||||
padding: 6px 10px 6px 6px;
|
||||
color: #333;
|
||||
background: #fff;
|
||||
}
|
||||
.leaflet-control-layers-scrollbar {
|
||||
overflow-y: scroll;
|
||||
overflow-x: hidden;
|
||||
padding-right: 5px;
|
||||
}
|
||||
.leaflet-control-layers-selector {
|
||||
margin-top: 2px;
|
||||
position: relative;
|
||||
top: 1px;
|
||||
}
|
||||
.leaflet-control-layers label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-size: 1.08333em;
|
||||
}
|
||||
.leaflet-control-layers-separator {
|
||||
height: 0;
|
||||
border-top: 1px solid #ddd;
|
||||
margin: 5px -10px 5px -6px;
|
||||
}
|
||||
|
||||
/* Default icon URLs */
|
||||
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
|
||||
background-image: url(images/marker-icon.png);
|
||||
}
|
||||
|
||||
|
||||
/* attribution and scale controls */
|
||||
|
||||
.leaflet-container .leaflet-control-attribution {
|
||||
background: #fff;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
margin: 0;
|
||||
}
|
||||
.leaflet-control-attribution,
|
||||
.leaflet-control-scale-line {
|
||||
padding: 0 5px;
|
||||
color: #333;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.leaflet-control-attribution a {
|
||||
text-decoration: none;
|
||||
}
|
||||
.leaflet-control-attribution a:hover,
|
||||
.leaflet-control-attribution a:focus {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.leaflet-attribution-flag {
|
||||
display: inline !important;
|
||||
vertical-align: baseline !important;
|
||||
width: 1em;
|
||||
height: 0.6669em;
|
||||
}
|
||||
.leaflet-left .leaflet-control-scale {
|
||||
margin-left: 5px;
|
||||
}
|
||||
.leaflet-bottom .leaflet-control-scale {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.leaflet-control-scale-line {
|
||||
border: 2px solid #777;
|
||||
border-top: none;
|
||||
line-height: 1.1;
|
||||
padding: 2px 5px 1px;
|
||||
white-space: nowrap;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
text-shadow: 1px 1px #fff;
|
||||
}
|
||||
.leaflet-control-scale-line:not(:first-child) {
|
||||
border-top: 2px solid #777;
|
||||
border-bottom: none;
|
||||
margin-top: -2px;
|
||||
}
|
||||
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
|
||||
border-bottom: 2px solid #777;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-control-attribution,
|
||||
.leaflet-touch .leaflet-control-layers,
|
||||
.leaflet-touch .leaflet-bar {
|
||||
box-shadow: none;
|
||||
}
|
||||
.leaflet-touch .leaflet-control-layers,
|
||||
.leaflet-touch .leaflet-bar {
|
||||
border: 2px solid rgba(0,0,0,0.2);
|
||||
background-clip: padding-box;
|
||||
}
|
||||
|
||||
|
||||
/* popup */
|
||||
|
||||
.leaflet-popup {
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.leaflet-popup-content-wrapper {
|
||||
padding: 1px;
|
||||
text-align: left;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.leaflet-popup-content {
|
||||
margin: 13px 24px 13px 20px;
|
||||
line-height: 1.3;
|
||||
font-size: 13px;
|
||||
font-size: 1.08333em;
|
||||
min-height: 1px;
|
||||
}
|
||||
.leaflet-popup-content p {
|
||||
margin: 17px 0;
|
||||
margin: 1.3em 0;
|
||||
}
|
||||
.leaflet-popup-tip-container {
|
||||
width: 40px;
|
||||
height: 20px;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
margin-top: -1px;
|
||||
margin-left: -20px;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
.leaflet-popup-tip {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
padding: 1px;
|
||||
|
||||
margin: -10px auto 0;
|
||||
pointer-events: auto;
|
||||
|
||||
-webkit-transform: rotate(45deg);
|
||||
-moz-transform: rotate(45deg);
|
||||
-ms-transform: rotate(45deg);
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.leaflet-popup-content-wrapper,
|
||||
.leaflet-popup-tip {
|
||||
background: white;
|
||||
color: #333;
|
||||
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
|
||||
}
|
||||
.leaflet-container a.leaflet-popup-close-button {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
border: none;
|
||||
text-align: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font: 16px/24px Tahoma, Verdana, sans-serif;
|
||||
color: #757575;
|
||||
text-decoration: none;
|
||||
background: transparent;
|
||||
}
|
||||
.leaflet-container a.leaflet-popup-close-button:hover,
|
||||
.leaflet-container a.leaflet-popup-close-button:focus {
|
||||
color: #585858;
|
||||
}
|
||||
.leaflet-popup-scrolled {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.leaflet-oldie .leaflet-popup-content-wrapper {
|
||||
-ms-zoom: 1;
|
||||
}
|
||||
.leaflet-oldie .leaflet-popup-tip {
|
||||
width: 24px;
|
||||
margin: 0 auto;
|
||||
|
||||
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
|
||||
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
|
||||
}
|
||||
|
||||
.leaflet-oldie .leaflet-control-zoom,
|
||||
.leaflet-oldie .leaflet-control-layers,
|
||||
.leaflet-oldie .leaflet-popup-content-wrapper,
|
||||
.leaflet-oldie .leaflet-popup-tip {
|
||||
border: 1px solid #999;
|
||||
}
|
||||
|
||||
|
||||
/* div icon */
|
||||
|
||||
.leaflet-div-icon {
|
||||
background: #fff;
|
||||
border: 1px solid #666;
|
||||
}
|
||||
|
||||
|
||||
/* Tooltip */
|
||||
/* Base styles for the element that has a tooltip */
|
||||
.leaflet-tooltip {
|
||||
position: absolute;
|
||||
padding: 6px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #fff;
|
||||
border-radius: 3px;
|
||||
color: #222;
|
||||
white-space: nowrap;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
|
||||
}
|
||||
.leaflet-tooltip.leaflet-interactive {
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.leaflet-tooltip-top:before,
|
||||
.leaflet-tooltip-bottom:before,
|
||||
.leaflet-tooltip-left:before,
|
||||
.leaflet-tooltip-right:before {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
border: 6px solid transparent;
|
||||
background: transparent;
|
||||
content: "";
|
||||
}
|
||||
|
||||
/* Directions */
|
||||
|
||||
.leaflet-tooltip-bottom {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.leaflet-tooltip-top {
|
||||
margin-top: -6px;
|
||||
}
|
||||
.leaflet-tooltip-bottom:before,
|
||||
.leaflet-tooltip-top:before {
|
||||
left: 50%;
|
||||
margin-left: -6px;
|
||||
}
|
||||
.leaflet-tooltip-top:before {
|
||||
bottom: 0;
|
||||
margin-bottom: -12px;
|
||||
border-top-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-bottom:before {
|
||||
top: 0;
|
||||
margin-top: -12px;
|
||||
margin-left: -6px;
|
||||
border-bottom-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-left {
|
||||
margin-left: -6px;
|
||||
}
|
||||
.leaflet-tooltip-right {
|
||||
margin-left: 6px;
|
||||
}
|
||||
.leaflet-tooltip-left:before,
|
||||
.leaflet-tooltip-right:before {
|
||||
top: 50%;
|
||||
margin-top: -6px;
|
||||
}
|
||||
.leaflet-tooltip-left:before {
|
||||
right: 0;
|
||||
margin-right: -12px;
|
||||
border-left-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-right:before {
|
||||
left: 0;
|
||||
margin-left: -12px;
|
||||
border-right-color: #fff;
|
||||
}
|
||||
|
||||
/* Printing */
|
||||
|
||||
@media print {
|
||||
/* Prevent printers from removing background-images of controls. */
|
||||
.leaflet-control {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
|
||||
#liveMap3D {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
#liveMap3D[hidden],
|
||||
.rid-live-3d-marker[hidden],
|
||||
.rid-live-3d-height[hidden],
|
||||
.rid-live-3d-popup[hidden] { display: none; }
|
||||
.mapWrap[data-map-mode="3d"] #map { visibility: hidden; }
|
||||
.rid-live-3d-trails,
|
||||
.rid-live-3d-markers {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
.rid-live-3d-marker {
|
||||
position: absolute;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
transform: translate(-50%, -50%);
|
||||
outline-offset: 3px;
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rid-live-3d-height {
|
||||
position: absolute;
|
||||
left: calc(100% + 5px);
|
||||
top: 2px;
|
||||
padding: 3px 6px;
|
||||
border: 1px solid #74c4f484;
|
||||
border-radius: 5px;
|
||||
background: #071e32ed;
|
||||
color: #e5f8ff;
|
||||
font: 600 11px/1.4 system-ui, sans-serif;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.rid-live-3d-popup {
|
||||
position: absolute;
|
||||
transform: translate(-50%, calc(-100% - 20px));
|
||||
z-index: 2;
|
||||
padding: 12px 22px 12px 14px;
|
||||
width: max-content;
|
||||
max-width: min(310px, 100%);
|
||||
overflow-wrap: anywhere;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
color: #152537;
|
||||
box-shadow: 0 3px 15px #10202b75;
|
||||
font: 13px/1.4 system-ui, sans-serif;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.rid-live-3d-popup.below { transform: translate(-50%, 20px); }
|
||||
.rid-live-3d-popup button {
|
||||
position: absolute;
|
||||
right: 6px;
|
||||
top: 4px;
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #516476;
|
||||
box-shadow: none;
|
||||
}
|
||||
.mapWrap .zonePopupCard {
|
||||
min-width: 100px;
|
||||
color: #192e42;
|
||||
overflow-wrap: anywhere;
|
||||
font: 13px/1.5 system-ui, sans-serif;
|
||||
}
|
||||
.mapWrap .zonePopupCard strong { display: block; font-size: 14px; font-weight: 650; }
|
||||
.mapWrap .zonePopupMeta { margin-top: 3px; color: #4b6072; }
|
||||
.mapWrap .zoneMapPopup .maplibregl-popup-content {
|
||||
padding: 10px 29px 10px 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.mapWrap .zoneMapPopup .leaflet-popup-content { margin: 10px 29px 10px 12px; }
|
||||
.mapWrap .zoneMapPopup :is(.maplibregl-popup-close-button, .leaflet-popup-close-button) {
|
||||
padding: 0;
|
||||
color: #4b6072;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
font-size: 16px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
.mapWrap .zoneMapPopup :is(.maplibregl-popup-close-button, .leaflet-popup-close-button):hover {
|
||||
color: #192e42;
|
||||
background: #e7edf2;
|
||||
}
|
||||
#mapViewToggle[aria-pressed="true"] {
|
||||
border-color: #6bccff;
|
||||
background: #166b97;
|
||||
color: white;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
|
||||
import * as ml from '/vendor/maplibre-gl.mjs';
|
||||
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
|
||||
const COLLECTION = 'FeatureCollection';
|
||||
|
||||
function project(matrix, coordinate, width, height) {
|
||||
const {x, y, z} = coordinate;
|
||||
const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
|
||||
if (w <= 0) return null;
|
||||
return [
|
||||
(1 + (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w) * width / 2,
|
||||
(1 - (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w) * height / 2
|
||||
];
|
||||
}
|
||||
|
||||
export function openLiveMap(container, options) {
|
||||
const {center, zoom, basemap, onCamera, onError} = options;
|
||||
const map = new ml.Map({
|
||||
container, center, zoom: zoom - 1, pitch: options.pitch ?? 52, bearing: options.bearing ?? 0, maxPitch: 70, maxZoom: 17,
|
||||
renderWorldCopies: false, attributionControl: false,
|
||||
style: {
|
||||
version: 8,
|
||||
sources: {
|
||||
base: {type:'raster', tiles:[basemap.tiles], tileSize:256, maxzoom:18, attribution:'天地图 © 自然资源部'},
|
||||
labels: {type:'raster', tiles:[basemap.labels || basemap.tiles], tileSize:256, maxzoom:18},
|
||||
fences: {type:'geojson', data:{type:COLLECTION, features:[]}}
|
||||
},
|
||||
layers: [
|
||||
{id:'background', type:'background', paint:{'background-color':'#0a1827'}},
|
||||
{id:'base', type:'raster', source:'base'},
|
||||
{id:'labels', type:'raster', source:'labels', layout:{visibility:basemap.labels ? 'visible' : 'none'}},
|
||||
{id:'fences', type:'fill', source:'fences', paint:{'fill-color':'#ff536e','fill-opacity':0.18}},
|
||||
{id:'fence-outline', type:'line', source:'fences', paint:{'line-color':'#ff637a','line-width':2}}
|
||||
]
|
||||
}
|
||||
});
|
||||
map.addControl(new ml.NavigationControl(), 'bottom-left');
|
||||
map.addControl(new ml.AttributionControl({compact:true}), 'bottom-right');
|
||||
|
||||
const lines = document.createElement('canvas');
|
||||
lines.className = 'rid-live-3d-trails';
|
||||
lines.setAttribute('aria-hidden', 'true');
|
||||
const context = lines.getContext('2d');
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'rid-live-3d-markers';
|
||||
const popup = document.createElement('div');
|
||||
popup.className = 'rid-live-3d-popup';
|
||||
popup.hidden = true;
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.setAttribute('aria-label', '关闭地图详情');
|
||||
close.textContent = '×';
|
||||
const popupBody = document.createElement('div');
|
||||
popup.append(close, popupBody);
|
||||
overlay.append(popup);
|
||||
map.getCanvasContainer().append(lines, overlay);
|
||||
|
||||
let active = true;
|
||||
let updatingCamera = false;
|
||||
let selected = null;
|
||||
let projection;
|
||||
const zonePopup = new ml.Popup({closeButton:true, className:'zoneMapPopup', maxWidth:'260px'});
|
||||
let config = basemap;
|
||||
let fences = [];
|
||||
let entries = new Map();
|
||||
const elements = new Map();
|
||||
let trailPoints = new WeakMap();
|
||||
let trackCoords = options.trackCoords;
|
||||
|
||||
function closePopup() {
|
||||
selected = null;
|
||||
popup.hidden = true;
|
||||
map.triggerRepaint();
|
||||
}
|
||||
close.addEventListener('click', () => {
|
||||
const button = elements.get(selected)?.button;
|
||||
closePopup();
|
||||
button?.focus();
|
||||
});
|
||||
|
||||
function showTarget(id) {
|
||||
selected = id;
|
||||
map.triggerRepaint();
|
||||
}
|
||||
|
||||
function toGround(point) {
|
||||
return ml.MercatorCoordinate.fromLngLat(point);
|
||||
}
|
||||
|
||||
function toAir(point, height) {
|
||||
return ml.MercatorCoordinate.fromLngLat(point, Math.max(0, height ?? 0));
|
||||
}
|
||||
|
||||
function trailPoint(raw) {
|
||||
let point = trailPoints.get(raw);
|
||||
if (!point) {
|
||||
point = toAir(trackCoords(raw[0], raw[1]), raw[2]);
|
||||
trailPoints.set(raw, point);
|
||||
}
|
||||
return point;
|
||||
}
|
||||
|
||||
function markerFor(entry) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'rid-live-3d-marker';
|
||||
const visual = document.createElement('span');
|
||||
const height = document.createElement('span');
|
||||
height.className = 'rid-live-3d-height';
|
||||
button.append(visual, height);
|
||||
button.addEventListener('pointerdown', event => event.stopPropagation());
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
if (selected === entry.id) closePopup();
|
||||
else showTarget(entry.id);
|
||||
});
|
||||
overlay.append(button);
|
||||
return {button, visual, height, icon: null};
|
||||
}
|
||||
|
||||
function updateEntries(next) {
|
||||
entries = new Map();
|
||||
for (const entry of next) {
|
||||
entries.set(entry.id, {...entry, ground:toGround(entry.position), air:toAir(entry.position, entry.height),
|
||||
pilotGround:entry.pilot ? toGround(entry.pilot) : null});
|
||||
let element = elements.get(entry.id);
|
||||
if (!element) elements.set(entry.id, element = markerFor(entry));
|
||||
if (element.icon !== entry.icon) {
|
||||
element.visual.replaceChildren(entry.icon?.cloneNode(true) || document.createTextNode(entry.label[0]));
|
||||
element.icon = entry.icon;
|
||||
element.plane = element.visual.querySelector('.rid-drone-plane');
|
||||
}
|
||||
element.button.setAttribute('aria-label', entry.label);
|
||||
const value = entry.heightLabel || '';
|
||||
if (element.height.textContent !== value) element.height.textContent = value;
|
||||
element.height.hidden = !value;
|
||||
}
|
||||
for (const [id, element] of elements) {
|
||||
if (entries.has(id)) continue;
|
||||
element.button.remove();
|
||||
elements.delete(id);
|
||||
if (selected === id) closePopup();
|
||||
}
|
||||
map.triggerRepaint();
|
||||
}
|
||||
|
||||
function paint(matrix) {
|
||||
if (!active || !context || !matrix) return;
|
||||
const width = container.clientWidth;
|
||||
const height = container.clientHeight;
|
||||
if (!width || !height) return;
|
||||
projection = {matrix:matrix.slice(),width,height};
|
||||
const scale = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const pixelsWide = Math.round(width * scale);
|
||||
const pixelsHigh = Math.round(height * scale);
|
||||
if (lines.width !== pixelsWide || lines.height !== pixelsHigh) {
|
||||
lines.width = pixelsWide;
|
||||
lines.height = pixelsHigh;
|
||||
}
|
||||
context.setTransform(scale, 0, 0, scale, 0, 0);
|
||||
context.clearRect(0, 0, width, height);
|
||||
context.lineJoin = context.lineCap = 'round';
|
||||
let popupAnchor;
|
||||
const screen = coordinate => project(matrix, coordinate, width, height);
|
||||
for (const [id, entry] of entries) {
|
||||
const element = elements.get(id);
|
||||
const position = screen(entry.air);
|
||||
const visible = position && position[0] >= -32 && position[0] <= width + 32
|
||||
&& position[1] >= -30 && position[1] <= height + 30;
|
||||
element.button.hidden = !visible;
|
||||
if (visible) {
|
||||
element.button.style.left = position[0] + 'px';
|
||||
element.button.style.top = position[1] + 'px';
|
||||
if (element.plane && Number.isFinite(entry.heading)) {
|
||||
const angle = entry.heading * Math.PI / 180;
|
||||
const distance = 20 * entry.air.meterInMercatorCoordinateUnits();
|
||||
const ahead = screen({x:entry.air.x + Math.sin(angle) * distance,
|
||||
y:entry.air.y - Math.cos(angle) * distance, z:entry.air.z});
|
||||
if (ahead) {
|
||||
const screenAngle = Math.atan2(ahead[0] - position[0], position[1] - ahead[1]) * 180 / Math.PI;
|
||||
element.plane.style.transform = `rotate(${screenAngle}deg)`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (entry.trail) {
|
||||
context.beginPath();
|
||||
context.setLineDash([]);
|
||||
context.strokeStyle = entry.trailColor || '#43efa0';
|
||||
context.lineWidth = 2.5;
|
||||
let previous;
|
||||
for (const raw of entry.trail) {
|
||||
const point = screen(trailPoint(raw));
|
||||
if (!point) { previous = undefined; continue; }
|
||||
if (previous && !raw[3]) {
|
||||
context.lineTo(...point);
|
||||
} else {
|
||||
context.moveTo(...point);
|
||||
}
|
||||
previous = raw;
|
||||
}
|
||||
context.stroke();
|
||||
}
|
||||
if (entry.pilotGround && visible) {
|
||||
const pilot = screen(entry.pilotGround);
|
||||
if (pilot) {
|
||||
context.beginPath();
|
||||
context.strokeStyle = '#55d5ef';
|
||||
context.lineWidth = 1.5;
|
||||
context.setLineDash([5, 5]);
|
||||
context.moveTo(...pilot);
|
||||
context.lineTo(...position);
|
||||
context.stroke();
|
||||
}
|
||||
}
|
||||
if (entry.height > 0 && visible) {
|
||||
const ground = screen(entry.ground);
|
||||
if (ground) {
|
||||
context.beginPath();
|
||||
context.setLineDash([4, 4]);
|
||||
context.strokeStyle = '#a6e5ff';
|
||||
context.lineWidth = 1.5;
|
||||
context.moveTo(...ground);
|
||||
context.lineTo(...position);
|
||||
context.stroke();
|
||||
}
|
||||
}
|
||||
element.button.setAttribute('aria-expanded', String(selected === id));
|
||||
if (selected === id && visible) popupAnchor = [position, entry.popup];
|
||||
}
|
||||
popup.hidden = !popupAnchor;
|
||||
if (popupAnchor) {
|
||||
const [position, content] = popupAnchor;
|
||||
if (popupBody.dataset.content !== content) {
|
||||
popupBody.innerHTML = content;
|
||||
popupBody.dataset.content = content;
|
||||
}
|
||||
const half = Math.min(popup.offsetWidth / 2, width / 2);
|
||||
popup.style.left = Math.max(half, Math.min(width - half, position[0])) + 'px';
|
||||
popup.style.top = position[1] + 'px';
|
||||
popup.classList.toggle('below', position[1] < popup.offsetHeight + 30);
|
||||
}
|
||||
}
|
||||
|
||||
function applyStyle() {
|
||||
map.getSource('base')?.setTiles([config.tiles]);
|
||||
if (config.labels) map.getSource('labels')?.setTiles([config.labels]);
|
||||
if (map.getLayer('labels')) map.setLayoutProperty('labels','visibility', config.labels ? 'visible' : 'none');
|
||||
map.getSource('fences')?.setData({type:COLLECTION, features:fences});
|
||||
}
|
||||
|
||||
map.on('style.load', () => {
|
||||
applyStyle();
|
||||
map.addLayer({id:'rid-airspace', type:'custom', renderingMode:'3d', render(_gl, args) {
|
||||
paint(args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix);
|
||||
}});
|
||||
});
|
||||
map.on('moveend', () => {
|
||||
if (active && !updatingCamera) onCamera(map.getCenter(), map.getZoom() + 1);
|
||||
});
|
||||
map.on('click', event => {
|
||||
closePopup();
|
||||
if (!map.getLayer('fences')) return;
|
||||
const [zone] = map.queryRenderedFeatures(event.point, {layers:['fences']});
|
||||
if (zone) {
|
||||
zonePopup.setLngLat(event.lngLat)
|
||||
.setDOMContent(options.createZonePopupContent(zone.properties))
|
||||
.addTo(map);
|
||||
}
|
||||
});
|
||||
map.on('webglcontextlost', onError);
|
||||
|
||||
function resize() {
|
||||
if (!active) return;
|
||||
updatingCamera = true;
|
||||
try {
|
||||
map.resize();
|
||||
} finally {
|
||||
updatingCamera = false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getCamera: () => ({pitch:map.getPitch(), bearing:map.getBearing()}),
|
||||
showTarget,
|
||||
setActive(value) {
|
||||
active = value;
|
||||
if (!active) zonePopup.remove();
|
||||
resize();
|
||||
},
|
||||
resize,
|
||||
destroy: () => map.remove(),
|
||||
setView(center, zoom) {
|
||||
const current = map.getCenter();
|
||||
if (Math.abs(current.lng - center[0]) < 1e-8 && Math.abs(current.lat - center[1]) < 1e-8
|
||||
&& Math.abs(map.getZoom() - zoom + 1) < 1e-6) return;
|
||||
updatingCamera = true;
|
||||
try { map.jumpTo({center, zoom:zoom - 1}); } finally { updatingCamera = false; }
|
||||
},
|
||||
setBasemap(value) {
|
||||
if (config.tiles === value.tiles && config.labels === value.labels) return;
|
||||
if (config.tiles !== value.tiles) trailPoints = new WeakMap();
|
||||
config = value;
|
||||
applyStyle();
|
||||
},
|
||||
setFences(value) {
|
||||
fences = value;
|
||||
zonePopup.remove();
|
||||
map.getSource('fences')?.setData({type:COLLECTION, features:fences});
|
||||
},
|
||||
updateEntries,
|
||||
metrics() {
|
||||
const screen = coordinate => projection && project(projection.matrix, coordinate, projection.width, projection.height);
|
||||
return {camera:{pitch:map.getPitch(), bearing:map.getBearing(), zoom:map.getZoom()+1}, size:[lines.width,lines.height],
|
||||
positions:[...entries.values()].map(entry => ({
|
||||
id:entry.id, heading:entry.heading, height:entry.height, altitude:entry.air.toAltitude(),
|
||||
air:screen(entry.air), ground:screen(entry.ground),
|
||||
tail:entry.trail?.length ? screen(trailPoint(entry.trail.at(-1))) : null
|
||||
}))};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>登录 - RID侦测平台</title>
|
||||
<link rel="icon" href="/workbench/assets/rid-app.ico" type="image/x-icon">
|
||||
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
|
||||
<link rel="stylesheet" href="/workbench/platform.css">
|
||||
<link rel="stylesheet" href="/workbench/integration.css">
|
||||
</head>
|
||||
<body class="loginPage loginCenterMountain">
|
||||
<main class="centerLoginScene">
|
||||
<div class="centerLoginBg" aria-hidden="true"></div>
|
||||
<div class="centerLoginShade" aria-hidden="true"></div>
|
||||
<header class="centerLoginHeader">
|
||||
<div class="centerBrand">
|
||||
<img class="centerBrandMark" src="/workbench/assets/bsrid_logo_icon_light.png" alt="" width="46" height="46">
|
||||
<strong id="loginPlatformName">RID侦测平台</strong>
|
||||
</div>
|
||||
</header>
|
||||
<form class="centerLoginPanel">
|
||||
<div class="centerPanelHeading"><h1>平台登录</h1></div>
|
||||
<label class="centerField"><span>用户名</span><input id="username" autocomplete="username" placeholder="请输入用户名" required></label>
|
||||
<label class="centerField"><span>密码</span><input id="password" type="password" autocomplete="current-password" placeholder="请输入密码" required></label>
|
||||
<button type="submit" class="centerLoginSubmit"><span>登录</span></button>
|
||||
<div id="loginMsg" class="centerLoginMsg" role="alert"></div>
|
||||
<div class="centerLoginState" id="loginStatusText" aria-live="polite">正在检查本地账号</div>
|
||||
</form>
|
||||
<footer class="centerLoginFooter">© 2026 <span id="loginFooterName">RID侦测平台</span></footer>
|
||||
</main>
|
||||
<script src="/workbench/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,61 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
const status = document.getElementById('loginStatusText');
|
||||
|
||||
const form = document.querySelector('.centerLoginPanel');
|
||||
const button = form.querySelector('button');
|
||||
const buttonLabel = button.querySelector('span');
|
||||
const message = document.getElementById('loginMsg');
|
||||
const username = document.getElementById('username');
|
||||
const password = document.getElementById('password');
|
||||
let needsSetup = false;
|
||||
button.disabled = true;
|
||||
|
||||
async function prepare() {
|
||||
const response = await fetch('/api/auth/status', { cache: 'no-store' });
|
||||
if (!response.ok) throw new Error('无法读取本地服务状态');
|
||||
const account = await response.json();
|
||||
if (account.authenticated) return location.replace('/workbench/platform.html');
|
||||
needsSetup = !account.configured;
|
||||
buttonLabel.textContent = needsSetup ? '创建管理员' : '登录';
|
||||
password.autocomplete = needsSetup ? 'new-password' : 'current-password';
|
||||
password.minLength = needsSetup ? 10 : 0;
|
||||
status.textContent = needsSetup ? '首次运行,请设置管理员账号和至少 10 字符的密码' : '本地账号验证';
|
||||
button.disabled = false;
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
button.disabled = true;
|
||||
message.textContent = '';
|
||||
status.textContent = needsSetup ? '正在创建管理员' : '正在验证本地账号';
|
||||
try {
|
||||
const response = await fetch(`/api/auth/${needsSetup ? 'setup' : 'login'}`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: username.value.trim(), password: password.value })
|
||||
});
|
||||
password.value = '';
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) await prepare();
|
||||
throw new Error(data.error || '本地账号验证失败');
|
||||
}
|
||||
status.textContent = '认证通过,正在进入平台';
|
||||
location.replace('/workbench/platform.html');
|
||||
} catch (error) {
|
||||
message.textContent = error.message;
|
||||
status.textContent = '请检查后重试';
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
prepare().catch(error => { message.textContent = error.message; });
|
||||
fetch('/api/workbench/branding', { cache: 'no-store' })
|
||||
.then(response => response.ok ? response.json() : null)
|
||||
.then(branding => {
|
||||
if (!branding?.name) return;
|
||||
document.getElementById('loginPlatformName').textContent = branding.name;
|
||||
document.getElementById('loginFooterName').textContent = branding.name;
|
||||
document.title = `登录 - ${branding.name}`;
|
||||
})
|
||||
.catch(() => {});
|
||||
})();
|
||||
@@ -0,0 +1,127 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const nativeViews = Object.freeze({
|
||||
register: 'register', archives: 'archives', drones: 'target-lists',
|
||||
maps: 'maps', history: 'history', receivers: 'receivers'
|
||||
});
|
||||
const workbenchViews = new Map(Object.entries(nativeViews).map(([key, view]) => [view, key]));
|
||||
const container = document.getElementById('moduleEmbed');
|
||||
const content = document.getElementById('moduleBody');
|
||||
const status = document.getElementById('moduleEmbedStatus');
|
||||
const retry = document.getElementById('moduleEmbedRetry');
|
||||
|
||||
let frame;
|
||||
let pendingView = 'home';
|
||||
let pendingRecord;
|
||||
let ready = false;
|
||||
let timer;
|
||||
|
||||
function navigate(view) {
|
||||
if (ready) frame.contentWindow.postMessage({
|
||||
type: 'rid-embedded-navigate', view, record: view === 'history' ? pendingRecord : undefined,
|
||||
mapOptions: view === 'history' ? {
|
||||
basemap: document.getElementById('mapSourceSelect').value === 'tdt-vector' ? 'road' : 'imagery',
|
||||
labels: document.getElementById('labelToggle').checked
|
||||
} : undefined
|
||||
}, location.origin);
|
||||
}
|
||||
|
||||
function mount() {
|
||||
frame = document.createElement('iframe');
|
||||
frame.title = 'RID 业务模块';
|
||||
frame.hidden = true;
|
||||
frame.src = '/workbench/module.html';
|
||||
container.append(frame);
|
||||
}
|
||||
|
||||
function waiting() {
|
||||
status.textContent = '正在打开业务模块…';
|
||||
status.hidden = false;
|
||||
retry.hidden = true;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(async () => {
|
||||
if (ready || container.hidden) return;
|
||||
const account = await window.ridWorkbenchApi.request('/api/auth/status').catch(() => null);
|
||||
if (ready || container.hidden) return;
|
||||
if (account && !account.authenticated) return location.replace('/workbench/');
|
||||
status.textContent = '业务模块加载失败,请重试。';
|
||||
retry.hidden = false;
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
function hide() {
|
||||
pendingView = 'home';
|
||||
pendingRecord = undefined;
|
||||
container.hidden = true;
|
||||
content.hidden = false;
|
||||
clearTimeout(timer);
|
||||
navigate(pendingView);
|
||||
}
|
||||
|
||||
function show(name, record) {
|
||||
if (!Object.hasOwn(nativeViews, name)) {
|
||||
hide();
|
||||
return false;
|
||||
}
|
||||
pendingView = nativeViews[name];
|
||||
pendingRecord = name === 'history' && record ? {
|
||||
flightKey: record.flightKey, targetId: record.targetId, timeMs: record.timeMs, endMs: record.endMs
|
||||
} : undefined;
|
||||
content.hidden = true;
|
||||
container.hidden = false;
|
||||
if (!frame) mount();
|
||||
frame.title = document.getElementById('moduleTitle').textContent;
|
||||
if (ready) navigate(pendingView);
|
||||
else waiting();
|
||||
return true;
|
||||
}
|
||||
|
||||
retry.addEventListener('click', () => {
|
||||
frame.remove();
|
||||
ready = false;
|
||||
mount();
|
||||
frame.title = document.getElementById('moduleTitle').textContent;
|
||||
waiting();
|
||||
});
|
||||
|
||||
function returnToRecords() {
|
||||
if (pendingView !== 'history' || !pendingRecord) return false;
|
||||
const records = content.querySelector('[data-module="records"]');
|
||||
if (!records) return false;
|
||||
const key = pendingRecord.flightKey;
|
||||
window.showModuleHeading('records');
|
||||
hide();
|
||||
records.onRecordsReturn?.();
|
||||
records.querySelector('[data-action="record-play"][data-id="' + CSS.escape(key) + '"]')?.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
window.addEventListener('message', event => {
|
||||
if (event.origin !== location.origin || !frame || event.source !== frame.contentWindow) return;
|
||||
if (event.data?.type === 'rid-embedded-ready') {
|
||||
ready = true;
|
||||
clearTimeout(timer);
|
||||
status.hidden = retry.hidden = true;
|
||||
frame.hidden = false;
|
||||
navigate(pendingView);
|
||||
return;
|
||||
}
|
||||
if (!ready || container.hidden) return;
|
||||
if (event.data?.type === 'rid-embedded-return-records' && pendingView === 'history' && pendingRecord) {
|
||||
if (!returnToRecords()) window.openModule('records');
|
||||
return;
|
||||
}
|
||||
if (event.data?.type !== 'rid-embedded-view') return;
|
||||
const view = event.data.view;
|
||||
if (view === 'home') {
|
||||
window.closeModule();
|
||||
} else if (workbenchViews.has(view)) {
|
||||
pendingView = view;
|
||||
window.showModuleHeading(workbenchViews.get(view));
|
||||
frame.title = document.getElementById('moduleTitle').textContent;
|
||||
}
|
||||
});
|
||||
|
||||
window.ridModuleHost = Object.freeze({ show, hide, returnToRecords });
|
||||
})();
|
||||
@@ -0,0 +1,716 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const { request, modelRules, resolveModel, roleLabel } = window.ridWorkbenchApi;
|
||||
const workbench = '/api/workbench';
|
||||
const receiverPath = '/api/receivers';
|
||||
const userPath = '/api/auth/users';
|
||||
const limit = 50;
|
||||
const transportNames = { serial: 'USB 串口', udp: 'UDP 监听', 'tcp-listen': 'TCP 监听' };
|
||||
const receiverFormat = format => !format || format === 'raw' ? 'rid-device-json' : format;
|
||||
const stateNames = {
|
||||
stopped: '已停用', 'serial-open': '串口已打开', 'udp-listening': 'UDP 监听中',
|
||||
'tcp-listening': 'TCP 监听中', connecting: '正在连接', disconnected: '连接中断'
|
||||
};
|
||||
function receiverState(row) {
|
||||
const status = row.status;
|
||||
if (!row.config.enabled) return '已停用';
|
||||
if (status.lastError) return status.lastError;
|
||||
if (status.state === 'tcp-listening') {
|
||||
if (!status.lastDataMs || Date.now() - status.lastDataMs > 15000) return '监听中 · 等待数据';
|
||||
return '接收中';
|
||||
}
|
||||
return stateNames[status.state] || '待机';
|
||||
}
|
||||
function receiverTone(row) {
|
||||
const { state, lastError, lastDataMs } = row.status;
|
||||
if (!row.config.enabled) return 'neutral';
|
||||
if (lastError || state === 'disconnected') return 'danger';
|
||||
if (/^(serial-open|udp-listening|tcp-listening)$/.test(state) &&
|
||||
lastDataMs && Date.now() - lastDataMs <= 15000) return 'ok';
|
||||
return 'neutral';
|
||||
}
|
||||
function receiverSource(row) {
|
||||
return row.status.lastPeerIp || (row.config.peerIp ? '未收到 · 已配置 ' + row.config.peerIp : '—');
|
||||
}
|
||||
const alertNames = Object.fromEntries(Object.entries(window.ridFlightStatus.types).map(([key,value])=>[key,value.label]));
|
||||
|
||||
const column = (label, key) => ({ label, key });
|
||||
const cell = (label, render) => ({ label, render });
|
||||
const time = value => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—';
|
||||
const fixed = (value, digits) => Number.isFinite(value) ? value.toFixed(digits) : '—';
|
||||
const editorField = (label, control) => `<label>${label}${control}</label>`;
|
||||
const input = (name, value, props = '') =>
|
||||
`<input name="${name}" value="${escAttr(value)}" ${props}>`;
|
||||
const select = (name, entries, selected) => `<select name="${name}">${entries.map(([value, label]) =>
|
||||
`<option value="${escAttr(value)}" ${selected === value ? 'selected' : ''}>${esc(label)}</option>`
|
||||
).join('')}</select>`;
|
||||
const enabled = (name, value, label) =>
|
||||
`<label class="rid-check"><input type="checkbox" name="${name}" ${value ? 'checked' : ''}>${label}</label>`;
|
||||
const button = (label, action, id, danger = false) =>
|
||||
`<button type="button" class="smallBtn ${danger ? 'red' : ''}" data-action="${action}" data-id="${escAttr(id)}">${label}</button>`;
|
||||
const editorFooter = label => `<div class="btnrow"><button type="submit">${label}</button><button type="button" data-action="cancel-edit">取消</button></div>`;
|
||||
const toolbar = (left, right = '') => `<div class="rid-module-toolbar">${left}${right}</div>`;
|
||||
const section = (title, body) => `<section class="configGroup"><h3>${title}</h3>${body}</section>`;
|
||||
|
||||
const live = root => root.isConnected && activeModuleName === root.dataset.module;
|
||||
function feedback(root, message, error = false) {
|
||||
const el = root.querySelector('.flightPlanDialog[open] .planDialogFeedback') || root.querySelector('.rid-module-feedback');
|
||||
el.textContent = message;
|
||||
el.hidden = !message;
|
||||
el.classList.toggle('dangerText', error);
|
||||
}
|
||||
function run(root, control, operation) {
|
||||
if (!live(root) || control.disabled) return;
|
||||
control.disabled = true;
|
||||
feedback(root, '');
|
||||
Promise.resolve().then(operation).catch(error => {
|
||||
if (live(root)) feedback(root, error.message || '操作失败,请重试', true);
|
||||
}).finally(() => { control.disabled = false; });
|
||||
}
|
||||
function onForm(root, form, operation) {
|
||||
form.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
run(root, event.submitter || form.querySelector('button[type="submit"]'),
|
||||
() => operation(new FormData(form)));
|
||||
});
|
||||
}
|
||||
function onAction(root, action, operation) {
|
||||
for (const control of root.querySelectorAll(`[data-action="${action}"]`)) {
|
||||
control.onclick = () => run(root, control, () => operation(control.dataset.id, control));
|
||||
}
|
||||
}
|
||||
function editArea(root, body) {
|
||||
const pane = root.querySelector('.rid-module-editor');
|
||||
pane.innerHTML = body;
|
||||
if (body) pane.querySelector('input,select')?.focus();
|
||||
onAction(root, 'cancel-edit', () => editArea(root, ''));
|
||||
return pane.querySelector('form');
|
||||
}
|
||||
function body(root, html) {
|
||||
if (live(root)) root.querySelector('.rid-module-content').innerHTML = html;
|
||||
}
|
||||
|
||||
function managedTable(root, label, columns, rows, empty, pageSize = 20) {
|
||||
const offset = Math.min(root.pageOffset ?? 0, lastPageOffset(rows.length, pageSize));
|
||||
root.pageOffset = offset;
|
||||
return renderTable(columns, rows.slice(offset, offset + pageSize), empty)
|
||||
+ renderPager(label, offset, rows.length, pageSize);
|
||||
}
|
||||
|
||||
function bindManagedTable(root, reload) {
|
||||
bindPager(root, async (offset, direction) => {
|
||||
const previousOffset = root.pageOffset;
|
||||
root.pageOffset = offset;
|
||||
try {
|
||||
await reload();
|
||||
if (live(root)) {
|
||||
(root.querySelector(`[data-page-direction="${direction}"]:enabled`) || root.querySelector('.rid-page-number'))?.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
root.pageOffset = previousOffset;
|
||||
if (live(root)) feedback(root, error.message || '换页失败,请重试', true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function dates(withKeyword, right = '') {
|
||||
return `<form class="filterBar rid-period">
|
||||
${withKeyword ? editorField('关键字', input('q', '', 'maxlength="80" placeholder="UAS ID / 上报机型 / BSSID / 接收器"')) : ''}
|
||||
${editorField('开始时间', input('from', '', 'type="datetime-local" required'))}
|
||||
${editorField('结束时间', input('to', '', 'type="datetime-local" required'))}
|
||||
<button type="submit">查询</button>${right}
|
||||
</form><div class="moduleResult" aria-live="polite"></div>`;
|
||||
}
|
||||
|
||||
function dateForm(root, name) {
|
||||
const form = root.querySelector('.rid-period');
|
||||
const from = form.elements.from, to = form.elements.to;
|
||||
from.id = `${name}From`;
|
||||
to.id = `${name}To`;
|
||||
setDefaultModuleDates(from.id, to.id);
|
||||
return form;
|
||||
}
|
||||
|
||||
function period(values, offset = 0) {
|
||||
const fromMs = new Date(values.get('from')).getTime();
|
||||
const toMs = new Date(values.get('to')).getTime() + 59999;
|
||||
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || fromMs > toMs) {
|
||||
throw new Error('请选择有效的开始和结束时间');
|
||||
}
|
||||
return new URLSearchParams({ fromMs, toMs, offset, limit, q: (values.get('q') || '').trim() });
|
||||
}
|
||||
|
||||
async function records(root) {
|
||||
body(root, dates(true));
|
||||
const form = dateForm(root, 'record');
|
||||
const result = root.querySelector('.moduleResult');
|
||||
let values = new FormData(form);
|
||||
let generation = 0;
|
||||
let refreshTimer;
|
||||
const query = (offset, activeRows) => {
|
||||
const params = period(values, offset);
|
||||
if (activeRows) {
|
||||
params.delete('q');
|
||||
params.set('flightKeys', activeRows.map(row => row.flightKey).join(','));
|
||||
}
|
||||
return request(`${workbench}/observations?${params}`);
|
||||
};
|
||||
const details = rules => [
|
||||
['UAS ID', row => row.targetId],
|
||||
['机型', row => resolveModel(row.targetId, row.model, rules) || '—'],
|
||||
['飞行状态', row => (row.flightStatuses?.length ? row.flightStatuses : ['unknown']).map(code=>window.ridFlightStatus.meta(code).label).join(' · ')],
|
||||
['开始时间', row => time(row.timeMs)],
|
||||
['结束时间', row => row.endMs == null ? '接收中' : time(row.endMs)],
|
||||
['BSSID', row => row.bssid || '—'],
|
||||
['RSSI / dBm', row => fixed(row.rssi, 1)],
|
||||
['高度 / m', row => fixed(row.altitudeM, 1)],
|
||||
['速度 / m/s', row => fixed(row.speedMps, 1)],
|
||||
['坐标', row => Number.isFinite(row.latitude) && Number.isFinite(row.longitude)
|
||||
? fixed(row.latitude, 6) + ', ' + fixed(row.longitude, 6) : '—'],
|
||||
['接收器', row => row.receiverId || '—']
|
||||
];
|
||||
|
||||
function refreshActiveRows(current, activeRows, columns) {
|
||||
clearTimeout(refreshTimer);
|
||||
if (!activeRows.size) return;
|
||||
refreshTimer = setTimeout(async () => {
|
||||
if (!live(root) || current !== generation) return;
|
||||
try {
|
||||
const data = await query(0, [...activeRows.values()].map(entry => entry.row));
|
||||
if (!live(root) || current !== generation) return;
|
||||
for (const row of data.entries) {
|
||||
const entry = activeRows.get(row.flightKey);
|
||||
if (!entry) continue;
|
||||
columns.forEach(([label, read], index) => {
|
||||
if (label === '飞行状态') {
|
||||
entry.cells[index].innerHTML = window.ridFlightStatus.tags(row.flightStatuses);
|
||||
return;
|
||||
}
|
||||
const value = read(row);
|
||||
if (entry.cells[index].textContent !== value) entry.cells[index].textContent = value;
|
||||
});
|
||||
Object.assign(entry.row, row);
|
||||
if (row.endMs != null) activeRows.delete(row.flightKey);
|
||||
}
|
||||
} catch {
|
||||
if (!live(root) || current !== generation) return;
|
||||
}
|
||||
refreshActiveRows(current, activeRows, columns);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
async function load(offset, focusAction) {
|
||||
clearTimeout(refreshTimer);
|
||||
const current = ++generation;
|
||||
result.innerHTML = '<div class="moduleEmpty">正在查询接收记录…</div>';
|
||||
try {
|
||||
const [page, rules] = await Promise.all([query(offset), modelRules().catch(() => [])]);
|
||||
if (!live(root) || current !== generation) return;
|
||||
const rows = page.entries;
|
||||
const columns = details(rules);
|
||||
const cols = [...columns.map(([label, read]) => cell(label, row => label==='飞行状态'?window.ridFlightStatus.tags(row.flightStatuses):esc(read(row)))),
|
||||
cell('操作', row => button('回放轨迹', 'record-play', row.flightKey))];
|
||||
const lastOffset = lastPageOffset(page.total, limit);
|
||||
if (offset > lastOffset) return load(lastOffset, focusAction);
|
||||
result.innerHTML = `<div class="resultCount">共 ${page.total} 条记录</div>
|
||||
${renderTable(cols, rows, '该时段无接收记录')}
|
||||
${renderPager('记录分页', offset, page.total, limit)}`;
|
||||
const activeRows = new Map();
|
||||
const recordsByKey = new Map();
|
||||
const visibleRows = result.querySelectorAll('tbody tr');
|
||||
rows.forEach((row, index) => {
|
||||
const tr = visibleRows[index];
|
||||
tr.querySelector('[data-action="record-play"]').setAttribute('aria-label', row.targetId + ' 的轨迹回放');
|
||||
recordsByKey.set(row.flightKey, row);
|
||||
if (row.endMs == null) activeRows.set(row.flightKey, {row, cells: tr.cells});
|
||||
});
|
||||
onAction(root, 'record-play', key => openModule('history', recordsByKey.get(key)));
|
||||
root.onRecordsReturn = () => refreshActiveRows(current, activeRows, columns);
|
||||
refreshActiveRows(current, activeRows, columns);
|
||||
bindPager(result, (next, direction) => load(next, direction).catch(error => {
|
||||
if (live(root)) feedback(root, error.message || '换页失败,请重试', true);
|
||||
}), focusAction);
|
||||
} catch (error) {
|
||||
if (live(root) && current === generation) result.innerHTML = '<div class="moduleEmpty">查询未完成,可调整条件后重试。</div>';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
onForm(root, form, async data => { values = data; await load(0); });
|
||||
await load(0);
|
||||
}
|
||||
|
||||
async function rankings(root) {
|
||||
body(root, dates(false));
|
||||
const form = dateForm(root, 'rank');
|
||||
const result = root.querySelector('.moduleResult');
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const trackStats = request('/api/history/summary?fromMs=' + today.getTime()).catch(() => null);
|
||||
async function load(values) {
|
||||
const params = period(values);
|
||||
result.innerHTML = '<div class="moduleEmpty">正在统计…</div>';
|
||||
try {
|
||||
const [targets, models, receivers, alarms, devices, tracks, flightStates] = await Promise.all([
|
||||
...['target', 'model', 'receiver'].map(dim => request(`${workbench}/rankings?${params}&dimension=${dim}`)),
|
||||
request(`/api/monitoring/rankings?${params}`),
|
||||
request(receiverPath),
|
||||
trackStats,
|
||||
request(`${workbench}/rankings?${params}&dimension=flight_status`)
|
||||
]);
|
||||
if (!live(root)) return;
|
||||
const names = new Map(devices.receivers.map(item => [item.id, item.name]));
|
||||
const rows = (data, labels) => data.entries.map((row, index) => ({
|
||||
...row, rank: index + 1, name: labels?.get(row.name) || row.name
|
||||
}));
|
||||
const groups = [
|
||||
['目标排行', rows(targets)], ['上报机型排行', rows(models)],
|
||||
['设备 / 链路贡献', rows(receivers, names)],
|
||||
['告警类型', rows(alarms, new Map(Object.entries(alertNames))), '次数'],
|
||||
['飞行状态(本次最高告警级别)', rows(flightStates, new Map(Object.entries(alertNames))), '飞行次数']
|
||||
];
|
||||
result.innerHTML = `${tracks ? `<p class="resultCount">今日轨迹点 ${Number(tracks.since).toLocaleString('zh-CN')} · 累计 ${Number(tracks.total).toLocaleString('zh-CN')}</p>` : ''}
|
||||
<div class="moduleSplit">${groups.map(([label]) => `<section><h3>${label}</h3><div></div></section>`).join('')}</div>`;
|
||||
result.querySelectorAll('.moduleSplit section > div').forEach((table, index) => {
|
||||
const [label, ranking, countLabel = '接收记录'] = groups[index];
|
||||
const pageSize = 10;
|
||||
const cols = [column('名次', 'rank'), column('名称', 'name'), column(countLabel, 'count')];
|
||||
function display(offset, direction) {
|
||||
table.innerHTML = renderTable(cols, ranking.slice(offset, offset + pageSize), '该时段无统计数据')
|
||||
+ (ranking.length > pageSize ? renderPager(label + '分页', offset, ranking.length, pageSize) : '');
|
||||
bindPager(table, display, direction);
|
||||
}
|
||||
display(0);
|
||||
});
|
||||
} catch (error) {
|
||||
if (live(root)) result.innerHTML = '<div class="moduleEmpty">统计未完成,可重新查询。</div>';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
onForm(root, form, load);
|
||||
await load(new FormData(form));
|
||||
}
|
||||
|
||||
async function settings(root, admin) {
|
||||
const current = await request(`${workbench}/settings`);
|
||||
if (!live(root)) return;
|
||||
body(root, section('平台信息与告警', `<form class="rid-admin-form rid-config-form">
|
||||
<fieldset ${admin ? '' : 'disabled'}>
|
||||
${editorField('平台名称', input('name', current.name, 'required maxlength="60"'))}
|
||||
<div class="rid-config-options">
|
||||
${enabled('sound', current.sound, '声音报警')}
|
||||
${enabled('flash', current.flash, '告警闪屏')}
|
||||
</div>
|
||||
${editorField('告警闪屏时长(秒)', input('flashSeconds', current.flashSeconds ?? 10, 'type="number" min="1" max="60" step="1" required'))}
|
||||
${admin ? '<button type="submit">保存平台设置</button>' : ''}
|
||||
</fieldset>
|
||||
</form>`));
|
||||
if (!admin) return;
|
||||
let savedSettings = current;
|
||||
const configForm = root.querySelector('.rid-config-form');
|
||||
onForm(root, configForm, async data => {
|
||||
savedSettings = await request(`${workbench}/settings`, 'PUT', {
|
||||
...savedSettings, name: data.get('name'),
|
||||
sound: data.has('sound'), flash: data.has('flash'), flashSeconds: Number(data.get('flashSeconds'))
|
||||
});
|
||||
if (!live(root)) return;
|
||||
configForm.elements.name.value = savedSettings.name;
|
||||
applyPlatformSettings(savedSettings);
|
||||
feedback(root, '平台设置已保存。');
|
||||
});
|
||||
}
|
||||
|
||||
const deviceListKey = data => JSON.stringify([data.receivers.map(row => row.id), data.discovery]);
|
||||
const deviceEditorOpen = root => root.querySelector('.rid-module-editor form, button[data-action]:disabled');
|
||||
|
||||
function refreshReceiverStatus(root, rows) {
|
||||
const byId = new Map(rows.map(row => [row.id, row]));
|
||||
for (const source of root.querySelectorAll('[data-rx-source]')) {
|
||||
const row = byId.get(source.dataset.rxSource);
|
||||
const tableRow = source.closest('tr');
|
||||
if (!row || !tableRow) continue;
|
||||
const status = tableRow.querySelector('[data-rx-status]');
|
||||
for (const [cell, value] of [[source, receiverSource(row)], [status, receiverState(row)],
|
||||
[tableRow.querySelector('[data-rx-time]'), time(row.status.lastDataMs)]]) {
|
||||
if (cell.textContent !== value) cell.textContent = value;
|
||||
}
|
||||
status.className = 'stateTag ' + receiverTone(row);
|
||||
}
|
||||
}
|
||||
|
||||
function watchDevices(root, admin) {
|
||||
async function poll() {
|
||||
if (!live(root)) return;
|
||||
try {
|
||||
if (document.hidden || deviceEditorOpen(root)) return;
|
||||
const data = await request(receiverPath);
|
||||
if (live(root) && !deviceEditorOpen(root)) {
|
||||
if (deviceListKey(data) !== root.receiverListKey) await devices(root, admin, '', data);
|
||||
else refreshReceiverStatus(root, data.receivers);
|
||||
}
|
||||
} catch (_) {
|
||||
// The next poll or a manual refresh can recover from a temporary failure.
|
||||
} finally {
|
||||
if (live(root)) setTimeout(poll, 2000);
|
||||
}
|
||||
}
|
||||
setTimeout(poll, 2000);
|
||||
}
|
||||
|
||||
async function devices(root, admin, notice = '', snapshot) {
|
||||
const [data, ports] = await Promise.all([
|
||||
snapshot || request(receiverPath), admin ? request('/api/receiver/ports') : { ports: [] }
|
||||
]);
|
||||
if (!live(root) || (snapshot && deviceEditorOpen(root))) return;
|
||||
const focused = snapshot && root.contains(document.activeElement) ? document.activeElement.dataset : null;
|
||||
root.receiverListKey = deviceListKey(data);
|
||||
const discovery = (data.discovery || []).map(entry => {
|
||||
const state = entry.error || (entry.listening ? '监听中 · 等待新设备' : '正在启动');
|
||||
return toolbar('<span>TCP 自动登记入口 <strong>' + esc(entry.endpoint) + '</strong> · ' +
|
||||
esc(state) + '</span>', admin ? button('取消保留', 'disable-discovery', entry.endpoint) : '');
|
||||
}).join('');
|
||||
body(root, toolbar(admin ? button('新增接收器', 'add-rx', '') : '',
|
||||
button('刷新', 'refresh-rx', '') + '<span class="muted">TCP 监听开启后,有效报文会自动登记新设备。</span>') +
|
||||
discovery + '<div class="rid-module-editor"></div>' +
|
||||
`<div class="resultCount">共 ${data.receivers.length} 台 / 32 台</div>` +
|
||||
managedTable(root, '接收器列表分页', [
|
||||
cell('设备名称', r => esc(r.name) + (r.networkDiscovered ? ' <small class="muted">自动登记</small>' : '')),
|
||||
cell('标识', r => esc(r.hardwareId || r.id)),
|
||||
cell('接入方式', r => esc(transportNames[r.config.transport])),
|
||||
cell('接收端点', r => esc(r.config.transport === 'serial' ? r.config.serialPort :
|
||||
`${r.config.bindIp}:${r.config.port}`)),
|
||||
cell('来源 IP', r => '<span data-rx-source="' + escAttr(r.id) + '">' + esc(receiverSource(r)) + '</span>'),
|
||||
cell('安装位置', r => esc(r.location ?? r.devicePlace)),
|
||||
column('备注', 'note'),
|
||||
cell('状态', r => '<span data-rx-status class="stateTag ' + receiverTone(r) + '">' + esc(receiverState(r)) + '</span>'),
|
||||
cell('最后接收', r => '<span data-rx-time>' + esc(time(r.status.lastDataMs)) + '</span>'),
|
||||
...(admin ? [cell('操作', r => button('编辑', 'edit-rx', r.id) + button(r.config.enabled ? '停用' : '启用', 'toggle-rx', r.id) +
|
||||
button('删除', 'delete-rx', r.id, true))] : [])
|
||||
], data.receivers, '暂无接收器', 12));
|
||||
bindManagedTable(root, () => devices(root, admin));
|
||||
if (focused?.action) {
|
||||
const action = CSS.escape(focused.action);
|
||||
const id = CSS.escape(focused.id ?? '');
|
||||
root.querySelector(`[data-action="${action}"][data-id="${id}"]`)?.focus({preventScroll:true});
|
||||
}
|
||||
feedback(root, data.error || notice, Boolean(data.error));
|
||||
onAction(root, 'refresh-rx', () => devices(root, admin));
|
||||
onAction(root, 'disable-discovery', async endpoint => {
|
||||
if (!confirm('取消保留 ' + endpoint + '?该端点没有启用的接收器时会停止监听。')) return;
|
||||
await request('/api/receiver/discovery', 'PUT', { endpoint, enabled: false });
|
||||
if (live(root)) await devices(root, admin, '已取消保留此 TCP 入口。');
|
||||
});
|
||||
const edit = item => {
|
||||
const c = item?.config || { transport: 'serial', format: 'rid-device-json', uidIdentity: 'source-scoped', baudRate: 115200, bindIp: '127.0.0.1', port: 8788 };
|
||||
const portList = `<datalist id="rid-board-ports">${ports.ports.map(port => `<option value="${escAttr(port)}"></option>`).join('')}</datalist>`;
|
||||
const form = editArea(root, section(item ? '编辑接收器' : '新增接收器', `<form class="rid-admin-form">
|
||||
${editorField('设备名称', input('name', item?.name, 'required maxlength="120"'))}
|
||||
${editorField('接入方式', select('transport', Object.entries(transportNames), c.transport))}
|
||||
<div data-rx-group="serial" class="rid-admin-fields">
|
||||
${editorField('COM 串口', input('serialPort', c.serialPort, 'list="rid-board-ports" maxlength="12"'))}
|
||||
${editorField('波特率', input('baudRate', c.baudRate, 'type="number" min="1200" max="4000000" required'))}
|
||||
</div>
|
||||
<div data-rx-group="network" class="rid-admin-fields">
|
||||
${editorField('监听 IP(本机网卡地址)', input('bindIp', c.bindIp, 'required maxlength="45"'))}
|
||||
${editorField('监听端口', input('port', c.port, 'type="number" min="1" max="65535" required'))}
|
||||
</div>
|
||||
<div data-rx-group="peer">
|
||||
${editorField('允许来源 IP(设备地址,可留空)', input('peerIp', c.peerIp, 'maxlength="45" placeholder="例如 192.168.1.200"'))}
|
||||
</div>
|
||||
<div data-rx-group="identity">
|
||||
${editorField('UID 归并', select('uidIdentity', [['source-scoped', '按接收源区分'], ['global-device', '按设备 UID 合并']], c.uidIdentity))}
|
||||
</div>
|
||||
${editorField('安装位置', input('location', item?.location ?? item?.devicePlace, 'maxlength="160"'))}
|
||||
${editorField('备注', input('note', item?.note, 'maxlength="160"'))}
|
||||
${enabled('enabled', c.enabled, '立即启用')}
|
||||
${portList}${editorFooter('保存设备')}
|
||||
</form>`));
|
||||
const toggleFields = () => {
|
||||
const transport = form.elements.transport.value;
|
||||
const serial = transport === 'serial';
|
||||
const uid = c.format === 'uid-json';
|
||||
for (const [group, visible] of [['serial', serial], ['network', !serial], ['peer', transport === 'tcp-listen'], ['identity', uid]]) {
|
||||
const scope = form.querySelector(`[data-rx-group="${group}"]`);
|
||||
scope.hidden = !visible;
|
||||
scope.querySelectorAll('input,select').forEach(control => { control.disabled = !visible; });
|
||||
}
|
||||
};
|
||||
form.elements.transport.onchange = toggleFields;
|
||||
toggleFields();
|
||||
onForm(root, form, async values => {
|
||||
const config = { ...c, enabled: values.has('enabled'), transport: values.get('transport'), format: receiverFormat(c.format) };
|
||||
if (values.has('serialPort')) {
|
||||
config.serialPort = values.get('serialPort').trim().toUpperCase();
|
||||
config.baudRate = Number(values.get('baudRate'));
|
||||
} else {
|
||||
config.bindIp = values.get('bindIp').trim();
|
||||
config.port = Number(values.get('port'));
|
||||
}
|
||||
config.peerIp = values.get('peerIp')?.trim() || null;
|
||||
if (values.has('uidIdentity')) config.uidIdentity = values.get('uidIdentity');
|
||||
await request(item ? `${receiverPath}/${encodeURIComponent(item.id)}` : receiverPath, item ? 'PUT' : 'POST', {
|
||||
name: values.get('name').trim(), config, location: values.get('location'), note: values.get('note')
|
||||
});
|
||||
if (live(root)) await devices(root, admin, '设备已保存。');
|
||||
});
|
||||
};
|
||||
const find = id => data.receivers.find(item => item.id === id);
|
||||
onAction(root, 'add-rx', () => edit(null));
|
||||
onAction(root, 'edit-rx', id => edit(find(id)));
|
||||
onAction(root, 'toggle-rx', async id => {
|
||||
const path = `${receiverPath}/${encodeURIComponent(id)}`;
|
||||
const item = await request(path);
|
||||
const config = { ...item.config, enabled: !item.config.enabled };
|
||||
if (config.enabled) config.format = receiverFormat(config.format);
|
||||
await request(path, 'PUT', { name: item.name, config });
|
||||
if (live(root)) await devices(root, admin, item.config.enabled ? '接收器已停用。' : '已保存启用设置,实际接收状态见下方。');
|
||||
});
|
||||
onAction(root, 'delete-rx', async id => {
|
||||
const receiver = find(id);
|
||||
const consequence = receiver.status.state === 'tcp-listening' && receiver.config.format === 'rid-device-json'
|
||||
? ' TCP 入口会继续接收,设备重新推送有效数据时会再次登记。' : '';
|
||||
if (!confirm('删除接收器「' + receiver.name + '」?已保存的接收记录会保留。' + consequence)) return;
|
||||
await request(`${receiverPath}/${encodeURIComponent(id)}`, 'DELETE');
|
||||
if (live(root)) await devices(root, admin, '设备已删除。');
|
||||
});
|
||||
}
|
||||
|
||||
const modelFields = [['serial', 'SN 前缀'], ['target', 'UAS ID'], ['model', '上报机型']];
|
||||
const modelFieldNames = Object.fromEntries(modelFields);
|
||||
|
||||
async function models(root, admin, notice = '') {
|
||||
const entries = await modelRules(true);
|
||||
if (!live(root)) return;
|
||||
body(root, toolbar(admin ? button('新增型号规则', 'add-model', '') : '',
|
||||
'<span>SN 从首位匹配,忽略大小写。多个前缀命中时取最长的一条。</span>') +
|
||||
'<div class="rid-module-editor"></div>' +
|
||||
'<div class="resultCount">共 ' + entries.length + ' 条规则</div>' +
|
||||
managedTable(root, '型号库分页', [
|
||||
cell('匹配字段', r => esc(modelFieldNames[r.field] || r.field)),
|
||||
column('关键字', 'pattern'), column('厂商', 'vendor'), column('机型', 'model'), column('备注', 'note'),
|
||||
cell('状态', r => r.enabled ? '<span class="stateTag ok">已启用</span>' : '<span class="stateTag neutral">已停用</span>'),
|
||||
...(admin ? [cell('操作', r => button('编辑', 'edit-model', r.id) + button('删除', 'delete-model', r.id, true))] : [])
|
||||
], entries, '暂无本地型号规则'));
|
||||
bindManagedTable(root, () => models(root, admin));
|
||||
feedback(root, notice);
|
||||
const edit = item => {
|
||||
const form = editArea(root, section(item ? '编辑型号规则' : '新增型号规则', `<form class="rid-admin-form">
|
||||
${editorField('匹配字段', select('field', modelFields, item?.field || 'serial'))}
|
||||
${editorField('前缀 / 关键字', input('pattern', item?.pattern, 'required maxlength="80"'))}
|
||||
${editorField('厂商', input('vendor', item?.vendor, 'maxlength="60"'))}
|
||||
${editorField('显示机型', input('model', item?.model, 'required maxlength="80"'))}
|
||||
${editorField('备注', input('note', item?.note, 'maxlength="200"'))}
|
||||
${enabled('enabled', item?.enabled ?? true, '启用规则')}${editorFooter('保存规则')}
|
||||
</form>`));
|
||||
onForm(root, form, async values => {
|
||||
const data = Object.fromEntries(values);
|
||||
data.enabled = values.has('enabled');
|
||||
await request(`${workbench}/models${item ? '/' + item.id : ''}`, item ? 'PUT' : 'POST', data);
|
||||
if (live(root)) await models(root, admin, '型号规则已保存。');
|
||||
});
|
||||
};
|
||||
onAction(root, 'add-model', () => edit(null));
|
||||
onAction(root, 'edit-model', id => edit(entries.find(item => item.id === Number(id))));
|
||||
onAction(root, 'delete-model', async id => {
|
||||
if (!confirm('删除这条型号规则?')) return;
|
||||
await request(`${workbench}/models/${id}`, 'DELETE');
|
||||
if (live(root)) await models(root, admin, '型号规则已删除。');
|
||||
});
|
||||
}
|
||||
|
||||
async function users(root, admin, notice = '') {
|
||||
if (!admin) {
|
||||
body(root, '<div class="moduleEmpty">仅管理员可管理用户。</div>');
|
||||
return;
|
||||
}
|
||||
const { entries } = await request(userPath);
|
||||
if (!live(root)) return;
|
||||
body(root, toolbar(button('新增用户', 'add-user', '')) +
|
||||
'<div class="rid-module-editor"></div>' +
|
||||
`<div class="resultCount">共 ${entries.length} 个账号</div>` +
|
||||
managedTable(root, '用户管理分页', [
|
||||
column('用户名', 'username'), cell('角色', r => esc(roleLabel(r.role))),
|
||||
cell('状态', r => r.enabled ? '启用' : '停用'),
|
||||
cell('操作', r => r.id === 0 ? '初始管理员' : button('编辑', 'edit-user', r.id) + button('删除', 'delete-user', r.id, true))
|
||||
], entries));
|
||||
bindManagedTable(root, () => users(root, admin));
|
||||
feedback(root, notice);
|
||||
const edit = item => {
|
||||
const form = editArea(root, section(item ? '编辑用户' : '新增用户', `<form class="rid-admin-form">
|
||||
${editorField('用户名', input('username', item?.username, item ? 'readonly' : 'required maxlength="40" autocomplete="off"'))}
|
||||
${editorField(item ? '新密码(留空保留原密码)' : '密码', input('password', '', `type="password" autocomplete="new-password" minlength="10" maxlength="256" ${item ? '' : 'required'}`))}
|
||||
${editorField('角色', select('role', [['viewer', '只读用户'], ['operator', '操作员']], item?.role))}
|
||||
${item ? enabled('enabled', item.enabled, '启用账号') : ''}
|
||||
${editorFooter('保存用户')}
|
||||
</form><p class="fusionNote">操作员可登记设备、维护名单和防控区、处置告警。只读用户可查看业务页面。</p>`));
|
||||
onForm(root, form, async values => {
|
||||
const password = values.get('password');
|
||||
const role = values.get('role');
|
||||
if (item) {
|
||||
await request(`${userPath}/${item.id}`, 'PUT', { password: password || null, role, enabled: values.has('enabled') });
|
||||
} else {
|
||||
await request(userPath, 'POST', { username: values.get('username'), password, role });
|
||||
}
|
||||
if (live(root)) await users(root, admin, '用户已保存。');
|
||||
});
|
||||
};
|
||||
onAction(root, 'add-user', () => edit(null));
|
||||
onAction(root, 'edit-user', id => edit(entries.find(item => item.id === Number(id))));
|
||||
onAction(root, 'delete-user', async id => {
|
||||
if (!confirm('删除此用户并退出其会话?')) return;
|
||||
await request(`${userPath}/${id}`, 'DELETE');
|
||||
if (live(root)) await users(root, admin, '用户已删除。');
|
||||
});
|
||||
}
|
||||
|
||||
async function flightPlans(root, admin, seed) {
|
||||
const account = await request('/api/auth/status');
|
||||
const editable = ['admin','operator'].includes(account.role);
|
||||
const [snapshot, archive] = await Promise.all([request('/api/flight-plans'),request('/api/records')]);
|
||||
if (!live(root)) return;
|
||||
let entries = snapshot.entries;
|
||||
const records = new Map(archive.records.map(r=>[r.id,r]));
|
||||
const names = p => records.get(p.recordId) || {};
|
||||
let keyword='', statusFilter='';
|
||||
const state = p => !p.enabled ? ['撤销','muted','cancelled'] : p.endMs<=Date.now() ? ['已过期','muted','expired']
|
||||
: p.approval==='rejected' ? ['已驳回','danger','rejected'] : p.approval!=='approved' ? ['待审批','warning','pending']
|
||||
: p.startMs>Date.now() ? ['已批准 · 未开始','white','approved'] : ['已批准 · 生效中','ok','active'];
|
||||
body(root, toolbar(`${editable?button('新增飞行报备','new-plan',''):''}${button('刷新','refresh-plans','')}<input class="planSearch" aria-label="搜索飞行报备" placeholder="搜索 SN、机型或报备名称"><label>状态 ${select('plan-filter',[['','全部'],['pending','待审批'],['approved','已批准 · 未开始'],['active','生效中'],['rejected','已驳回'],['expired','已过期'],['cancelled','已撤销']],'')}</label>`)
|
||||
+'<div class="rid-module-editor"></div><div class="planResults"></div>');
|
||||
const result=root.querySelector('.planResults');
|
||||
function geometryText(g) {return g.type==='circle' ? `圆形 · 半径 ${g.radius_m} m` : `多边形 · ${g.vertices.length} 个顶点`;}
|
||||
function render() {
|
||||
const rows=entries.filter(p=>(!statusFilter||state(p)[2]===statusFilter)&&[p.name,names(p).serialNo,names(p).modelName].join(' ').toLowerCase().includes(keyword))
|
||||
.sort((a,b)=>Number(state(b)[2]==='pending')-Number(state(a)[2]==='pending')||b.startMs-a.startMs);
|
||||
result.innerHTML=managedTable(root,'飞行报备分页',[
|
||||
cell('飞机',p=>`<strong>${esc(names(p).modelName||'未填写机型')}</strong><br><code>${esc(names(p).serialNo||'档案已移除')}</code>`),
|
||||
column('报备名称','name'),cell('飞行时段',p=>`${esc(time(p.startMs))}<br>${esc(time(p.endMs))}`),
|
||||
cell('允许区域',p=>esc(geometryText(p.geometry))),
|
||||
cell('状态',p=>{const [label,tone]=state(p);return `<span class="flightTag ${tone}">${label}</span>`;}),
|
||||
cell('审批',p=>`${esc(p.reviewedBy||'—')}${p.reviewNote?'<br>'+esc(p.reviewNote):''}`),
|
||||
cell('操作',p=>button('详情','detail-plan',p.id)+(editable?button('编辑','edit-plan',p.id):'')
|
||||
+(admin&&state(p)[2]==='pending'?button('审批','review-plan',p.id):'')
|
||||
+(editable&&p.enabled?button('撤销','cancel-plan',p.id,true):''))
|
||||
],rows,'暂无匹配的飞行报备');
|
||||
bindManagedTable(root,render);
|
||||
onAction(root,'detail-plan',id=>details(entries.find(p=>p.id===id)));
|
||||
onAction(root,'edit-plan',id=>edit(entries.find(p=>p.id===id)));
|
||||
onAction(root,'review-plan',id=>review(entries.find(p=>p.id===id)));
|
||||
onAction(root,'cancel-plan',async id=>{
|
||||
if (!confirm('撤销后该报备将不再允许飞行,确认撤销?')) return;
|
||||
const plan=entries.find(p=>p.id===id);
|
||||
await request('/api/flight-plans/'+encodeURIComponent(id),'PUT',{...plan,enabled:false});await reload();
|
||||
});
|
||||
}
|
||||
async function reload(){entries=(await request('/api/flight-plans')).entries;if(live(root)){editArea(root,'');render();}}
|
||||
function details(p){
|
||||
editArea(root,section('报备详情',`<dl class="planDetails"><dt>飞机</dt><dd>${esc(names(p).modelName)} · ${esc(names(p).serialNo)}</dd><dt>时间</dt><dd>${esc(time(p.startMs))} — ${esc(time(p.endMs))}</dd><dt>区域(经度,纬度)</dt><dd><pre>${esc((p.geometry.type==='circle'?[p.geometry.center]:p.geometry.vertices).map(v=>v.join(', ')).join('\n'))}</pre>${esc(geometryText(p.geometry))}</dd><dt>备注</dt><dd>${esc(p.note||'—')}</dd><dt>审批</dt><dd>${esc(state(p)[0])} · ${esc(p.reviewedBy||'—')} · ${esc(time(p.reviewedAtMs))}<br>${esc(p.reviewNote)}</dd></dl><button type="button" data-action="cancel-edit">关闭</button>`));
|
||||
}
|
||||
function review(p){
|
||||
const form=editArea(root,`<form class="configGroup planReviewForm"><h3>审批 ${esc(p.name)}</h3><p>${esc(names(p).serialNo)} · ${esc(time(p.startMs))} 至 ${esc(time(p.endMs))}</p><p>${esc(geometryText(p.geometry))}</p><pre>${esc((p.geometry.type==='circle'?[p.geometry.center]:p.geometry.vertices).map(v=>v.join(', ')).join('\n'))}</pre>
|
||||
${editorField('审批结果',select('decision',[['approve','批准'],['reject','驳回']],'approve'))}
|
||||
${editorField('审批意见', '<textarea name="note" maxlength="500" rows="2" placeholder="驳回时必填"></textarea>')}${editorFooter('提交审批结果')}</form>`);
|
||||
onForm(root,form,async data=>{
|
||||
await request('/api/flight-plans/'+encodeURIComponent(p.id)+'/approval','PUT',{approved:data.get('decision')==='approve',expectedRevision:p.revision,note:data.get('note')});
|
||||
await reload();feedback(root,'审批结果已保存。');
|
||||
});
|
||||
}
|
||||
function planEditor(html) {
|
||||
editArea(root,'');
|
||||
root.querySelector('.flightPlanDialog')?.remove();
|
||||
const trigger=document.activeElement;
|
||||
const modal=document.createElement('dialog');
|
||||
modal.className='flightPlanDialog';
|
||||
modal.setAttribute('aria-labelledby','flight-plan-dialog-title');
|
||||
modal.innerHTML=html;
|
||||
const form=modal.querySelector('form');
|
||||
const heading=form.querySelector('h3');
|
||||
heading.id='flight-plan-dialog-title';
|
||||
const closeButton=document.createElement('button');
|
||||
closeButton.type='button';closeButton.className='planDialogClose';
|
||||
closeButton.setAttribute('aria-label','关闭飞行报备弹窗');closeButton.textContent='×';
|
||||
form.querySelector('.planFormHeader').append(closeButton);
|
||||
const notice=document.createElement('div');
|
||||
notice.className='rid-module-feedback planDialogFeedback';
|
||||
notice.setAttribute('role','alert');notice.hidden=true;
|
||||
form.querySelector('.planFormHeader').after(notice);
|
||||
const close=()=>{
|
||||
if(form.querySelector('button[type="submit"]').disabled) return;
|
||||
modal.close();modal.remove();
|
||||
if(trigger?.isConnected) trigger.focus();
|
||||
else root.querySelector('[data-action="new-plan"]')?.focus();
|
||||
};
|
||||
closeButton.onclick=close;
|
||||
form.querySelector('[data-action="cancel-edit"]').onclick=close;
|
||||
modal.addEventListener('cancel',event=>{event.preventDefault();close();});
|
||||
root.append(modal);modal.showModal();
|
||||
form.querySelector('select,input')?.focus();
|
||||
return form;
|
||||
}
|
||||
function edit(p, recordId) {
|
||||
if (!editable) return;
|
||||
if (!records.size) {feedback(root,'请先在设备登记中登记飞机。',true);return;}
|
||||
const g=p?.geometry||{type:'circle',center:[],radius_m:500};
|
||||
const form=planEditor(`<form class="configGroup flightPlanForm"><header class="planFormHeader"><h3>${p?'修改飞行报备':'新增飞行报备'}</h3><p class="muted">提交后需管理员审批;修改已批准报备后需要重新审批。坐标使用 WGS84。</p></header><div class="planEditorColumns"><section class="planFieldGroup"><h4>飞行信息</h4><div class="planFormGrid">
|
||||
${editorField('登记飞机',select('recordId',[['','请选择登记飞机'],...archive.records.map(r=>[r.id,`${r.serialNo} · ${r.modelName||'未填写机型'}`])],p?.recordId||recordId||''))}
|
||||
${editorField('报备名称',input('name',p?.name||'','required maxlength="80"'))}
|
||||
${editorField('开始时间',input('start',p?toDatetimeLocalValue(new Date(p.startMs)):toDatetimeLocalValue(new Date()),'type="datetime-local" required'))}
|
||||
${editorField('结束时间',input('end',p?toDatetimeLocalValue(new Date(p.endMs)):toDatetimeLocalValue(new Date(Date.now()+3600000)),'type="datetime-local" required'))}
|
||||
</div>${editorField('备注','<textarea name="note" rows="3" maxlength="500" placeholder="选填飞行用途或补充说明">'+esc(p?.note||'')+'</textarea>')}</section><section class="planFieldGroup"><h4>允许飞行区域</h4><div class="planFormGrid">
|
||||
${editorField('区域形状',select('shape',[['circle','圆形'],['polygon','多边形']],g.type))}
|
||||
${editorField('圆形半径(米)',input('radius',g.radius_m||500,'type="number" min="1" max="1000000" step="any"'))}
|
||||
</div>${editorField('允许飞行区域坐标(经度,纬度)',`<textarea name="coordinates" rows="4" required spellcheck="false" placeholder="118.576700, 31.954800">${esc((g.type==='circle'?(g.center.length?[g.center]:[]):g.vertices).map(v=>v.join(', ')).join('\n'))}</textarea>`)}
|
||||
<p class="muted">圆形填写一行中心坐标;多边形每行一个顶点,按边界顺序填写,至少三个点。</p>
|
||||
</section></div>${editorFooter('提交报备')}</form>`);
|
||||
const updateShape=()=>{form.elements.radius.disabled=form.elements.shape.value!=='circle';form.elements.radius.required=!form.elements.radius.disabled;};
|
||||
form.elements.shape.onchange=updateShape;updateShape();form.elements.recordId.required=true;
|
||||
onForm(root,form,async data=>{
|
||||
const coords=String(data.get('coordinates')).trim().split(/\r?\n/).filter(line=>line.trim()).map(line=>line.trim().split(/[,,\s]+/).map(Number));
|
||||
if (coords.some(v=>v.length!==2||!v.every(Number.isFinite)||Math.abs(v[0])>180||Math.abs(v[1])>90)) throw new Error('每行请填写有效的经度、纬度');
|
||||
const circle=data.get('shape')==='circle';
|
||||
if (circle?coords.length!==1:coords.length<3) throw new Error(circle?'圆形只需一行中心坐标':'多边形至少需要三个顶点');
|
||||
const startMs=new Date(data.get('start')).getTime(),endMs=new Date(data.get('end')).getTime();
|
||||
if (!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs>=endMs||endMs<=Date.now()) throw new Error('结束时间须晚于开始时间和当前时间');
|
||||
const id=p?.id||'plan-'+crypto.randomUUID();
|
||||
await request('/api/flight-plans/'+encodeURIComponent(id),'PUT',{id,recordId:data.get('recordId'),name:data.get('name'),startMs,endMs,
|
||||
geometry:circle?{type:'circle',center:coords[0],radius_m:Number(data.get('radius'))}:{type:'polygon',vertices:coords},note:data.get('note'),enabled:true,revision:p?.revision||0});
|
||||
const modal=form.closest('dialog');
|
||||
modal.close();modal.remove();
|
||||
root.querySelector('[data-action="new-plan"]')?.focus();
|
||||
await reload();feedback(root,'报备已提交,等待管理员审批。');
|
||||
});
|
||||
}
|
||||
root.querySelector('.planSearch').oninput=event=>{keyword=event.target.value.trim().toLowerCase();root.pageOffset=0;render();};
|
||||
root.querySelector('[name="plan-filter"]').onchange=event=>{statusFilter=event.target.value;root.pageOffset=0;render();};
|
||||
onAction(root,'new-plan',()=>edit());
|
||||
onAction(root,'refresh-plans',()=>reload());
|
||||
render();if(seed?.recordId) edit(null,seed.recordId);
|
||||
}
|
||||
|
||||
const pages = {
|
||||
records, rankings, devices, models, users,
|
||||
"flight-plans": flightPlans,
|
||||
configs: settings
|
||||
};
|
||||
window.ridWorkbenchModules = Object.freeze({
|
||||
async open(name, seed) {
|
||||
const root = document.createElement('div');
|
||||
root.className = 'rid-module-page';
|
||||
root.dataset.module = name;
|
||||
root.innerHTML = '<div class="rid-module-feedback" role="status" hidden></div><div class="rid-module-content"><div class="moduleEmpty">正在加载数据…</div></div>';
|
||||
document.getElementById('moduleBody').replaceChildren(root);
|
||||
try {
|
||||
const account = await request('/api/auth/status');
|
||||
if (!live(root)) return;
|
||||
if (!account.authenticated) return location.replace('/workbench/');
|
||||
await pages[name](root, account.role === 'admin', seed);
|
||||
if (name === 'devices' && live(root)) watchDevices(root, account.role === 'admin');
|
||||
} catch (error) {
|
||||
if (!live(root)) return;
|
||||
const content = root.querySelector('.rid-module-content');
|
||||
if (content.firstElementChild?.classList.contains('moduleEmpty')) content.replaceChildren();
|
||||
feedback(root, error.message || '加载失败,请重试', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,66 @@
|
||||
.rid-pager,
|
||||
.registry-workspace .rid-pager {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px 14px;
|
||||
margin: 10px 0 0;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid #29465c;
|
||||
border-radius: 7px;
|
||||
background: #102438;
|
||||
color: #c7ddeb;
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.rid-pager .rid-pager-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.rid-page-summary { color: #b3c9d9; }
|
||||
.rid-page-summary > span { color: #9db8cc; }
|
||||
.rid-page-number {
|
||||
min-width: 5.5em;
|
||||
color: #eff7fc;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rid-pager .rid-pager-actions button {
|
||||
min-width: 58px;
|
||||
min-height: 32px;
|
||||
margin: 0;
|
||||
padding: 4px 9px;
|
||||
border: 1px solid #466982;
|
||||
border-radius: 5px;
|
||||
background: #18344c;
|
||||
color: #ecf5ff;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rid-pager .rid-pager-actions button:hover:not(:disabled) {
|
||||
background: #254f70;
|
||||
border-color: #76bbe7;
|
||||
}
|
||||
.rid-pager .rid-pager-actions button:disabled {
|
||||
border-color: #2b465b;
|
||||
background: #13283a;
|
||||
color: #91aabf;
|
||||
opacity: 1;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.rid-pager :focus-visible {
|
||||
outline: 2px solid #7ddcff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.rid-pager[aria-busy="true"] .rid-pager-actions button { cursor: wait; }
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.rid-pager, .registry-workspace .rid-pager { padding-inline: 9px; }
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>RID侦测平台</title>
|
||||
<link rel="icon" href="/workbench/assets/rid-app.ico" type="image/x-icon">
|
||||
<link rel="stylesheet" href="/workbench/leaflet/leaflet.css">
|
||||
<script src="/workbench/leaflet/leaflet.js"></script>
|
||||
<link rel="stylesheet" href="/workbench/platform.css">
|
||||
<link rel="stylesheet" href="/workbench/integration.css">
|
||||
<link rel="stylesheet" href="/workbench/pagination.css">
|
||||
<link rel="stylesheet" href="/workbench/drone-marker.css">
|
||||
<link rel="stylesheet" href="/vendor/maplibre-gl.css">
|
||||
<link rel="stylesheet" href="/workbench/live-map-3d.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app">
|
||||
<div class="top">
|
||||
<div class="brand">
|
||||
<img class="logo brandLogo" src="/workbench/assets/bsrid_logo_icon_light.png" alt="" width="42" height="42">
|
||||
<div class="overview-totals" aria-label="工作台总览">
|
||||
<span>侦测设备 <strong id="kpiStations">0</strong></span>
|
||||
<span>实时目标 <strong id="kpiTargets">0</strong></span>
|
||||
<span>告警 <strong id="kpiAlerts">0</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="titleBox">
|
||||
<div class="title" id="platformTitle">RID侦测平台</div>
|
||||
</div>
|
||||
<nav class="nav" id="workbenchNav" aria-label="工作台导航">
|
||||
<button type="button" class="btn" data-rid-click="fitAll" aria-current="page">空域总览</button>
|
||||
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="records">记录</button>
|
||||
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="devices">设备管理</button>
|
||||
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="register">档案</button>
|
||||
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="configs">设置</button>
|
||||
<span class="nav-account" id="currentUserName">未登录</span>
|
||||
<button type="button" class="btn" data-rid-click="logout">退出</button>
|
||||
</nav>
|
||||
</div>
|
||||
<div class="main">
|
||||
<div class="left" id="overviewLeft">
|
||||
<div class="panel deviceListPanel">
|
||||
<div class="p-title">侦测设备列表 <span id="stationSummary" class="panelCount">在线 0 · 离线 0</span></div>
|
||||
<div id="stationList" class="list compactList">
|
||||
<div class="muted">暂无侦测设备</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel targetListPanel">
|
||||
<div class="p-title">实时目标列表 <span id="targetSummary" class="panelCount">在线 0</span></div>
|
||||
<div id="droneList" class="list">
|
||||
<div class="muted">暂无目标</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mapWrap">
|
||||
<div id="map" aria-label="平面实时地图"></div>
|
||||
<div id="liveMap3D" aria-label="三维实时地图" hidden></div>
|
||||
<div class="gridOverlay"></div>
|
||||
<div class="mapDock">
|
||||
<div class="legend" role="group" aria-label="地图图例">
|
||||
<button type="button" class="mapLegendToggle" aria-controls="mapLegendContent" aria-expanded="false">
|
||||
图例与显示选项 <span class="mapLegendArrow" aria-hidden="true"></span>
|
||||
</button>
|
||||
<div class="mapLegendContent" id="mapLegendContent">
|
||||
<div class="legendStatus">
|
||||
<span><i class="dot registeredDrone"></i><em>白名单</em></span>
|
||||
<span><i class="dot registeredDrone"></i><em>已报备</em></span>
|
||||
<span><i class="dot flightWarning"></i><em>未报备告警</em></span>
|
||||
<span><i class="dot flightDanger"></i><em>未登记 / 防控区 / 黑名单告警</em></span>
|
||||
<span><i class="dot offlineDot"></i><em>待核验</em></span>
|
||||
</div>
|
||||
<div class="legendSymbols">
|
||||
<span title="轨迹"><i class="dot track"></i><em>轨迹</em></span>
|
||||
<span title="防控区"><i class="dot zone"></i><em>防控区</em></span>
|
||||
<span title="飞手/遥控器"><i class="dot pilotDot"></i><em>飞手</em></span>
|
||||
</div>
|
||||
<div class="mapDisplayOptions" role="group" aria-label="地图显示选项">
|
||||
<label><input id="showFlightTrails" type="checkbox" checked>显示轨迹</label>
|
||||
<label><input id="showModelLabels" type="checkbox" checked>显示型号</label>
|
||||
<label><input id="showPilotMarkers" type="checkbox" checked>显示遥控器</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toolbar" role="group" aria-label="地图绘图工具">
|
||||
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="polygon" title="绘制多边形防控区">
|
||||
<div>⬠</div>多边形
|
||||
</div>
|
||||
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="rectangle" title="绘制矩形防控区">
|
||||
<div>▭</div>矩形
|
||||
</div>
|
||||
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="circle" title="绘制圆形防控区">
|
||||
<div>○</div>圆形
|
||||
</div>
|
||||
<div class="tool" data-rid-click="finishDrawZone" title="完成绘制/保存防控区">
|
||||
<div>✓</div>完成
|
||||
</div>
|
||||
<div class="tool" data-rid-click="cancelDrawZone" title="取消绘制">
|
||||
<div>×</div>取消
|
||||
</div>
|
||||
<div class="tool" data-rid-click="clearAllTrackLayers" title="清除实时轨迹">
|
||||
<div>↺</div>清除实时轨迹
|
||||
</div>
|
||||
</div>
|
||||
<div class="mapSourceBox" title="选择地图底图">
|
||||
<button type="button" id="mapViewToggle" class="smallBtn" aria-pressed="false" title="切换 2D / 3D 视角">3D</button>
|
||||
<span id="baseMapIcon">▧</span>
|
||||
<select id="mapSourceSelect" aria-label="地图底图" data-rid-change="setBaseMap" data-rid-arg0="@value">
|
||||
<option value="tdt-satellite" selected>天地图影像</option>
|
||||
<option value="tdt-vector">天地图矢量</option>
|
||||
<option value="amap-vector" disabled>高德地图(待接入)</option>
|
||||
<option value="amap-satellite" disabled>高德卫星(待接入)</option>
|
||||
<option value="osm-vector" disabled>OSM地图(待接入)</option>
|
||||
<option value="esri-satellite" disabled>Esri卫星(待接入)</option>
|
||||
<option value="custom-xyz" disabled>专网自定义地图(待接入)</option>
|
||||
</select>
|
||||
<label class="labelToggle" title="卫星图可叠加道路、地名、行政区等文字标注">
|
||||
<input id="labelToggle" type="checkbox" checked data-rid-change="toggleMapLabels" data-rid-arg0="@checked"><span>标注</span>
|
||||
</label>
|
||||
<label class="cacheToggle" title="已浏览瓦片缓存到 maps/cache,手动下载的离线地图保存在 map_cache">
|
||||
<input id="mapCacheQuickToggle" type="checkbox" checked disabled title="使用 RID 现有地图缓存"><span>缓存</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="sideToggle leftToggle" data-rid-click="toggleSidePanel" data-rid-arg0="left" aria-controls="overviewLeft" aria-expanded="true" aria-label="设备与目标" title="收起设备与目标">‹</button>
|
||||
<button type="button" class="sideToggle rightToggle" data-rid-click="toggleSidePanel" data-rid-arg0="right" aria-controls="overviewRight" aria-expanded="true" aria-label="防控区与告警" title="收起防控区与告警">›</button>
|
||||
|
||||
</div>
|
||||
<div class="right" id="overviewRight">
|
||||
<section class="panel zonePanel" aria-label="防控区管理">
|
||||
<div class="p-title">防控区管理</div>
|
||||
<p class="zoneFeedback" id="zoneFeedback" role="status" hidden></p>
|
||||
<div class="list zonePanelContent">
|
||||
<details id="zoneCoordinateEntry" class="zoneCoordinateEntry">
|
||||
<summary>录入坐标</summary>
|
||||
<form id="zoneCoordinateForm">
|
||||
<div class="zoneFormFields">
|
||||
<label>区域名称<input id="coordinateZoneName" maxlength="40" required></label>
|
||||
<label>形状<select id="coordinateZoneType">
|
||||
<option value="polygon">多边形</option>
|
||||
<option value="rectangle">矩形</option>
|
||||
<option value="circle">圆形</option>
|
||||
</select></label>
|
||||
</div>
|
||||
<label>坐标(经度,纬度)
|
||||
<textarea id="zoneCoordinates" rows="3" spellcheck="false" required aria-describedby="zoneCoordinateHelp" placeholder="118.782100, 31.982300"></textarea>
|
||||
</label>
|
||||
<p id="zoneCoordinateHelp">每行一个顶点,按边界顺序输入,至少三行。</p>
|
||||
<label id="zoneRadiusField" hidden>半径(米)
|
||||
<input id="zoneRadius" type="number" inputmode="decimal" min="1" max="1000000" step="any" disabled>
|
||||
</label>
|
||||
<button type="submit" id="coordinateZoneSave">保存防控区</button>
|
||||
</form>
|
||||
</details>
|
||||
<div class="zoneDrawEditor" id="zoneDrawEditor" hidden>
|
||||
<p id="drawHint"></p>
|
||||
<div class="zoneDrawActions">
|
||||
<input id="zoneName" maxlength="40" placeholder="防控区名称" aria-label="地图绘制防控区名称">
|
||||
<button type="button" id="zoneDrawSave" data-rid-click="finishDrawZone">保存绘制</button>
|
||||
</div>
|
||||
</div>
|
||||
<ul id="zoneList" class="zoneList"></ul>
|
||||
</div>
|
||||
</section>
|
||||
<section class="panel alertPanel" aria-label="告警中心">
|
||||
<div class="p-title">告警中心 <span class="panelCount" id="alertBadge">未读 0 · 已读 0</span></div>
|
||||
<p id="alertFeedback" class="muted" role="status" hidden></p>
|
||||
<div id="alertList" class="list">
|
||||
<div class="muted">暂无告警</div>
|
||||
</div>
|
||||
<div class="alarmSettingRow">
|
||||
<label><input id="soundAlarmToggle" type="checkbox" checked> 声音报警</label>
|
||||
<label><input id="flashAlarmToggle" type="checkbox" checked> 告警闪屏</label>
|
||||
<button type="button" class="smallBtn gray" data-rid-click="testAlarm">测试告警</button>
|
||||
<button type="button" id="clearAlarm" class="smallBtn gray" data-rid-click="clearCurrentAlerts" disabled>清除显示</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<section id="moduleWorkspace" class="moduleWorkspace" aria-labelledby="moduleTitle">
|
||||
<h2 id="moduleTitle" tabindex="-1"></h2>
|
||||
<nav class="moduleNav" data-module-group="records" aria-label="记录分类" hidden>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="records">轨迹记录</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="alarms">报警查询</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="rankings">统计分析</button>
|
||||
</nav>
|
||||
<nav class="moduleNav" data-module-group="devices" aria-label="设备管理分类" hidden>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="devices">接收器列表</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="receivers">接收器诊断</button>
|
||||
</nav>
|
||||
<nav class="moduleNav" data-module-group="register" aria-label="档案分类" hidden>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="register">设备登记</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="archives">本地档案</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="flight-plans">飞行报备</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="drones">黑白名单</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="models">型号库</button>
|
||||
</nav>
|
||||
<nav class="moduleNav" data-module-group="configs" aria-label="设置分类" hidden>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="configs">平台设置</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="maps">地图与离线下载</button>
|
||||
<button type="button" data-rid-click="openModule" data-rid-arg0="users">用户管理</button>
|
||||
</nav>
|
||||
<div id="moduleBody" class="moduleBody"></div>
|
||||
<div id="moduleEmbed" class="moduleEmbed" hidden>
|
||||
<p id="moduleEmbedStatus" role="status" hidden></p>
|
||||
<button id="moduleEmbedRetry" type="button" hidden>重新加载</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<div id="alarmOverlay"><div class="alarmText" role="status"></div></div>
|
||||
<p id="rid-workbench-status" role="status" aria-live="polite" hidden></p>
|
||||
<script src="/workbench/drone-map.js"></script>
|
||||
<script src="/workbench/flight-status.js"></script>
|
||||
<script src="/workbench/rid-api.js"></script>
|
||||
<script src="/workbench/platform.js"></script>
|
||||
<script src="/workbench/modules.js"></script>
|
||||
<script src="/workbench/module-host.js"></script>
|
||||
<script src="/workbench/events.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,453 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// Translate the authorized reference view's shapes at one boundary. Business
|
||||
// rules, session checks, persistence, and receiver ownership stay in RID.
|
||||
async function request(path, method = 'GET', body, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
...options, method, cache: 'no-store', credentials: 'same-origin',
|
||||
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
});
|
||||
if (response.status === 401) {
|
||||
location.replace('/workbench/');
|
||||
throw new Error('会话已结束,请重新登录');
|
||||
}
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const error = new Error(data.error || data.message || `RID 服务返回 HTTP ${response.status}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
let receivers;
|
||||
let receiverRequest;
|
||||
let receiversAt = -Infinity;
|
||||
async function receiverRows(refresh = false) {
|
||||
if (!refresh && receivers && performance.now() - receiversAt < 900) return receivers;
|
||||
if (!receiverRequest) {
|
||||
receiverRequest = request('/api/receivers').then(data => {
|
||||
if (data.error) throw new Error(data.error);
|
||||
receiversAt = performance.now();
|
||||
return receivers = data.receivers;
|
||||
}).finally(() => { receiverRequest = null; });
|
||||
}
|
||||
return receiverRequest;
|
||||
}
|
||||
|
||||
const stateLabels = {
|
||||
'serial-open': '串口已打开', 'udp-listening': 'UDP 正在监听', 'tcp-listening': 'TCP 正在监听',
|
||||
'connecting': '正在连接', 'disconnected': '连接中断', 'stopped': '未连接'
|
||||
};
|
||||
function link(row) {
|
||||
const state = row?.status?.state;
|
||||
const serial = row?.config.transport === 'serial';
|
||||
const lastData = serial ? row.status?.lastValidFrameMs : row?.status?.lastDataMs;
|
||||
const connected = Boolean(row?.config.enabled && ['serial-open', 'udp-listening', 'tcp-listening'].includes(state));
|
||||
const receiving = connected && lastData != null && Date.now() - lastData <= 15000;
|
||||
const tcp = row?.config.transport === 'tcp-listen';
|
||||
let message = row?.status?.lastError || stateLabels[state] || '未连接';
|
||||
if (connected && tcp) {
|
||||
const peer = row.status.lastPeerIp;
|
||||
message = receiving && peer ? '接收中 · ' + peer : 'TCP 监听中 · 等待数据';
|
||||
}
|
||||
if (connected && serial) message = receiving ? '串口接收中' : '串口已打开 · 等待有效报文';
|
||||
return { connected, receiving, message };
|
||||
}
|
||||
|
||||
function isStation(row) {
|
||||
if (row.config.transport !== 'serial') return true;
|
||||
return row.status.lastValidFrameMs != null || Boolean(row.userConfigured && row.config.serialPort);
|
||||
}
|
||||
async function sourceStatus() {
|
||||
const rows = await receiverRows();
|
||||
const serial = rows.filter(row => row.config.transport === 'serial');
|
||||
const tcp = rows.filter(row => row.config.transport === 'tcp-listen');
|
||||
const udp = rows.filter(row => row.config.transport === 'udp');
|
||||
const collection = list => list.find(row => link(row).connected) || list[0];
|
||||
return {
|
||||
usb: link(collection(serial)), ble: { connected: false, message: '本阶段未接入 BLE' },
|
||||
tcp: link(collection(tcp)), udp: link(collection(udp)), tcpDevices: tcp.map(link)
|
||||
};
|
||||
}
|
||||
|
||||
async function changeSerial(body, enabled) {
|
||||
if (!/^COM[1-9]\d*$/i.test(body.port || '')) throw new Error('请先选择串口');
|
||||
const port = body.port.toUpperCase();
|
||||
const rows = await receiverRows(true);
|
||||
const serial = rows.find(row => row.config.transport === 'serial' && row.config.serialPort === port);
|
||||
if (!serial && !enabled) return { ok: true, connected: false, message: '该串口未被本平台打开' };
|
||||
const code = serial ? `/api/receivers/${encodeURIComponent(serial.id)}` : '/api/receivers';
|
||||
const config = { ...(serial?.config || { transport: 'serial', format: 'raw' }), enabled, serialPort: port };
|
||||
if (enabled) config.baudRate = Number(body.baud);
|
||||
await request(code, serial ? 'PUT' : 'POST', { name: serial?.name || `USB 串口 ${port}`, config });
|
||||
receiversAt = -Infinity;
|
||||
return { ok: true, connected: false, message: enabled ? '已启动串口接收任务,等待设备状态' : '串口已断开' };
|
||||
}
|
||||
|
||||
const targets = new Map();
|
||||
let ownership = new Map();
|
||||
let lastFrame = -Infinity;
|
||||
let stream;
|
||||
let retry;
|
||||
let stopped = false;
|
||||
|
||||
function applyFrame(frame) {
|
||||
if (frame.snapshot) targets.clear();
|
||||
for (const id of frame.removed) targets.delete(id);
|
||||
for (const target of frame.targets) targets.set(target.observation.target_id, target);
|
||||
lastFrame = performance.now();
|
||||
if (frame.snapshot || frame.targets.length || frame.removed.length) {
|
||||
window.dispatchEvent(new Event('rid-live-frame'));
|
||||
}
|
||||
}
|
||||
function connectStream() {
|
||||
if (stopped || stream) return;
|
||||
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
stream = new WebSocket(`${protocol}//${location.host}/api/realtime/ws?format=json`);
|
||||
stream.onmessage = ({ data }) => {
|
||||
try {
|
||||
const frame = JSON.parse(data);
|
||||
applyFrame(frame);
|
||||
stream.send(String(frame.sequence));
|
||||
} catch (_) {
|
||||
stream.close();
|
||||
}
|
||||
};
|
||||
stream.onclose = () => {
|
||||
stream = null;
|
||||
if (!stopped) retry = setTimeout(connectStream, 2500);
|
||||
};
|
||||
}
|
||||
window.addEventListener('pagehide', () => { stopped = true; clearTimeout(retry); stream?.close(); });
|
||||
window.addEventListener('pageshow', () => { stopped = false; connectStream(); });
|
||||
|
||||
let rules = [];
|
||||
let rulesExpires = 0;
|
||||
let pendingRules;
|
||||
function modelRules(refresh = false) {
|
||||
if (!refresh && performance.now() < rulesExpires) return Promise.resolve(rules);
|
||||
return pendingRules ??= request('/api/workbench/models').then(data => {
|
||||
rulesExpires = performance.now() + 10000;
|
||||
return rules = data.entries;
|
||||
}).finally(() => { pendingRules = null; });
|
||||
}
|
||||
const modelRuleIndexes = new WeakMap();
|
||||
|
||||
function indexModelRules(entries) {
|
||||
let index = modelRuleIndexes.get(entries);
|
||||
if (index) return index;
|
||||
|
||||
const prefixes = new Map();
|
||||
const keywords = [];
|
||||
for (const rule of entries) {
|
||||
if (!rule.enabled) continue;
|
||||
if (rule.field === 'serial') prefixes.set(rule.pattern.toUpperCase(), rule);
|
||||
else if (rule.field === 'target' || rule.field === 'model') keywords.push(rule);
|
||||
}
|
||||
const lengths = [...new Set([...prefixes.keys()].map(prefix => prefix.length))].sort((a, b) => b - a);
|
||||
index = {prefixes, lengths, keywords};
|
||||
modelRuleIndexes.set(entries, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
function resolveModel(targetId, reported, entries = rules, serial) {
|
||||
const {prefixes, lengths, keywords} = indexModelRules(entries);
|
||||
const sn = (serial || '').trim().toUpperCase();
|
||||
let match;
|
||||
for (const length of lengths) {
|
||||
if (length > sn.length) continue;
|
||||
match = prefixes.get(sn.slice(0, length));
|
||||
if (match) break;
|
||||
}
|
||||
if (!match) {
|
||||
const ident = (targetId || '').toLowerCase();
|
||||
const model = (reported || '').toLowerCase();
|
||||
match = keywords.find(rule => (rule.field === 'target' ? ident : model).includes(rule.pattern));
|
||||
}
|
||||
if (!match) return reported;
|
||||
const vendor = match.vendor.toLowerCase();
|
||||
const name = match.model.toLowerCase();
|
||||
if (match.field === 'serial' && (name === vendor || name.startsWith(vendor + ' '))) {
|
||||
return match.model;
|
||||
}
|
||||
return [match.vendor, match.model].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
function detectionReceiver(id) {
|
||||
const row = receivers?.find(receiver => receiver.id === id);
|
||||
if (!row) return null;
|
||||
// A network receiver with no peer restriction cannot identify which sender owns its last GNSS fix.
|
||||
const identified = row.config.transport === 'serial'
|
||||
|| (row.config.transport === 'tcp-listen' && !!row.config.peerIp);
|
||||
const fresh = performance.now() - receiversAt <= 5000;
|
||||
return {name: row.name, gnss: identified && fresh ? row.status.gnss : null};
|
||||
}
|
||||
|
||||
async function liveRows() {
|
||||
if (performance.now() - lastFrame > 2000) {
|
||||
const frame = await request('/api/realtime/snapshot');
|
||||
if (performance.now() - lastFrame > 2000) applyFrame(frame);
|
||||
}
|
||||
await Promise.all([modelRules().catch(() => rules), refreshOwnership()]);
|
||||
return cachedLiveRows();
|
||||
}
|
||||
|
||||
async function registrations(ids) {
|
||||
const unique = [...new Set(ids)];
|
||||
const batches = [];
|
||||
for (let start = 0; start < unique.length; start += 96) {
|
||||
const params = new URLSearchParams({ids: unique.slice(start, start + 96).join(',')});
|
||||
batches.push(request('/api/target-registration-status?' + params));
|
||||
}
|
||||
const rows = (await Promise.all(batches)).flatMap(response => response.entries);
|
||||
return new Map(rows.map(row => [row.targetId, row]));
|
||||
}
|
||||
|
||||
let ownershipRequest;
|
||||
let flightAssessments = new Map();
|
||||
function refreshOwnership() {
|
||||
return ownershipRequest ??= Promise.all([registrations(targets.keys()),request("/api/flight-status")]).then(([rows,status]) => {
|
||||
ownership = rows;
|
||||
flightAssessments = new Map(status.entries.map(row=>[row.targetId,row]));
|
||||
}).catch(error => {flightAssessments.clear();console.warn('飞行状态暂不可用', error.message);})
|
||||
.finally(() => { ownershipRequest = null; });
|
||||
}
|
||||
|
||||
function registrationInfo(status) {
|
||||
if (!status) return {};
|
||||
const registryClass = status.listKind === 'black' ? 'blacklist'
|
||||
: status.listKind === 'white' ? 'whitelist' : status.registered ? 'registered' : 'unregistered';
|
||||
return { registered: status.registered, registryClass };
|
||||
}
|
||||
|
||||
function cachedLiveRows() {
|
||||
return [...targets.values()].map(target => {
|
||||
const observation = target.observation;
|
||||
const telemetry = observation.telemetry || {};
|
||||
const source = target.sources?.find(source => source.observation.receiver_id === observation.receiver_id);
|
||||
return {
|
||||
uasId: observation.target_id, model: resolveModel(observation.target_id, telemetry.model || telemetry.name, rules, telemetry.serial) || 'RID 目标', bssid: telemetry.mac,
|
||||
lat: observation.latitude, lng: observation.longitude, alt: observation.altitude_m,
|
||||
pilotLat: telemetry.pilot_position?.[1], pilotLng: telemetry.pilot_position?.[0],
|
||||
geometricAltitude: telemetry.geometric_altitude_m, pressureAltitude: telemetry.pressure_altitude_m,
|
||||
heightAgl: telemetry.height_agl_m, relativeHeight: telemetry.relative_height_m,
|
||||
speed: telemetry.speed_mps, rssi: telemetry.rssi, heading: observation.heading_deg,
|
||||
source: observation.receiver_id, time: timestamp(target.received_at_ms), online: true,
|
||||
sourceCount: target.sources?.length || 1,
|
||||
receivedAtMs: source?.received_at_ms ?? target.received_at_ms, positionGeneration: target.position_generation,
|
||||
sampleId: [observation.receiver_id, observation.source_epoch, observation.sequence].join(':'),
|
||||
...registrationInfo(ownership.get(observation.target_id)),
|
||||
flightClass: flightAssessments.get(observation.target_id)?.class || "unknown",
|
||||
flightReason: flightAssessments.get(observation.target_id)?.reason,
|
||||
positionUnverified: telemetry.position_unverified === true
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function projectFence(fence) {
|
||||
const geometry = fence.geometry;
|
||||
const point = ([lng, lat]) => ({ lat, lng });
|
||||
let type = geometry.type;
|
||||
let points = geometry.vertices?.map(point);
|
||||
if (type === 'circle') points = [{ ...point(geometry.center), radius: geometry.radius_m }];
|
||||
if (type === 'polygon' && points.length === 4
|
||||
&& new Set(points.map(point => point.lat)).size === 2
|
||||
&& new Set(points.map(point => point.lng)).size === 2) {
|
||||
type = 'rectangle';
|
||||
points = [points[0], points[2]];
|
||||
}
|
||||
return { id: fence.id, name: fence.name, enabled: fence.enabled, type, points };
|
||||
}
|
||||
async function saveZone(method, id, body) {
|
||||
const snapshot = await request('/api/geofences');
|
||||
const existing = snapshot.entries.find(zone => zone.id === id);
|
||||
if (id && !existing) throw new Error('防控区已变更,请刷新后重试');
|
||||
if (method === 'DELETE') {
|
||||
await request(`/api/geofences/${encodeURIComponent(id)}?revision=${snapshot.revision}`, method);
|
||||
return { ok: true };
|
||||
}
|
||||
if (!id) id = `zone-${crypto.randomUUID()}`;
|
||||
const coord = point => [point.lng, point.lat];
|
||||
let geometry = existing?.geometry;
|
||||
if (!geometry && body.type === 'circle') {
|
||||
geometry = { type: 'circle', center: coord(body.points[0]), radius_m: body.points[0].radius };
|
||||
} else if (!geometry && body.type === 'rectangle') {
|
||||
const [a, b] = body.points;
|
||||
geometry = { type: 'polygon', vertices: [coord(a), [a.lng, b.lat], coord(b), [b.lng, a.lat]] };
|
||||
} else if (!geometry) {
|
||||
geometry = { type: 'polygon', vertices: body.points.map(coord) };
|
||||
}
|
||||
await request(`/api/geofences/${encodeURIComponent(id)}`, 'PUT', {
|
||||
expected_revision: snapshot.revision, fence: { id, name: body.name, enabled: body.enabled === true, geometry }
|
||||
});
|
||||
return { ok: true, id };
|
||||
}
|
||||
|
||||
function timestamp(ms) {
|
||||
return new Date(ms).toLocaleString('sv-SE', { hourCycle: 'h23' });
|
||||
}
|
||||
function dateArgument(value, fallback) {
|
||||
if (!value) return fallback;
|
||||
const result = new Date(value.replace(' ', 'T')).getTime();
|
||||
if (!Number.isSafeInteger(result) || result < 0) throw new Error('日期范围无效');
|
||||
return result;
|
||||
}
|
||||
function range(query) {
|
||||
return {
|
||||
fromMs: dateArgument(query.get('start'), 0),
|
||||
toMs: dateArgument(query.get('end'), Date.now()),
|
||||
q: query.get('keyword') || ''
|
||||
};
|
||||
}
|
||||
async function events(query, limit = 100, offset, center = false) {
|
||||
const { fromMs, toMs, q } = range(query);
|
||||
const params = new URLSearchParams({ limit, from_ms: fromMs, to_ms: toMs, q: q === '未登记' || q === '未登记无人机告警' ? '' : q });
|
||||
if (q === '未登记' || q === '未登记无人机告警') params.set('type','unregistered');
|
||||
if (query.get('type')) params.set('type',query.get('type'));
|
||||
if (query.get('handled')) params.set('handled', query.get('handled') === '1' ? '1' : '0');
|
||||
if (offset !== undefined) params.set('offset', offset);
|
||||
if (query.has('before')) params.set('before', query.get('before'));
|
||||
if (query.has('after')) params.set('after', query.get('after'));
|
||||
if (query.has('counts')) params.set('counts', '1');
|
||||
const data = await request(`/api/monitoring/${center ? 'center' : 'events'}?${params}`);
|
||||
const alerts = data.entries.map(event => ({
|
||||
id: event.id, time: timestamp(event.occurred_at_ms), timeMs: event.occurred_at_ms,
|
||||
uasId: event.target_id, lat: event.latitude, lng: event.longitude, kind: event.event_type,
|
||||
type: window.ridFlightStatus.meta(event.event_type).label,
|
||||
message: event.event_type === 'unregistered' ? '设备登记中未找到该目标' : event.fence_name || event.target_id,
|
||||
handled: event.acknowledged_at_ms != null,
|
||||
acknowledgedBy: event.acknowledged_by
|
||||
}));
|
||||
return { alerts, count: data.total ?? alerts.length, read: data.read, unread: data.unread };
|
||||
}
|
||||
|
||||
async function getFlights(query) {
|
||||
const params = new URLSearchParams({ ...range(query), limit: 120 });
|
||||
const response = await request('/api/workbench/observations?' + params);
|
||||
const flights = response.entries.map(row => ({
|
||||
uasId: row.targetId, flightId: row.flightKey, model: row.model || row.targetId,
|
||||
start: timestamp(row.timeMs), end: row.endMs == null ? '接收中' : timestamp(row.endMs),
|
||||
lastLat: row.latitude, lastLng: row.longitude
|
||||
}));
|
||||
return { flights, total: response.total };
|
||||
}
|
||||
|
||||
async function getPoints(flightKey) {
|
||||
const points = [];
|
||||
let after = 0;
|
||||
do {
|
||||
const params = new URLSearchParams({ flightKey, after, limit: 5000 });
|
||||
const row = await request('/api/history/flight-points?' + params);
|
||||
points.push(...row.entries);
|
||||
after = row.nextAfter;
|
||||
} while (after);
|
||||
return window.ridDroneMap.prepareTrack(points).points.map(point => {
|
||||
const osd = point.osd || {};
|
||||
return {
|
||||
lat: point.latitude, lng: point.longitude, alt: point.altitudeM,
|
||||
heading: point.headingDeg, time: timestamp(point.timeMs), timeMs: point.timeMs, segmentStart: point.segmentStart,
|
||||
speed: osd.speedMps, verticalSpeed: osd.verticalSpeedMps, rssi: osd.rssi,
|
||||
height: osd.heightAglM, relativeHeight: osd.relativeHeightM,
|
||||
geometricAltitude: osd.geometricAltitudeM, pressureAltitude: osd.pressureAltitudeM,
|
||||
pilotLat: osd.pilotPosition?.[1], pilotLng: osd.pilotPosition?.[0]
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function summary() {
|
||||
const midnight = new Date();
|
||||
midnight.setHours(0, 0, 0, 0);
|
||||
const [live, links, rows, fences, lists, recentAlerts, historyStats, alertStats] = await Promise.all([
|
||||
liveRows(), sourceStatus(), receiverRows(), request('/api/geofences'), request('/api/target-lists'),
|
||||
events(new URLSearchParams(), 6).then(result => result.alerts), request(`/api/history/summary?fromMs=${midnight.getTime()}`),
|
||||
request(`/api/monitoring/summary?from_ms=${midnight.getTime()}`)
|
||||
]);
|
||||
const userData = await request('/api/auth/users').catch(error => {
|
||||
if (error.status !== 403) throw error;
|
||||
});
|
||||
return {
|
||||
...links, onlineCount: live.length, targetCount: live.length, zones: fences.entries.length,
|
||||
deviceTotal: rows.length, userTotal: userData?.entries.length, registryTotal: lists.entries.length,
|
||||
recentAlerts, recentRecords: historyStats.recent.map(point => ({ time: timestamp(point.timeMs), uasId: point.targetId, lat: point.latitude, lng: point.longitude })),
|
||||
recordsToday: historyStats.since, recordsTotal: historyStats.total, alertsToday: alertStats.since, alertsTotal: alertStats.total
|
||||
};
|
||||
}
|
||||
|
||||
async function read(route, params) {
|
||||
switch (route) {
|
||||
case '/api/current_user': {
|
||||
const account = await request('/api/auth/status');
|
||||
if (!account.authenticated) { location.replace('/workbench/'); throw new Error('请重新登录'); }
|
||||
return { user: { displayName: account.username, role: roleLabel(account.role), canAcknowledge: ['admin', 'operator'].includes(account.role) } };
|
||||
}
|
||||
case '/api/platform_configs': {
|
||||
const prefs = await request('/api/maps/preferences');
|
||||
return { configs: [{ key: 'default_map', value: prefs.basemap === 'road' ? 'tdt-vector' : 'tdt-satellite' }] };
|
||||
}
|
||||
case '/api/status': return sourceStatus();
|
||||
case '/api/drones': {
|
||||
const [drones, status] = await Promise.all([liveRows(), sourceStatus()]);
|
||||
return { drones, count: drones.length, onlineCount: drones.length, status };
|
||||
}
|
||||
case '/api/ports': return (await request('/api/receiver/ports')).ports.map(device => ({ device }));
|
||||
case '/api/zones': return (await request('/api/geofences')).entries.map(projectFence);
|
||||
case '/api/alerts': params.set('counts', '1'); return events(params, 50, undefined, true);
|
||||
case '/api/alerts_query': return events(params, 50, params.get('offset') ?? 0);
|
||||
case '/api/local_stations': return { stations: (await receiverRows()).filter(isStation).map(row => {
|
||||
const { connected, receiving, message } = link(row);
|
||||
return {
|
||||
id: row.id, name: row.name, sn: row.hardwareId, endpoint: row.status.endpoint,
|
||||
transport: row.config.transport,
|
||||
deviceIp: row.status.lastPeerIp || row.config.peerIp,
|
||||
gnss: row.status.gnss,
|
||||
status: message, linkState: receiving ? 'online' : connected ? 'waiting' : 'offline'
|
||||
};
|
||||
}) };
|
||||
case '/api/local_fusion_info': return { sources: await sourceStatus() };
|
||||
case '/api/flights': return getFlights(params);
|
||||
case '/api/flight_track': return { points: await getPoints(params.get('flightId')) };
|
||||
case '/api/monitor_summary': return summary();
|
||||
case '/api/map_cache/status': {
|
||||
const state = await request('/api/maps/status');
|
||||
return { enabled: true, offlineOnly: state.mode === 'offline', hasTdtKey: state.keyConfigured };
|
||||
}
|
||||
default: throw new Error('此功能尚未接入本阶段');
|
||||
}
|
||||
}
|
||||
|
||||
async function mutate(route, method, body) {
|
||||
if (route === '/api/zones' || route.startsWith('/api/zones/')) return saveZone(method, route.split('/')[3], body);
|
||||
switch (route) {
|
||||
case '/api/logout': return request('/api/auth/logout', 'POST');
|
||||
case '/api/connect': return changeSerial(body, true);
|
||||
case '/api/disconnect':
|
||||
case '/api/release_port': return changeSerial(body, false);
|
||||
case '/api/alerts_query':
|
||||
return request(`/api/monitoring/events/${encodeURIComponent(body.id)}/acknowledgement`, 'PUT', {});
|
||||
default: throw new Error('此功能尚未接入本阶段');
|
||||
}
|
||||
}
|
||||
|
||||
function roleLabel(role) {
|
||||
return ({ admin: '管理员', operator: '操作员', viewer: '只读用户' })[role] || '未知角色';
|
||||
}
|
||||
|
||||
window.ridWorkbenchApi = Object.freeze({
|
||||
request, modelRules, resolveModel, roleLabel, getRecordPoints: getPoints, cachedLiveRows, detectionReceiver,
|
||||
async registration(target) { return registrationInfo((await registrations([target])).get(target)); },
|
||||
preferences: () => request('/api/maps/preferences'),
|
||||
async fetch(path, options = {}) {
|
||||
const url = new URL(path, location.origin);
|
||||
try {
|
||||
if (url.origin !== location.origin) throw new Error('仅允许访问本机 RID 接口');
|
||||
const method = options.method || 'GET';
|
||||
const body = typeof options.body === 'string' ? JSON.parse(options.body) : {};
|
||||
return Response.json(method === 'GET' ? await read(url.pathname, url.searchParams) : await mutate(url.pathname, method, body));
|
||||
} catch (error) {
|
||||
return Response.json({ ok: false, message: error.message, error: error.message }, { status: error.status || 400 });
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启动本地服务,页面就绪后自动打开系统默认浏览器。保持程序窗口打开;关闭浏览器页面不会停止服务,关闭程序窗口才会退出。也可使用 `启动Rust版.cmd`。不需要安装 Rust 或 Node.js;包含 USB/UDP/TCP 接收传输层;厂商 RID 解析需协议适配,不包含原版设备写入上位机。
|
||||
|
||||
浏览器未自动打开时,可手动访问 http://127.0.0.1:8787/ 。命令行加 `--no-browser` 可只启动服务,供自动化测试或手动打开页面使用。启动失败(例如 8787 端口被占用)时不会打开浏览器,可用 `启动Rust版.cmd` 查看错误。
|
||||
浏览器未自动打开时,可手动访问 http://127.0.0.1:8787/workbench/ 。命令行加 `--no-browser` 可只启动服务,供自动化测试或手动打开页面使用。启动失败(例如 8787 端口被占用)时不会打开浏览器,可用 `启动Rust版.cmd` 查看错误。
|
||||
|
||||
默认数据目录是 exe 所在目录,不是命令行当前目录。目录必须可写,不要放在 Program Files。数据库仍为 `registry/data/registry.sqlite`,自动档案仍在 `档案库/`。高级用法:`fpv-rid-registry.exe --data-root "D:\我的备案"`。
|
||||
|
||||
@@ -14,13 +14,15 @@ Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启
|
||||
|
||||
地图框选下载需保留发布包内与主程序同目录的 `rid-map-downloader.exe`,不要只分发主 EXE。目标电脑无需安装 Go 或 Rust。程序优先使用有效的 `RID_MAP_DOWNLOADER` 路径;未设置或指向不存在的文件时,自动使用程序同目录的下载器。源码目录的 `启动Rust版.cmd` 会为本机 Release 版本设置统一工具目录中的下载器路径。
|
||||
|
||||
程序启动时自动创建数据目录中的 `maps/offline/` 文件夹,不需要手动建目录。下载时自动在其中按图层、缩放级别和瓦片坐标创建子目录;再次启动保留已有地图。默认数据目录为 EXE 所在目录;使用 `--data-root` 时保存在指定的数据目录内。
|
||||
发布包解压后,EXE 旁已带有 `map_cache/` 文件夹。可以从地图管理下载所需范围,或把已有离线瓦片放入该目录,程序会自动读取。默认启动时数据目录为 EXE 所在目录。使用 `--data-root` 时,新下载保存在指定数据目录下,同时读取 EXE 旁的 `map_cache/` 和数据目录中已有的 `maps/offline/`。
|
||||
|
||||
首次下载未缓存的区域需要联网,并在数据目录的 `config.json` 中配置有效的 `maps.tianditu_token`(也支持启动环境变量 `TIANDITU_TOKEN` 或旧版 `maps/config.json`)。发布包不包含业务数据或天地图密钥。下载结果保存在数据目录的 `maps/offline/`,下载完成后可离线使用相应区域、图层和层级;失败或取消的任务不代表完整离线覆盖。
|
||||
首次下载未缓存的区域需要联网,并使用可用的天地图授权。可以通过数据目录的 `config.json` 设置 `maps.tianditu_token`,也支持启动环境变量 `TIANDITU_TOKEN` 或旧版 `maps/config.json`。下载完成后可离线使用相应区域、图层和层级。失败或取消后可重试,已完成的瓦片会复用。
|
||||
|
||||
## 编辑和照片
|
||||
|
||||
启动后进入 B1 玻璃工具卡片首页,点击“设备登记”“实时目标”或“设置”进入对应应用。首页不显示左侧菜单;进入应用后恢复菜单和顶部工具栏,可通过顶部“应用”按钮返回首页。菜单收起状态在当前浏览器会话内保留。
|
||||
首次启动先创建管理员,后续使用已有账号登录。登录后进入地图工作台,顶部可打开设备台账、记录查询、排名统计和我的平台,也可直接进入原有的设备登记和本地档案。记录查询使用接收器已解码且被平台接受的 RID 记录,保留最近 30 天且最多 30 万条。升级前的轨迹仍可从历史回放检索。
|
||||
|
||||
管理员可在“用户管理”创建操作员和只读账号。操作员可维护登记、名单、防控区及告警处置。只读账号可查看业务页面。接收器配置、型号规则、平台设置和账号管理由管理员维护。修改、停用或删除附加账号会让对应会话退出。
|
||||
|
||||
设备登记使用档案侧栏;实时工作台使用地图浮层,目录和详情可收起,底部可打开接收器配置。没有真实接收数据时不生成示例目标。未匹配本地登记不代表违法或未官方备案。
|
||||
|
||||
@@ -61,7 +63,7 @@ Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启
|
||||
|
||||
本仓库将稳定工具链固定为 1.99.1。已有终端若未刷新环境,可先在 PowerShell 执行 `. ./scripts/rust-env.ps1`。Rust 编译依赖保存在 util/cargo/registry;Windows SDK、Visual Studio 等共享组件保留在原安装目录。
|
||||
|
||||
`scripts/package.ps1` 通过独立暂存目录及六文件白名单,生成 `dist/FPV-RID-Rust/`、Windows ZIP 和两份 SHA-256 清单,不打包备案数据。若已有发布目录含数据库、档案或其他非发布文件,脚本会停止并保留原内容及旧 ZIP;请使用 `./scripts/package.ps1 -OutputRoot "D:\单独发布目录"` 指定干净输出目录。禁止把正在使用的数据目录作为打包暂存目录。
|
||||
`scripts/package.ps1` 通过独立暂存目录及发布文件白名单,生成 `dist/FPV-RID-Rust/`、Windows ZIP 和两份 SHA-256 清单,不打包备案数据。若已有发布目录含数据库、档案或其他非发布文件,脚本会停止并保留原内容及旧 ZIP;请使用 `./scripts/package.ps1 -OutputRoot "D:\单独发布目录"` 指定干净输出目录。禁止把正在使用的数据目录作为打包暂存目录。
|
||||
|
||||
`node scripts/verify.mjs` 在独立临时目录执行 Rust Release 版接口、导出、重启和旧数据导入验收;Node.js 仅作为开发测试工具;`powershell -ExecutionPolicy Bypass -File scripts/test-package.ps1` 验证重复打包、运行数据隔离及校验和。临时验收目录保留作为证据,不触及正式数据。
|
||||
|
||||
@@ -69,7 +71,7 @@ Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启
|
||||
|
||||
当前登记交互和二维码生成均由 Rust/Wasm 实现,原 JavaScript 业务文件已移除。地图引擎仍包含固定版本的第三方 JavaScript,少量模块加载和地图互操作代码用于接入浏览器。
|
||||
|
||||
从登记页进入“实时目标研判”,或访问 `/realtime`。采用已选择的 C 布局,显示目标目录、地图、GPU 目标图层与选中目标详情。在线优先使用天地图,失败后自动读取本地离线资源。轨迹只保留当前选择目标最近 30 秒、最多 200 点;标签最多一个。请在启动环境配置 TIANDITU_TOKEN,并将实际离线资源放入 exe 旁 maps/offline/。支持 vec_w、cva_w 的 XYZ 栅格目录或同名 MBTiles(默认 TMS 行号)。没有数据覆盖时会提示缺失,网格不等于街道或卫星底图。
|
||||
从登记页进入“实时目标研判”,或访问 `/realtime`。采用已选择的 C 布局,显示目标目录、地图、GPU 目标图层与选中目标详情。轨迹只保留当前选择目标最近 30 秒、最多 200 点;标签最多一个。地图会自动读取 EXE 旁的 `map_cache/`,支持 `vec_w`、`cva_w`、`img_w`、`cia_w` 的 XYZ 栅格目录或同名 MBTiles(默认 TMS 行号)。
|
||||
|
||||
首次启动默认不启用设备接收、不生成模拟数据;已保存为启用的接收配置会在后续启动自动重连。合成输入仅在 `--simulation-api` 模式开启,目标状态只在内存保存,30 秒未更新自动过期。不得把隔离测试结果当成真实 RID 接收或设备到屏幕的延迟验收。
|
||||
|
||||
@@ -79,4 +81,12 @@ Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启
|
||||
|
||||
在实时目标页展开“电脑接收设置”,当前 USB 请选择真实 COM 号与设备要求的波特率,未知厂商格式先用原始诊断。可以复制最近 4 KiB 字节用于协议适配。串口打开或端口监听成功不代表已解码出真实 RID 位置。
|
||||
|
||||
UDP/TCP 为电脑监听模式:填写电脑本机 IP 和接收端口,再用模块工具把目标地址设置为这台电脑。程序不自动写入未知厂商的模块配置命令。配置保存在数据目录 receiver-config.json,禁用会释放监听与串口。
|
||||
UDP/TCP 为电脑监听模式:填写电脑本机 IP 和接收端口,再用模块工具把目标地址设置为这台电脑。程序不自动写入未知厂商的模块配置命令。配置保存在数据目录 receivers.json,禁用会释放监听与串口。
|
||||
|
||||
## 携带离线地图的发布包
|
||||
|
||||
在 PowerShell 执行:
|
||||
|
||||
./scripts/package.ps1 -OutputRoot 'D:\RID交付' -MapSeedRoot 'D:\当前数据目录\map_cache'
|
||||
|
||||
发布脚本将受支持的 XYZ 和 MBTiles 文件放到 EXE 旁的 `map_cache/`,也接受旧的 `maps/` 作为种子目录。首次双击 EXE 时自动创建空数据库。已有账户、档案和密钥继续留在原数据目录,迁移时请按上文停机备份。离线可用范围取决于包内图层与瓦片,可在应用的“地图管理”补充所需区域。
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ridTools = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0'
|
||||
$env:GOCACHE = 'D:/Rust_Contact/util/tools/go-cache'
|
||||
$env:GOMODCACHE = 'D:/Rust_Contact/util/tools/go-modules'
|
||||
$ridGo = (Get-Command go -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1).Source
|
||||
if (-not $ridGo) { $ridGo = 'D:/Rust_Contact/util/tools/go/1.27.4/go/bin/go.exe' }
|
||||
if (-not (Test-Path -LiteralPath $ridGo -PathType Leaf)) {
|
||||
throw '找不到 Go。请将 go.exe 加入 PATH 或安装到项目统一工具目录。'
|
||||
}
|
||||
New-Item -ItemType Directory -Force $ridTools | Out-Null
|
||||
Push-Location (Join-Path $PSScriptRoot 'map-downloader')
|
||||
try {
|
||||
go test ./...
|
||||
& $ridGo test ./...
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader tests failed' }
|
||||
go build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
|
||||
& $ridGo build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader build failed' }
|
||||
Copy-Item -LiteralPath 'LICENSE-upstream.txt' -Destination $ridTools
|
||||
$env:RID_MAP_DOWNLOADER = Join-Path $ridTools 'rid-map-downloader.exe'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$OutputRoot)
|
||||
param([string]$OutputRoot, [string]$MapSeedRoot)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot 'rust-env.ps1')
|
||||
@@ -7,10 +7,21 @@ if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
|
||||
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
|
||||
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
|
||||
$ridWhitelist = @('fpv-rid-registry.exe', 'rid-map-downloader.exe', 'map-downloader-LICENSE.txt', '启动Rust版.cmd', '使用说明.md', 'config.example.json', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
|
||||
$ridTarget = 'x86_64-pc-windows-msvc'
|
||||
$ridMapReadme = '程序自动读取 EXE 同目录的 map_cache。请从地图管理下载离线瓦片,或将已有瓦片放入此目录。'
|
||||
|
||||
function Assert-CleanDestination {
|
||||
if (Test-Path -LiteralPath $ridDestination) {
|
||||
foreach ($ridEntry in Get-ChildItem -LiteralPath $ridDestination -Force) {
|
||||
if ($ridEntry.PSIsContainer -and $ridEntry.Name -eq 'map_cache' -and
|
||||
!($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
$files = @(Get-ChildItem -LiteralPath $ridEntry.FullName -Force)
|
||||
if ($files.Count -eq 0 -or ($files.Count -eq 1 -and $files[0].Name -eq 'README.txt' -and
|
||||
!$files[0].PSIsContainer -and !($files[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -and
|
||||
([IO.File]::ReadAllText($files[0].FullName).TrimEnd() -ceq $ridMapReadme))) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if ($ridEntry.PSIsContainer -or ($ridEntry.Name -notin $ridWhitelist -and $ridEntry.Name -ne 'qrcode-LICENSE.txt') -or
|
||||
($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "发布目录含运行数据或非发布文件,已停止打包并保留原内容:$($ridEntry.FullName)。请通过 -OutputRoot 指定单独的输出目录。"
|
||||
@@ -19,6 +30,41 @@ function Assert-CleanDestination {
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RidMapSeed([string]$Root) {
|
||||
$rootItem = Get-Item -LiteralPath $Root -Force
|
||||
if (-not $rootItem.PSIsContainer -or ($rootItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "地图种子目录必须为普通目录:$Root"
|
||||
}
|
||||
$kinds = if ($rootItem.Name -eq 'map_cache') { @('portable') } else { @('cache', 'offline') }
|
||||
foreach ($kind in $kinds) {
|
||||
$source = if ($kind -eq 'portable') { $rootItem.FullName } else { Join-Path $rootItem.FullName $kind }
|
||||
$destination = if ($kind -eq 'portable') { 'map_cache' } else { "maps/$kind" }
|
||||
if (-not (Test-Path -LiteralPath $source)) { continue }
|
||||
$sourceItem = Get-Item -LiteralPath $source -Force
|
||||
if (-not $sourceItem.PSIsContainer -or ($sourceItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "不能从链接或非目录读取地图:$source"
|
||||
}
|
||||
foreach ($item in Get-ChildItem -LiteralPath $source -Recurse -Force) {
|
||||
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
|
||||
throw "地图种子目录含链接:$($item.FullName)"
|
||||
}
|
||||
if ($item.PSIsContainer) { continue }
|
||||
$relative = $item.FullName.Substring($source.Length + 1).Replace('\','/')
|
||||
$layer = '(vec_w|cva_w|img_w|cia_w)'
|
||||
if ($kind -ne 'cache' -and $relative -cmatch "^$layer[.]mbtiles$") {
|
||||
[pscustomobject]@{ Source=$item.FullName; Path="$destination/$relative" }
|
||||
} elseif ($relative -cmatch "^$layer/([0-9]{1,2})/([0-9]{1,7})/([0-9]{1,7})[.](tile|png|jpg|jpeg)$") {
|
||||
$z = [int]$Matches[2]
|
||||
$x = [int]$Matches[3]
|
||||
$y = [int]$Matches[4]
|
||||
if ($z -le 18 -and $x -lt (1 -shl $z) -and $y -lt (1 -shl $z) -and ($kind -ne 'cache' -or $Matches[5] -eq 'tile')) {
|
||||
[pscustomobject]@{ Source=$item.FullName; Path="$destination/$relative" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RidSourceManifest {
|
||||
$ridInputs = @('Cargo.toml','Cargo.lock','rust-toolchain.toml','build.rs','config.example.json') | ForEach-Object { Get-Item -LiteralPath (Join-Path $ridRepo $_) }
|
||||
$ridInputs += @('src','crates','xtask','scripts','.cargo') | ForEach-Object { Get-ChildItem -LiteralPath (Join-Path $ridRepo $_) -Recurse -File }
|
||||
@@ -27,6 +73,13 @@ function Get-RidSourceManifest {
|
||||
|
||||
# Refuse a used deployment folder before building or changing any published files.
|
||||
Assert-CleanDestination
|
||||
$ridSeedFiles = @()
|
||||
$ridPaths = $ridWhitelist + 'map_cache/README.txt'
|
||||
if ($MapSeedRoot) {
|
||||
$ridSeedFiles = @(Get-RidMapSeed $MapSeedRoot | Sort-Object Path)
|
||||
$ridPaths += 'registry/data/README.txt'
|
||||
$ridPaths += @($ridSeedFiles | ForEach-Object Path)
|
||||
}
|
||||
& (Join-Path $PSScriptRoot 'build-map-downloader.ps1')
|
||||
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
|
||||
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
|
||||
@@ -41,24 +94,37 @@ try {
|
||||
$ridInitialManifestJson = ConvertTo-Json -InputObject $ridInitialManifest -Depth 5 -Compress
|
||||
cargo xtask web
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Rust frontend build failed' }
|
||||
cargo build --release --locked -p fpv-rid-registry
|
||||
cargo build --release --locked -p fpv-rid-registry --target $ridTarget
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release build failed' }
|
||||
$ridMetadata = cargo metadata --locked --format-version 1 --no-deps | ConvertFrom-Json
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
|
||||
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
|
||||
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory "$ridTarget/release/fpv-rid-registry-fullstack.exe") -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
|
||||
Copy-Item -LiteralPath $env:RID_MAP_DOWNLOADER -Destination (Join-Path $ridStage 'rid-map-downloader.exe')
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'map-downloader/LICENSE-upstream.txt') -Destination (Join-Path $ridStage 'map-downloader-LICENSE.txt')
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'config.example.json') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'third-party-licenses.txt')
|
||||
Get-Content -LiteralPath (Join-Path $ridRepo 'crates/web-ui/workbench/leaflet/LICENSE.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'third-party-licenses.txt') -Encoding utf8
|
||||
$ridLicenses = cargo tree --workspace --locked --prefix none --format '{p} {l}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Dependency inventory failed' }
|
||||
$ridLicenses | Set-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
|
||||
Get-Content -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
|
||||
Get-Content -LiteralPath (Join-Path $ridStage 'third-party-licenses.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
|
||||
$ridSourceManifest = @(Get-RidSourceManifest)
|
||||
if ((ConvertTo-Json -InputObject $ridSourceManifest -Depth 5 -Compress) -ne $ridInitialManifestJson) { throw '源码在构建期间发生变化,已停止发布并保留原发布包;请在源码稳定后重新构建。' }
|
||||
foreach ($ridSeed in $ridSeedFiles) {
|
||||
$ridSeedDestination = Join-Path $ridStage $ridSeed.Path
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $ridSeedDestination -Parent) | Out-Null
|
||||
Copy-Item -LiteralPath $ridSeed.Source -Destination $ridSeedDestination
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $ridStage 'map_cache') | Out-Null
|
||||
$ridMapReadme | Set-Content -LiteralPath (Join-Path $ridStage 'map_cache/README.txt') -Encoding utf8
|
||||
if ($MapSeedRoot) {
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $ridStage 'registry/data') | Out-Null
|
||||
'应用首次启动时在此创建 SQLite 数据库。已有业务数据请在停机备份后单独迁移。' |
|
||||
Set-Content -LiteralPath (Join-Path $ridStage 'registry/data/README.txt') -Encoding utf8
|
||||
}
|
||||
$ridBuildInfo = [ordered]@{
|
||||
builtAtUtc=[DateTime]::UtcNow.ToString('o')
|
||||
gitRevision=(git rev-parse HEAD)
|
||||
@@ -67,23 +133,31 @@ try {
|
||||
trunk='0.22.0'
|
||||
wasmBindgen='0.2.129'
|
||||
executableSha256=(Get-FileHash -LiteralPath (Join-Path $ridStage 'fpv-rid-registry.exe') -Algorithm SHA256).Hash
|
||||
mapSeedFileCount=$ridSeedFiles.Count
|
||||
sourceManifest=$ridSourceManifest
|
||||
}
|
||||
$ridBuildInfo | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $ridStage 'build-info.json') -Encoding utf8
|
||||
$ridWhitelist | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
|
||||
$ridPaths | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
|
||||
'{0} {1}' -f (Get-FileHash -LiteralPath (Join-Path $ridStage $_) -Algorithm SHA256).Hash, $_
|
||||
} | Set-Content -LiteralPath (Join-Path $ridStage 'SHA256SUMS.txt') -Encoding utf8
|
||||
|
||||
$ridActual = @(Get-ChildItem -LiteralPath $ridStage -Force)
|
||||
if ($ridActual.Count -ne $ridWhitelist.Count -or @($ridActual | Where-Object { $_.PSIsContainer -or $_.Name -notin $ridWhitelist }).Count) {
|
||||
$ridActual = @(Get-ChildItem -LiteralPath $ridStage -Recurse -File -Force | ForEach-Object {
|
||||
$_.FullName.Substring($ridStage.Length + 1).Replace('\','/')
|
||||
})
|
||||
if ($ridActual.Count -ne $ridPaths.Count -or @(Compare-Object $ridActual $ridPaths -CaseSensitive).Count) {
|
||||
throw 'Staging directory does not match the release whitelist'
|
||||
}
|
||||
# Only the fresh, checked staging tree is ever compressed.
|
||||
Compress-Archive -LiteralPath $ridStage -DestinationPath $ridTemporaryZip
|
||||
Assert-CleanDestination
|
||||
New-Item -ItemType Directory -Force -Path $ridDestination | Out-Null
|
||||
foreach ($ridName in $ridWhitelist) {
|
||||
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination (Join-Path $ridDestination $ridName)
|
||||
foreach ($ridName in $ridPaths) {
|
||||
$ridPublishFile = Join-Path $ridDestination $ridName
|
||||
$ridParent = Split-Path $ridPublishFile -Parent
|
||||
if (-not (Test-Path -LiteralPath $ridParent)) {
|
||||
New-Item -ItemType Directory -Force -Path $ridParent | Out-Null
|
||||
}
|
||||
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination $ridPublishFile
|
||||
}
|
||||
$ridObsoleteLicense = Join-Path $ridDestination 'qrcode-LICENSE.txt'
|
||||
if (Test-Path -LiteralPath $ridObsoleteLicense -PathType Leaf) { Remove-Item -LiteralPath $ridObsoleteLicense }
|
||||
@@ -98,11 +172,19 @@ try {
|
||||
if ($ridBuildLock) { $ridBuildLock.Dispose() }
|
||||
Pop-Location
|
||||
# Clean only files this invocation created. Never recursively delete an output directory.
|
||||
foreach ($ridName in $ridWhitelist) {
|
||||
foreach ($ridName in $ridPaths) {
|
||||
$ridOwnedFile = Join-Path $ridStage $ridName
|
||||
if (Test-Path -LiteralPath $ridOwnedFile -PathType Leaf) { Remove-Item -LiteralPath $ridOwnedFile }
|
||||
}
|
||||
if (Test-Path -LiteralPath $ridTemporaryZip -PathType Leaf) { Remove-Item -LiteralPath $ridTemporaryZip }
|
||||
if ((Test-Path -LiteralPath $ridStage -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStage -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStage }
|
||||
if (Test-Path -LiteralPath $ridStage -PathType Container) {
|
||||
Get-ChildItem -LiteralPath $ridStage -Directory -Recurse -Force |
|
||||
Sort-Object { $_.FullName.Length } -Descending | ForEach-Object {
|
||||
if (@(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0) {
|
||||
[IO.Directory]::Delete($_.FullName, $false)
|
||||
}
|
||||
}
|
||||
if (@(Get-ChildItem -LiteralPath $ridStage -Force).Count -eq 0) { [IO.Directory]::Delete($ridStage, $false) }
|
||||
}
|
||||
if ((Test-Path -LiteralPath $ridStageRoot -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStageRoot -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStageRoot }
|
||||
}
|
||||
|
||||
@@ -7,38 +7,78 @@ import vm from 'node:vm';
|
||||
const source=(await readFile(new URL('../crates/web-ui/public/history-map-adapter.js',import.meta.url),'utf8'))
|
||||
.replace(/^import .*;$/gm,'').replaceAll('export function ','function ');
|
||||
|
||||
test('historical segments stay separate and playback moves only the marker',()=>{
|
||||
const markerSource=await readFile(new URL('../crates/web-ui/workbench/drone-map.js',import.meta.url),'utf8');
|
||||
|
||||
test('replay keeps real segments, changes its basemap and advances the marker on the route',async()=>{
|
||||
let map,marker,fitCount=0,removed=false;
|
||||
const sources=new Map();
|
||||
class FakeMap{
|
||||
constructor(){map=this;this.handlers={};}
|
||||
constructor(options){
|
||||
map=this;this.handlers={};this.style=options.style;
|
||||
for(const [id,value] of Object.entries(this.style.sources)) this.addSource(id,value);
|
||||
}
|
||||
on(name,fn){this.handlers[name]=fn;}
|
||||
addControl(){}
|
||||
addSource(id,value){sources.set(id,{data:value.data,setData(data){this.data=data;}});}
|
||||
addSource(id,value){sources.set(id,{...value,setData(data){this.data=data;},setTiles(tiles){this.tiles=tiles;}});}
|
||||
addLayer(){}
|
||||
getSource(id){return sources.get(id);}
|
||||
getLayer(id){return this.style.layers.find(layer=>layer.id===id);}
|
||||
setLayoutProperty(id,key,value){this.getLayer(id).layout[key]=value;}
|
||||
fitBounds(){fitCount++;}
|
||||
resize(){}
|
||||
remove(){removed=true;}
|
||||
}
|
||||
class Marker{setLngLat(point){this.position=[...point];marker=this;return this;}addTo(){return this;}remove(){}}
|
||||
class Marker{
|
||||
constructor({element}){this.element=element;}
|
||||
getElement(){return this.element;}
|
||||
setLngLat(point){this.position=[...point];marker=this;return this;}
|
||||
getLngLat(){return {lng:this.position[0],lat:this.position[1]};}
|
||||
setRotation(angle){this.angle=angle;return this;}
|
||||
getRotation(){return this.angle;}
|
||||
addTo(){return this;}
|
||||
remove(){}
|
||||
}
|
||||
class MercatorCoordinate{
|
||||
constructor(x,y){Object.assign(this,{x,y});}
|
||||
static fromLngLat([lng,lat]){return new MercatorCoordinate(lng/360,lat/360);}
|
||||
toLngLat(){return {toArray:()=>[this.x*360,this.y*360]};}
|
||||
}
|
||||
class Bounds{constructor(){this.points=[];}extend(point){this.points.push(point);}isEmpty(){return this.points.length===0;}}
|
||||
const context=vm.createContext({window:{dispatchEvent(){}},document:{getElementById(){return {};}},
|
||||
ResizeObserver:class{observe(){}disconnect(){}},Event:class{},Number,Array,Math,
|
||||
ml:{setWorkerUrl(){},Map:FakeMap,Marker,LngLatBounds:Bounds,NavigationControl:class{},AttributionControl:class{}},
|
||||
attachTileBuffer:()=>({destroy(){}})});
|
||||
function element(){
|
||||
const styles = new Map();
|
||||
return {setAttribute(){},append(){},style:{setProperty:(name,value)=>styles.set(name,value),getPropertyValue:name=>styles.get(name)}};
|
||||
}
|
||||
const context=vm.createContext({window:{dispatchEvent(){}},document:{getElementById(){return {};},createElement:element},
|
||||
ResizeObserver:class{observe(){}disconnect(){}},Event:class{},Number,Array,Math,URLSearchParams,
|
||||
fetch:async()=>({ok:true,json:async()=>({entries:[{registered:true}]})}),
|
||||
ml:{setWorkerUrl(){},Map:FakeMap,Marker,MercatorCoordinate,LngLatBounds:Bounds,NavigationControl:class{},AttributionControl:class{}},
|
||||
attachTileBuffer:()=>({destroy(){},schedule(){}})});
|
||||
vm.runInContext(markerSource,context);
|
||||
vm.runInContext(source,context);
|
||||
vm.runInContext('open({longitude:118.77,latitude:32.04,zoom:15,basemap:"road"})',context);
|
||||
vm.runInContext('setPoints([{longitude:118,latitude:32,segmentStart:true},{longitude:119,latitude:32,segmentStart:false},{longitude:120,latitude:32,segmentStart:true},{longitude:121,latitude:32,segmentStart:false}])',context);
|
||||
vm.runInContext('open({longitude:118.77,latitude:32.04,zoom:15,basemap:"road",labels:false})',context);
|
||||
vm.runInContext(`setPoints([
|
||||
{longitude:118,latitude:32,timeMs:1000,headingDeg:90,segmentStart:true},
|
||||
{longitude:119,latitude:32,timeMs:2000,headingDeg:90,segmentStart:false},
|
||||
{longitude:120,latitude:32,timeMs:40000,headingDeg:180,segmentStart:true},
|
||||
{longitude:121,latitude:32,timeMs:41000,headingDeg:180,segmentStart:false}
|
||||
], 'TEST-OWN')`,context);
|
||||
map.handlers['style.load']();
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
assert.equal(marker.getElement().style.getPropertyValue('--rid-drone-fill'),'#26ad72');
|
||||
const features=sources.get('history-track').data.features;
|
||||
assert.equal(features.length,2);
|
||||
assert.deepEqual([...features[0].geometry.coordinates].map(p=>[...p]),[[118,32],[119,32]]);
|
||||
assert.deepEqual([...features[1].geometry.coordinates].map(p=>[...p]),[[120,32],[121,32]]);
|
||||
assert.deepEqual([...features].map(feature=>Array.from(feature.geometry.coordinates, point=>[...point])),
|
||||
[[[118,32],[119,32]],[[120,32],[121,32]]]);
|
||||
assert.equal(fitCount,1);
|
||||
vm.runInContext('setIndex(2)',context);
|
||||
vm.runInContext('setCursor(0,.5)',context);
|
||||
assert.deepEqual(marker.position,[118.5,32]);
|
||||
vm.runInContext('setCursor(1,.5)',context);
|
||||
assert.deepEqual(marker.position,[119,32]);
|
||||
vm.runInContext('setMapOptions({basemap:"imagery",labels:true}); setCursor(2,0)',context);
|
||||
assert.deepEqual([...sources.get('base').tiles],['/api/maps/tile/img_w/{z}/{x}/{y}']);
|
||||
assert.equal(map.getLayer('labels').layout.visibility,'visible');
|
||||
assert.deepEqual(marker.position,[120,32]);
|
||||
assert.equal(fitCount,1,'playback should not recenter the map repeatedly');
|
||||
assert.equal(marker.angle,180);
|
||||
assert.equal(fitCount,1);
|
||||
vm.runInContext('close()',context);
|
||||
assert.ok(removed);
|
||||
});
|
||||
|
||||
@@ -14,6 +14,15 @@ if (-not $ridRejected) { throw 'Dirty deployment folder was accepted' }
|
||||
if ((Get-FileHash -LiteralPath $ridSentinel -Algorithm SHA256).Hash -ne $ridBefore) { throw 'Deployment data was modified' }
|
||||
if (Test-Path -LiteralPath (Join-Path $ridOutput 'FPV-RID-Rust-Windows-x64.zip')) { throw 'Dirty package was published' }
|
||||
|
||||
$ridCacheOutput = Join-Path $ridRoot 'existing-map'
|
||||
$ridExistingTiles = Join-Path $ridCacheOutput 'FPV-RID-Rust/map_cache/img_w/2/1'
|
||||
New-Item -ItemType Directory -Path $ridExistingTiles -Force | Out-Null
|
||||
$ridMapSentinel = Join-Path $ridExistingTiles '2.png'
|
||||
[IO.File]::WriteAllText($ridMapSentinel, 'existing offline tile')
|
||||
$ridRejected = $false
|
||||
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCacheOutput } catch { $ridRejected = $true }
|
||||
if (!$ridRejected -or [IO.File]::ReadAllText($ridMapSentinel) -ne 'existing offline tile') { throw 'Offline map directory was not protected' }
|
||||
|
||||
$ridCleanOutput = Join-Path $ridRoot 'clean'
|
||||
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Clean package failed' }
|
||||
@@ -34,7 +43,7 @@ Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$ridZipPath = Join-Path $ridCleanOutput 'FPV-RID-Rust-Windows-x64.zip'
|
||||
$ridZip = [IO.Compression.ZipFile]::OpenRead($ridZipPath)
|
||||
try {
|
||||
$ridExpected = @('fpv-rid-registry.exe','rid-map-downloader.exe','map-downloader-LICENSE.txt','启动Rust版.cmd','使用说明.md','config.example.json','third-party-licenses.txt','dependency-licenses.txt','build-info.json','SHA256SUMS.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
|
||||
$ridExpected = @('fpv-rid-registry.exe','rid-map-downloader.exe','map-downloader-LICENSE.txt','启动Rust版.cmd','使用说明.md','config.example.json','third-party-licenses.txt','dependency-licenses.txt','build-info.json','SHA256SUMS.txt','map_cache/README.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
|
||||
$ridActual = @($ridZip.Entries | ForEach-Object { $_.FullName.Replace('\','/') })
|
||||
if ($ridActual.Count -ne $ridExpected.Count -or @(Compare-Object $ridActual $ridExpected).Count) { throw 'Archive contains unexpected files' }
|
||||
} finally { $ridZip.Dispose() }
|
||||
@@ -47,4 +56,4 @@ foreach ($ridLine in Get-Content -LiteralPath (Join-Path $ridCleanOutput 'FPV-RI
|
||||
if ((Get-FileHash -LiteralPath $ridFile -Algorithm SHA256).Hash -ne $ridHash) { throw 'Release file checksum mismatch' }
|
||||
}
|
||||
if (@(Get-ChildItem -LiteralPath $ridCleanOutput -Directory -Filter '.package-*').Count) { throw 'Owned staging files were left behind' }
|
||||
Write-Output "PASS: dirty deployment refused and preserved; repeat package, whitelist, ZIP and file checksums verified. Evidence: $ridRoot"
|
||||
Write-Output "PASS: existing data and tiles preserved; repeat package, map_cache, ZIP and file checksums verified. Evidence: $ridRoot"
|
||||
|
||||
@@ -6,12 +6,15 @@ import {spawn} from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
import {DatabaseSync} from 'node:sqlite';
|
||||
import {inflateRawSync} from 'node:zlib';
|
||||
import {randomBytes} from 'node:crypto';
|
||||
const repo=path.resolve(import.meta.dirname,'..');
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-中文验证-'));
|
||||
const base='http://127.0.0.1:8787';
|
||||
const png='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=';
|
||||
let child;let output='';
|
||||
let spawnError;
|
||||
let sessionCookie='';
|
||||
const account={username:'registry-verification',password:randomBytes(24).toString('base64url')};
|
||||
async function start(command,args){
|
||||
// Never attach to, or mutate, an unrelated service already listening on this port.
|
||||
let occupied=false;try{await fetch(base+'/api/records',{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
|
||||
@@ -19,10 +22,29 @@ async function start(command,args){
|
||||
output='';spawnError=null;child=spawn(command,args,{cwd:root,windowsHide:true,stdio:['ignore','pipe','pipe']});
|
||||
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);
|
||||
child.on('error',e=>{spawnError=e;output+=e.message;});
|
||||
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output);try{const r=await fetch(base+'/api/records');if(r.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('启动超时 '+output);
|
||||
sessionCookie='';
|
||||
for(let i=0;i<150;i++){
|
||||
if(spawnError||child.exitCode!==null)throw Error(output);
|
||||
const status=output.includes('FPV-RID Rust 登记站')
|
||||
?await fetch(base+'/api/auth/status',{signal:AbortSignal.timeout(1000)}).catch(()=>null)
|
||||
:null;
|
||||
if(status?.ok){
|
||||
const {configured}=await status.json();
|
||||
const session=await fetch(base+(configured?'/api/auth/login':'/api/auth/setup'),{
|
||||
method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify(account)
|
||||
});
|
||||
assert.ok(session.ok,`验收账号登录失败:HTTP ${session.status}`);
|
||||
sessionCookie=session.headers.get('set-cookie')?.split(';')[0]??'';
|
||||
assert.match(sessionCookie,/^rid_session=/);
|
||||
return;
|
||||
}
|
||||
await new Promise(r=>setTimeout(r,100));
|
||||
}
|
||||
throw Error('启动超时 '+output);
|
||||
}
|
||||
async function stop(){if(child&&!spawnError&&child.exitCode===null){const exited=new Promise(r=>child.once('exit',r));if(child.kill())await exited;}child=null;}
|
||||
async function api(route,method='GET',body,status=200){const r=await fetch(base+route,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});const v=await r.json();assert.equal(r.status,status,JSON.stringify(v));return v;}
|
||||
function authenticated(route,options={}){return fetch(base+route,{...options,headers:{cookie:sessionCookie,...options.headers}});}
|
||||
async function api(route,method='GET',body,status=200){const r=await authenticated(route,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});const v=await r.json();assert.equal(r.status,status,JSON.stringify(v));return v;}
|
||||
function unzip(bytes){
|
||||
const end=bytes.lastIndexOf(Buffer.from([0x50,0x4b,0x05,0x06]));assert.ok(end>=0);
|
||||
const entries=new Map();let offset=bytes.readUInt32LE(end+16);
|
||||
@@ -40,7 +62,7 @@ function unzip(bytes){
|
||||
}
|
||||
async function exports(id,label){
|
||||
for(const kind of ['archive','excel']){
|
||||
const r=await fetch(base+'/api/export/'+kind,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({ids:[id]})});assert.equal(r.status,200);
|
||||
const r=await authenticated('/api/export/'+kind,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({ids:[id]})});assert.equal(r.status,200);
|
||||
const bytes=Buffer.from(await r.arrayBuffer());const entries=unzip(bytes);
|
||||
if(kind==='archive'){
|
||||
const manifest=JSON.parse(entries.get('档案库/records.json').toString());assert.equal(manifest[0].id,id);assert.equal(manifest[0].fpvCode,'FPV00000001');
|
||||
@@ -52,7 +74,7 @@ async function exports(id,label){
|
||||
}
|
||||
await writeFile(path.join(root,`${label}-${kind}.zip`),bytes);
|
||||
}
|
||||
const r=await fetch(base+`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('<测试>'));
|
||||
const r=await authenticated(`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('<测试>'));
|
||||
}
|
||||
try{
|
||||
const exe=path.resolve(process.argv[2]||path.join(repo,'dist/FPV-RID-Rust/fpv-rid-registry.exe'));
|
||||
@@ -71,7 +93,7 @@ try{
|
||||
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).id,id);
|
||||
await api('/api/resolve?url='+encodeURIComponent('http://example.com/r/'+id),'GET',undefined,400);
|
||||
await exports(id,'rust');db=new DatabaseSync(dbPath);assert.equal(db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes,before);db.close();
|
||||
const blocked=await fetch(base+'/api/records',{headers:{origin:'https://example.com'}});assert.equal(blocked.status,403);
|
||||
const blocked=await authenticated('/api/records',{headers:{origin:'https://example.com'}});assert.equal(blocked.status,403);
|
||||
const p=await api('/api/records?page=1&pageSize=1');assert.equal(p.total,1);assert.equal(p.records.length,1);
|
||||
await api('/api/records?page=0','GET',undefined,400);
|
||||
const edited=await api('/api/records/'+id,'PATCH',{modelName:'',ownerName:'新登记人'});assert.equal(edited.record.modelName,'');
|
||||
@@ -79,7 +101,7 @@ try{
|
||||
await api('/api/records/'+id,'PATCH',{ownerName:'must rollback',photo1:'invalid'},400);
|
||||
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).ownerName,'新登记人');
|
||||
await api('/api/records/'+id,'PATCH',{photo1:null,photo2:png});
|
||||
assert.equal((await fetch(base+'/api/records/'+id+'/photos/2')).status,200);
|
||||
assert.equal((await authenticated('/api/records/'+id+'/photos/2')).status,200);
|
||||
await api('/api/records/'+id+'/photos/1','DELETE');await api('/api/records/'+id+'/photos/1','GET',undefined,404);
|
||||
await api('/api/records','POST',{serialNo:'TEST-SN-001',photo1:png});
|
||||
// Simulate an archive directory failure without modifying the active database.
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
use crate::{
|
||||
config, history, http, launch, lifecycle::Signal, map_settings, maps, monitoring, realtime,
|
||||
receiver, services::Services,
|
||||
auth, config, history, http, launch, lifecycle::Signal, map_settings, maps, monitoring,
|
||||
realtime, receiver, services::Services,
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mut root = std::env::current_exe()?
|
||||
.parent()
|
||||
.ok_or("无法确定程序目录")?
|
||||
.to_owned();
|
||||
pub(crate) async fn run(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let executable = std::env::current_exe()?;
|
||||
let executable_dir = executable.parent().ok_or("无法确定程序目录")?;
|
||||
let portable = cfg!(feature = "portable");
|
||||
let mut root = if portable {
|
||||
executable_dir.join("data")
|
||||
} else {
|
||||
executable_dir.to_owned()
|
||||
};
|
||||
let mut simulation_api = false;
|
||||
let mut open_browser = true;
|
||||
let mut explicit_data_root = false;
|
||||
@@ -27,20 +32,30 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let executable_tiles = executable_dir.join(if portable {
|
||||
"map"
|
||||
} else {
|
||||
maps::OFFLINE_DIRECTORY
|
||||
});
|
||||
let download_directory = if portable && !explicit_data_root {
|
||||
executable_tiles.clone()
|
||||
} else {
|
||||
root.join(maps::OFFLINE_DIRECTORY)
|
||||
};
|
||||
let port = 8787;
|
||||
let config = config::load(&root)?;
|
||||
let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
if error.kind() == std::io::ErrorKind::AddrInUse
|
||||
&& open_browser
|
||||
&& !explicit_data_root
|
||||
&& launch::open_existing(port).await?
|
||||
{
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => {
|
||||
if portable {
|
||||
return Err(format!("端口 {port} 已被占用。请先退出正在运行的 RID 服务,或关闭占用此端口的程序,再启动便携版。" ).into());
|
||||
}
|
||||
if open_browser && !explicit_data_root && launch::open_existing(port).await? {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!("无法监听 8787,请关闭旧版或其他实例:{error}").into());
|
||||
return Err(format!("无法监听 {port},请关闭旧版或其他实例:{error}").into());
|
||||
}
|
||||
Err(error) => return Err(format!("无法监听 {port}:{error}").into()),
|
||||
};
|
||||
std::fs::create_dir_all(root.join("registry/data"))?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
@@ -50,7 +65,7 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.write(true)
|
||||
.open(root.join("registry/data/rust.lock"))?;
|
||||
fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| "该数据目录已被另一个 Rust 实例使用")?;
|
||||
map_settings::prepare_offline_directory(&root.join("maps"))?;
|
||||
let auth = auth::Auth::open(&root).await?;
|
||||
let map_root = root.clone();
|
||||
|
||||
let services = Services::open(root, &config.sqlite).await?;
|
||||
@@ -59,6 +74,7 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
let map_router = maps::router(
|
||||
map_root.clone(),
|
||||
executable_tiles,
|
||||
config.maps.tianditu_token,
|
||||
config.maps.offline_directory,
|
||||
)?;
|
||||
@@ -66,6 +82,7 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let monitor_stop = Signal::new();
|
||||
let live_store = realtime::new_store();
|
||||
let history = history::History::open(&map_root, &config.sqlite).await?;
|
||||
let workbench = crate::workbench::Workbench::open(&map_root, &config.sqlite).await?;
|
||||
let (monitor, monitor_task) = monitoring::start(
|
||||
services.clone(),
|
||||
history.clone(),
|
||||
@@ -73,18 +90,27 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
monitor_stop.clone(),
|
||||
)?;
|
||||
let (receivers, receiver_stop) = receiver::start(map_root.clone(), live_store.clone()).await;
|
||||
let (map_preferences, map_downloads) = map_settings::router(map_root.clone(), port);
|
||||
let (map_preferences, map_downloads) =
|
||||
map_settings::router(map_root.clone(), download_directory, port);
|
||||
let (realtime_router, expiration_task) =
|
||||
realtime::start(simulation_api, live_store, closing.clone());
|
||||
realtime::start(simulation_api, live_store.clone(), closing.clone());
|
||||
let requests = crate::lifecycle::Requests::new(closing.clone());
|
||||
let admission = requests.clone();
|
||||
let app = http::router(services.clone())
|
||||
.merge(realtime_router)
|
||||
.merge(crate::flight_plans::live_router(
|
||||
services.clone(),
|
||||
live_store,
|
||||
))
|
||||
.merge(receivers)
|
||||
.merge(monitor)
|
||||
.merge(history::router(history.clone()))
|
||||
.merge(crate::observations::router(history.clone()))
|
||||
.merge(workbench.router())
|
||||
.merge(map_preferences)
|
||||
.merge(map_router)
|
||||
.merge(auth.router())
|
||||
.layer(axum::middleware::from_fn_with_state(auth, auth::protect))
|
||||
.layer(axum::middleware::from_fn(
|
||||
move |req: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let stop = admission.clone();
|
||||
@@ -92,6 +118,9 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
},
|
||||
));
|
||||
println!("FPV-RID Rust 登记站:http://127.0.0.1:{port}");
|
||||
if portable && open_browser {
|
||||
println!("服务运行中。停止时请在此窗口按 Ctrl+C,等待程序退出。");
|
||||
}
|
||||
let browser_task = open_browser.then(|| tokio::spawn(launch::open_when_ready(port)));
|
||||
let stop = closing.clone();
|
||||
let receiver_signal = receiver_stop.clone();
|
||||
@@ -116,6 +145,7 @@ pub(crate) async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
monitor_stop.cancel();
|
||||
let monitoring_result = monitor_task.await;
|
||||
history.close().await;
|
||||
workbench.close().await;
|
||||
map_downloads.wait().await;
|
||||
services.close().await;
|
||||
drop(lock);
|
||||
|
||||
@@ -0,0 +1,640 @@
|
||||
//! Local account setup, role enforcement and browser sessions.
|
||||
use argon2::{
|
||||
Argon2,
|
||||
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{DefaultBodyLimit, Path as RoutePath, Request, State},
|
||||
http::{HeaderMap, HeaderValue, Method, StatusCode, header},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const COOKIE: &str = "rid_session";
|
||||
const SESSION_AGE: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
const LOGIN_INTERVAL: Duration = Duration::from_millis(750);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Auth(Arc<Inner>);
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Actor(pub String, Role);
|
||||
|
||||
impl Actor {
|
||||
pub fn can_capture(&self) -> bool {
|
||||
matches!(self.1, Role::Administrator)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SessionLease(Auth, String);
|
||||
|
||||
impl SessionLease {
|
||||
pub async fn active(&self) -> bool {
|
||||
self.0
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.sessions
|
||||
.get(&self.1)
|
||||
.is_some_and(|session| session.expires > Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
db: SqlitePool,
|
||||
state: Mutex<AuthState>,
|
||||
}
|
||||
|
||||
struct AuthState {
|
||||
account: Option<(String, String)>,
|
||||
sessions: HashMap<String, Session>,
|
||||
last_attempt: Option<Instant>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Session {
|
||||
username: String,
|
||||
role: Role,
|
||||
expires: Instant,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum MemberRole {
|
||||
Operator,
|
||||
Viewer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Role {
|
||||
Administrator,
|
||||
Member(MemberRole),
|
||||
}
|
||||
|
||||
impl MemberRole {
|
||||
fn value(self) -> &'static str {
|
||||
match self {
|
||||
Self::Operator => "operator",
|
||||
Self::Viewer => "viewer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Role {
|
||||
fn value(self) -> &'static str {
|
||||
match self {
|
||||
Self::Administrator => "admin",
|
||||
Self::Member(role) => role.value(),
|
||||
}
|
||||
}
|
||||
|
||||
fn permits(self, method: &Method, path: &str) -> bool {
|
||||
if matches!(self, Self::Administrator) {
|
||||
return true;
|
||||
}
|
||||
if path.starts_with("/api/auth/users") || path.ends_with("/capture") {
|
||||
return false;
|
||||
}
|
||||
if matches!(*method, Method::GET | Method::HEAD) {
|
||||
return true;
|
||||
}
|
||||
// Every signed-in user may save their own camera and alert-display preferences.
|
||||
if *method == Method::PUT && path == "/api/workbench/view" {
|
||||
return true;
|
||||
}
|
||||
if *method == Method::PUT
|
||||
&& path.starts_with("/api/monitoring/events/")
|
||||
&& path.ends_with("/dismissal")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if matches!(self, Self::Member(MemberRole::Viewer)) {
|
||||
return false;
|
||||
}
|
||||
if path.starts_with("/api/flight-plans/") && path.ends_with("/approval") {
|
||||
return false;
|
||||
}
|
||||
// Operators maintain local registration, lists and alert dispositions.
|
||||
[
|
||||
"/api/records",
|
||||
"/api/flight-plans",
|
||||
"/api/target-lists",
|
||||
"/api/target-bindings",
|
||||
"/api/geofences",
|
||||
"/api/monitoring/events",
|
||||
"/api/export",
|
||||
"/api/archive/retry",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|prefix| {
|
||||
path == prefix
|
||||
|| path
|
||||
.strip_prefix(prefix)
|
||||
.is_some_and(|suffix| suffix.starts_with('/'))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod flight_plan_permissions {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_admin_can_approve_and_viewers_cannot_submit() {
|
||||
let plan = "/api/flight-plans/plan-1";
|
||||
let approval = "/api/flight-plans/plan-1/approval";
|
||||
assert!(Role::Administrator.permits(&Method::PUT, approval));
|
||||
assert!(!Role::Member(MemberRole::Operator).permits(&Method::PUT, approval));
|
||||
assert!(!Role::Member(MemberRole::Viewer).permits(&Method::PUT, approval));
|
||||
assert!(Role::Member(MemberRole::Operator).permits(&Method::PUT, plan));
|
||||
assert!(!Role::Member(MemberRole::Viewer).permits(&Method::PUT, plan));
|
||||
assert!(Role::Member(MemberRole::Viewer).permits(&Method::GET, "/api/flight-plans"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
pub async fn open(root: &Path) -> Result<Self, sqlx::Error> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(root.join("registry/data/workbench-auth.sqlite"))
|
||||
.create_if_missing(true);
|
||||
let db = SqlitePool::connect_with(options).await?;
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS administrator (id INTEGER PRIMARY KEY CHECK(id=1), username TEXT NOT NULL, password_hash TEXT NOT NULL)")
|
||||
.execute(&db).await?;
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS workbench_users(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('operator','viewer')),
|
||||
enabled INTEGER NOT NULL CHECK(enabled IN (0,1))
|
||||
)",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let account = sqlx::query_as("SELECT username,password_hash FROM administrator WHERE id=1")
|
||||
.fetch_optional(&db)
|
||||
.await?;
|
||||
Ok(Self(Arc::new(Inner {
|
||||
db,
|
||||
state: Mutex::new(AuthState {
|
||||
account,
|
||||
sessions: HashMap::new(),
|
||||
last_attempt: None,
|
||||
}),
|
||||
})))
|
||||
}
|
||||
|
||||
pub fn router(&self) -> Router {
|
||||
Router::new()
|
||||
.route("/api/auth/status", get(status))
|
||||
.route("/api/auth/setup", post(setup))
|
||||
.route("/api/auth/login", post(login))
|
||||
.route("/api/auth/logout", post(logout))
|
||||
.route("/api/auth/users", get(users).post(create_user))
|
||||
.route(
|
||||
"/api/auth/users/{id}",
|
||||
axum::routing::put(save_user).delete(delete_user),
|
||||
)
|
||||
.layer(DefaultBodyLimit::max(4096))
|
||||
.with_state(self.clone())
|
||||
}
|
||||
|
||||
async fn current(&self, headers: &HeaderMap) -> Option<Session> {
|
||||
let token = session_token(headers)?;
|
||||
self.0
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.sessions
|
||||
.get(token)
|
||||
.filter(|session| session.expires > Instant::now())
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
fn session_token(headers: &HeaderMap) -> Option<&str> {
|
||||
headers
|
||||
.get(header::COOKIE)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(';')
|
||||
.find_map(|entry| {
|
||||
let (name, value) = entry.trim().split_once('=')?;
|
||||
(name == COOKIE && value.len() == 43).then_some(value)
|
||||
})
|
||||
}
|
||||
|
||||
fn cookie(value: &str, age: u64) -> HeaderValue {
|
||||
HeaderValue::from_str(&format!(
|
||||
"{COOKIE}={value}; Path=/; HttpOnly; SameSite=Strict; Max-Age={age}"
|
||||
))
|
||||
.expect("session cookies are URL-safe")
|
||||
}
|
||||
|
||||
fn rejected(status: StatusCode, error: &'static str) -> Response {
|
||||
(status, Json(json!({"error":error}))).into_response()
|
||||
}
|
||||
|
||||
fn success(
|
||||
state: &mut AuthState,
|
||||
username: String,
|
||||
role: Role,
|
||||
previous: Option<&str>,
|
||||
) -> Response {
|
||||
let now = Instant::now();
|
||||
state
|
||||
.sessions
|
||||
.retain(|token, session| Some(token.as_str()) != previous && session.expires > now);
|
||||
if state.sessions.len() >= 64
|
||||
&& let Some(oldest) = state
|
||||
.sessions
|
||||
.iter()
|
||||
.min_by_key(|(_, session)| session.expires)
|
||||
.map(|(token, _)| token.clone())
|
||||
{
|
||||
state.sessions.remove(&oldest);
|
||||
}
|
||||
let token = URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>());
|
||||
state.sessions.insert(
|
||||
token.clone(),
|
||||
Session {
|
||||
username,
|
||||
role,
|
||||
expires: now + SESSION_AGE,
|
||||
},
|
||||
);
|
||||
(
|
||||
[(header::SET_COOKIE, cookie(&token, SESSION_AGE.as_secs()))],
|
||||
Json(json!({"ok":true})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Credentials {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
async fn status(State(auth): State<Auth>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let session = auth.current(&headers).await;
|
||||
let configured = auth.0.state.lock().await.account.is_some();
|
||||
Json(json!({
|
||||
"configured":configured, "authenticated":session.is_some(),
|
||||
"role":session.as_ref().map(|session|session.role.value()),
|
||||
"username":session.map(|session|session.username)
|
||||
}))
|
||||
}
|
||||
|
||||
fn valid_user_name(username: &str) -> bool {
|
||||
!username.is_empty()
|
||||
&& username.chars().count() <= 40
|
||||
&& !username.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
fn valid_password(password: &str) -> bool {
|
||||
password.chars().count() >= 10 && password.len() <= 256
|
||||
}
|
||||
|
||||
async fn password_hash(password: String) -> Result<String, ()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let salt = SaltString::encode_b64(&rand::random::<[u8; 16]>()).map_err(|_| ())?;
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ())?
|
||||
}
|
||||
|
||||
async fn setup(
|
||||
State(auth): State<Auth>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Credentials>,
|
||||
) -> Response {
|
||||
let username = input.username.trim().to_owned();
|
||||
if !valid_user_name(&username) || !valid_password(&input.password) {
|
||||
return rejected(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"请输入 1–40 字的用户名和至少 10 字符的密码",
|
||||
);
|
||||
}
|
||||
let mut state = auth.0.state.lock().await;
|
||||
if state.account.is_some() {
|
||||
return rejected(StatusCode::CONFLICT, "管理员已创建,请登录");
|
||||
}
|
||||
let Ok(hash) = password_hash(input.password).await else {
|
||||
return rejected(StatusCode::INTERNAL_SERVER_ERROR, "创建管理员失败");
|
||||
};
|
||||
if sqlx::query("INSERT INTO administrator(id,username,password_hash) VALUES(1,?,?)")
|
||||
.bind(&username)
|
||||
.bind(&hash)
|
||||
.execute(&auth.0.db)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return rejected(StatusCode::INTERNAL_SERVER_ERROR, "保存管理员失败");
|
||||
}
|
||||
state.account = Some((username.clone(), hash));
|
||||
success(
|
||||
&mut state,
|
||||
username,
|
||||
Role::Administrator,
|
||||
session_token(&headers),
|
||||
)
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(auth): State<Auth>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Credentials>,
|
||||
) -> Response {
|
||||
if input.username.len() > 160 || input.password.len() > 256 {
|
||||
return rejected(StatusCode::UNAUTHORIZED, "用户名或密码错误");
|
||||
}
|
||||
let mut state = auth.0.state.lock().await;
|
||||
let Some((username, hash)) = state.account.clone() else {
|
||||
return rejected(StatusCode::CONFLICT, "请先创建管理员");
|
||||
};
|
||||
let now = Instant::now();
|
||||
if state
|
||||
.last_attempt
|
||||
.is_some_and(|last| now.duration_since(last) < LOGIN_INTERVAL)
|
||||
{
|
||||
return rejected(StatusCode::TOO_MANY_REQUESTS, "操作过于频繁,请稍后重试");
|
||||
}
|
||||
state.last_attempt = Some(now);
|
||||
let input_user = input.username.trim().to_owned();
|
||||
let (hash, role) = if input_user == username {
|
||||
(hash, Some(Role::Administrator))
|
||||
} else {
|
||||
let member = sqlx::query_as::<_, (String, String, bool)>(
|
||||
"SELECT password_hash,role,enabled FROM workbench_users WHERE username=?",
|
||||
)
|
||||
.bind(&input_user)
|
||||
.fetch_optional(&auth.0.db)
|
||||
.await;
|
||||
match member {
|
||||
Ok(Some((hash, role, true))) => {
|
||||
let role = if role == "operator" {
|
||||
MemberRole::Operator
|
||||
} else {
|
||||
MemberRole::Viewer
|
||||
};
|
||||
(hash, Some(Role::Member(role)))
|
||||
}
|
||||
Ok(_) => (hash, None),
|
||||
Err(_) => return rejected(StatusCode::INTERNAL_SERVER_ERROR, "暂时无法读取账号"),
|
||||
}
|
||||
};
|
||||
let verified = tokio::task::spawn_blocking(move || {
|
||||
PasswordHash::new(&hash).is_ok_and(|parsed| {
|
||||
Argon2::default()
|
||||
.verify_password(input.password.as_bytes(), &parsed)
|
||||
.is_ok()
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
let Some(role) = role.filter(|_| verified) else {
|
||||
return rejected(StatusCode::UNAUTHORIZED, "用户名或密码错误");
|
||||
};
|
||||
success(&mut state, input_user, role, session_token(&headers))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NewUser {
|
||||
username: String,
|
||||
password: String,
|
||||
role: MemberRole,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UserChange {
|
||||
password: Option<String>,
|
||||
role: MemberRole,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
async fn users(State(auth): State<Auth>) -> crate::error::Result<Json<serde_json::Value>> {
|
||||
let owner = auth
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.account
|
||||
.as_ref()
|
||||
.map(|(name, _)| name.clone());
|
||||
let mut entries = Vec::new();
|
||||
if let Some(owner) = owner {
|
||||
entries.push(json!({"id":0,"username":owner,"role":"admin","enabled":true}));
|
||||
}
|
||||
let rows = sqlx::query_as::<_, (i64, String, String, bool)>(
|
||||
"SELECT id,username,role,enabled FROM workbench_users ORDER BY username,id",
|
||||
)
|
||||
.fetch_all(&auth.0.db)
|
||||
.await?;
|
||||
entries.extend(rows.into_iter().map(|(id, username, role, enabled)| {
|
||||
json!({
|
||||
"id":id,"username":username,"role":role,"enabled":enabled
|
||||
})
|
||||
}));
|
||||
Ok(Json(json!({"entries":entries})))
|
||||
}
|
||||
|
||||
async fn create_user(State(auth): State<Auth>, Json(input): Json<NewUser>) -> Response {
|
||||
let username = input.username.trim();
|
||||
if !valid_user_name(username) || !valid_password(&input.password) {
|
||||
return rejected(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"请输入 1–40 字的用户名和至少 10 字符的密码",
|
||||
);
|
||||
}
|
||||
let Ok(hash) = password_hash(input.password).await else {
|
||||
return rejected(StatusCode::INTERNAL_SERVER_ERROR, "保存密码失败");
|
||||
};
|
||||
let state = auth.0.state.lock().await;
|
||||
if state
|
||||
.account
|
||||
.as_ref()
|
||||
.is_some_and(|(owner, _)| owner == username)
|
||||
{
|
||||
return rejected(StatusCode::CONFLICT, "用户名已存在");
|
||||
}
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO workbench_users(username,password_hash,role,enabled)
|
||||
SELECT ?,?,?,1 WHERE (SELECT count(*) FROM workbench_users)<128",
|
||||
)
|
||||
.bind(username)
|
||||
.bind(hash)
|
||||
.bind(input.role.value())
|
||||
.execute(&auth.0.db)
|
||||
.await;
|
||||
match result {
|
||||
Ok(result) if result.rows_affected() == 1 => StatusCode::CREATED.into_response(),
|
||||
Ok(_) => rejected(StatusCode::CONFLICT, "已达到 128 个附加用户上限"),
|
||||
Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
|
||||
rejected(StatusCode::CONFLICT, "用户名已存在")
|
||||
}
|
||||
Err(_) => rejected(StatusCode::INTERNAL_SERVER_ERROR, "创建用户失败"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_user(
|
||||
State(auth): State<Auth>,
|
||||
RoutePath(id): RoutePath<i64>,
|
||||
Json(input): Json<UserChange>,
|
||||
) -> Response {
|
||||
if id == 0 {
|
||||
return rejected(StatusCode::FORBIDDEN, "初始管理员受保护");
|
||||
}
|
||||
let mut new_hash = None;
|
||||
if let Some(password) = input.password {
|
||||
if !valid_password(&password) {
|
||||
return rejected(StatusCode::BAD_REQUEST, "密码至少 10 字符");
|
||||
}
|
||||
match password_hash(password).await {
|
||||
Ok(hash) => new_hash = Some(hash),
|
||||
Err(_) => return rejected(StatusCode::INTERNAL_SERVER_ERROR, "保存密码失败"),
|
||||
}
|
||||
}
|
||||
let mut state = auth.0.state.lock().await;
|
||||
let result = sqlx::query_scalar::<_, String>(
|
||||
"UPDATE workbench_users SET
|
||||
role=?,enabled=?,password_hash=COALESCE(?,password_hash) WHERE id=? RETURNING username",
|
||||
)
|
||||
.bind(input.role.value())
|
||||
.bind(input.enabled)
|
||||
.bind(new_hash)
|
||||
.bind(id)
|
||||
.fetch_optional(&auth.0.db)
|
||||
.await;
|
||||
change_user_response(result, &mut state)
|
||||
}
|
||||
|
||||
async fn delete_user(State(auth): State<Auth>, RoutePath(id): RoutePath<i64>) -> Response {
|
||||
if id == 0 {
|
||||
return rejected(StatusCode::FORBIDDEN, "初始管理员受保护");
|
||||
}
|
||||
let mut state = auth.0.state.lock().await;
|
||||
let result = sqlx::query_scalar::<_, String>(
|
||||
"DELETE FROM workbench_users WHERE id=? RETURNING username",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&auth.0.db)
|
||||
.await;
|
||||
change_user_response(result, &mut state)
|
||||
}
|
||||
|
||||
fn change_user_response(
|
||||
result: Result<Option<String>, sqlx::Error>,
|
||||
state: &mut AuthState,
|
||||
) -> Response {
|
||||
match result {
|
||||
Ok(Some(username)) => {
|
||||
state
|
||||
.sessions
|
||||
.retain(|_, session| session.username != username);
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
Ok(None) => rejected(StatusCode::NOT_FOUND, "账号不存在"),
|
||||
Err(_) => rejected(StatusCode::INTERNAL_SERVER_ERROR, "无法更新账号"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn logout(State(auth): State<Auth>, headers: HeaderMap) -> Response {
|
||||
if let Some(token) = session_token(&headers) {
|
||||
auth.0.state.lock().await.sessions.remove(token);
|
||||
}
|
||||
(
|
||||
[(header::SET_COOKIE, cookie("", 0))],
|
||||
Json(json!({"ok":true})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub(crate) async fn protect(
|
||||
State(auth): State<Auth>,
|
||||
mut request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let headers = request.headers();
|
||||
let host = headers
|
||||
.get(header::HOST)
|
||||
.and_then(|host| host.to_str().ok());
|
||||
let origin = match host {
|
||||
Some("127.0.0.1:8787") => "http://127.0.0.1:8787",
|
||||
Some("localhost:8787") => "http://localhost:8787",
|
||||
_ => return rejected(StatusCode::FORBIDDEN, "仅允许本机访问"),
|
||||
};
|
||||
let path = request.uri().path();
|
||||
let method = request.method();
|
||||
let auth_action = *method == Method::POST
|
||||
&& matches!(
|
||||
path,
|
||||
"/api/auth/setup" | "/api/auth/login" | "/api/auth/logout"
|
||||
);
|
||||
// QR cards and their existing lookup are public by design. Map tiles are also
|
||||
// consumed by the local offline-map helper, which has no browser session.
|
||||
let public_card = *method == Method::GET && (path.starts_with("/r/") || path == "/api/resolve");
|
||||
let request_origin = headers.get(header::ORIGIN);
|
||||
if (!public_card && request_origin.is_some_and(|value| value != origin))
|
||||
|| (auth_action && request_origin.is_none())
|
||||
{
|
||||
return rejected(StatusCode::FORBIDDEN, "请求来源无效");
|
||||
}
|
||||
let public = public_card
|
||||
|| auth_action
|
||||
|| (*method == Method::GET
|
||||
&& (matches!(
|
||||
path,
|
||||
"/workbench"
|
||||
| "/workbench/"
|
||||
| "/workbench/login.html"
|
||||
| "/api/auth/status"
|
||||
| "/api/workbench/branding"
|
||||
) || path.starts_with("/api/maps/tile/")
|
||||
|| (path.starts_with("/workbench/") && !path.ends_with(".html"))));
|
||||
if !public {
|
||||
let Some(session) = auth.current(headers).await else {
|
||||
return if *method == Method::GET
|
||||
&& matches!(path, "/" | "/realtime" | "/workbench/platform.html")
|
||||
{
|
||||
Redirect::to("/workbench/").into_response()
|
||||
} else {
|
||||
rejected(StatusCode::UNAUTHORIZED, "请登录 RID 平台")
|
||||
};
|
||||
};
|
||||
if !session.role.permits(method, path) {
|
||||
return rejected(StatusCode::FORBIDDEN, "当前账号没有此操作权限");
|
||||
}
|
||||
let lease =
|
||||
session_token(headers).map(|token| SessionLease(auth.clone(), token.to_owned()));
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(Actor(session.username, session.role));
|
||||
if let Some(lease) = lease {
|
||||
request.extensions_mut().insert(lease);
|
||||
}
|
||||
}
|
||||
let mut response = next.run(request).await;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
response
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
//! Local flight filings and the shared server-side flight assessment.
|
||||
use crate::{
|
||||
error::{AppError, Result},
|
||||
target_bindings::RegistrationStatus,
|
||||
};
|
||||
use rid_shared::{
|
||||
Observation,
|
||||
geofences::{Fence, Geometry},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Plan {
|
||||
pub id: String,
|
||||
pub record_id: String,
|
||||
pub name: String,
|
||||
pub start_ms: i64,
|
||||
pub end_ms: i64,
|
||||
pub geometry: Geometry,
|
||||
pub note: String,
|
||||
pub enabled: bool,
|
||||
pub revision: u64,
|
||||
#[serde(default)]
|
||||
pub approval: String,
|
||||
#[serde(default)]
|
||||
pub reviewed_by: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reviewed_at_ms: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub review_note: String,
|
||||
}
|
||||
impl Plan {
|
||||
fn valid(&self) -> bool {
|
||||
rid_shared::target_lists::valid_target_id(&self.id)
|
||||
&& crate::store::valid_id(&self.record_id)
|
||||
&& !self.name.trim().is_empty()
|
||||
&& self.name.chars().count() <= 80
|
||||
&& self.note.chars().count() <= 500
|
||||
&& self.start_ms > 0
|
||||
&& self.end_ms > self.start_ms
|
||||
&& self.geometry.valid()
|
||||
}
|
||||
}
|
||||
pub async fn init(db: &mut SqliteConnection) -> Result<()> {
|
||||
sqlx::raw_sql("CREATE TABLE IF NOT EXISTS flight_plans(id TEXT PRIMARY KEY,record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,value TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS flight_plan_record ON flight_plans(record_id);").execute(db).await?;
|
||||
Ok(())
|
||||
}
|
||||
pub async fn list(db: &mut SqliteConnection) -> Result<Vec<Plan>> {
|
||||
let rows: Vec<String> = sqlx::query_scalar("SELECT value FROM flight_plans ORDER BY id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
rows.into_iter()
|
||||
.map(|v| serde_json::from_str(&v).map_err(|e| AppError::Internal(e.to_string())))
|
||||
.collect()
|
||||
}
|
||||
pub async fn save(db: &mut SqliteConnection, id: &str, mut plan: Plan) -> Result<Plan> {
|
||||
plan.name = plan.name.trim().to_owned();
|
||||
if id != plan.id || !plan.valid() {
|
||||
return Err("请检查报备飞机、名称、起止时间和飞行区域".into());
|
||||
}
|
||||
let mut tx = db.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let previous: Option<String> = sqlx::query_scalar("SELECT value FROM flight_plans WHERE id=?")
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let revision = previous
|
||||
.as_ref()
|
||||
.map(|v| serde_json::from_str::<Plan>(v).map(|p| p.revision))
|
||||
.transpose()
|
||||
.map_err(|e| AppError::Internal(e.to_string()))?
|
||||
.unwrap_or(0);
|
||||
if revision != plan.revision {
|
||||
return Err("报备已被修改,请刷新后重试".into());
|
||||
}
|
||||
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM records WHERE id=?)")
|
||||
.bind(&plan.record_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !exists {
|
||||
return Err("请先在本地档案登记该飞机".into());
|
||||
}
|
||||
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM flight_plans")
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if previous.is_none() && count >= 10000 {
|
||||
return Err("飞行报备已达 10000 条,请清理失效报备".into());
|
||||
}
|
||||
plan.revision += 1;
|
||||
plan.approval = "pending".into();
|
||||
plan.reviewed_by = None;
|
||||
plan.reviewed_at_ms = None;
|
||||
plan.review_note.clear();
|
||||
let value = serde_json::to_string(&plan).map_err(|e| AppError::Internal(e.to_string()))?;
|
||||
sqlx::query("INSERT INTO flight_plans VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET record_id=excluded.record_id,value=excluded.value")
|
||||
.bind(id).bind(&plan.record_id).bind(value).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(plan)
|
||||
}
|
||||
pub async fn remove(db: &mut SqliteConnection, id: &str, revision: u64) -> Result<()> {
|
||||
let mut tx = db.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let value: String = sqlx::query_scalar("SELECT value FROM flight_plans WHERE id=?")
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound("报备不存在"))?;
|
||||
let plan: Plan = serde_json::from_str(&value).map_err(|e| AppError::Internal(e.to_string()))?;
|
||||
if plan.revision != revision {
|
||||
return Err("报备已被修改,请刷新后重试".into());
|
||||
}
|
||||
sqlx::query("DELETE FROM flight_plans WHERE id=?")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Decision {
|
||||
pub approved: bool,
|
||||
pub expected_revision: u64,
|
||||
pub note: String,
|
||||
}
|
||||
pub async fn review(
|
||||
db: &mut SqliteConnection,
|
||||
id: &str,
|
||||
decision: Decision,
|
||||
actor: &str,
|
||||
) -> Result<Plan> {
|
||||
if decision.note.chars().count() > 500
|
||||
|| (!decision.approved && decision.note.trim().is_empty())
|
||||
{
|
||||
return Err("驳回时请填写原因,最多 500 字".into());
|
||||
}
|
||||
let mut tx = db.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let value: String = sqlx::query_scalar("SELECT value FROM flight_plans WHERE id=?")
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound("报备不存在"))?;
|
||||
let mut plan: Plan =
|
||||
serde_json::from_str(&value).map_err(|e| AppError::Internal(e.to_string()))?;
|
||||
if plan.revision != decision.expected_revision || plan.approval != "pending" || !plan.enabled {
|
||||
return Err("报备已变更或不在待审批状态,请刷新后重试".into());
|
||||
}
|
||||
if plan.end_ms <= crate::realtime::now_ms() as i64 {
|
||||
return Err("报备时段已结束,请修改后重新提交".into());
|
||||
}
|
||||
plan.approval = if decision.approved {
|
||||
"approved"
|
||||
} else {
|
||||
"rejected"
|
||||
}
|
||||
.into();
|
||||
plan.reviewed_by = Some(actor.into());
|
||||
plan.reviewed_at_ms = Some(crate::realtime::now_ms());
|
||||
plan.review_note = decision.note.trim().into();
|
||||
plan.revision += 1;
|
||||
sqlx::query("UPDATE flight_plans SET value=? WHERE id=?")
|
||||
.bind(serde_json::to_string(&plan).map_err(|e| e.to_string())?)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Assessment {
|
||||
pub target_id: String,
|
||||
pub class: String,
|
||||
pub reason: String,
|
||||
pub plan_id: Option<String>,
|
||||
pub fence_id: Option<String>,
|
||||
pub fence_name: Option<String>,
|
||||
pub list_kind: String,
|
||||
}
|
||||
pub struct Policy {
|
||||
registrations: HashMap<String, RegistrationStatus>,
|
||||
plans: Vec<Plan>,
|
||||
fences: Vec<Fence>,
|
||||
}
|
||||
impl Policy {
|
||||
pub async fn load(db: &mut SqliteConnection, ids: &[&str]) -> Result<Self> {
|
||||
let registrations: HashMap<_, _> = crate::target_bindings::statuses(db, ids)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|s| (s.target_id.clone(), s))
|
||||
.collect();
|
||||
let records: std::collections::HashSet<_> = registrations
|
||||
.values()
|
||||
.filter_map(|s| s.record_id.as_deref())
|
||||
.collect();
|
||||
let rows: Vec<String> = sqlx::query_scalar("SELECT value FROM flight_plans WHERE record_id IN (SELECT value FROM json_each(?)) ORDER BY id")
|
||||
.bind(serde_json::to_string(&records).map_err(|e|e.to_string())?).fetch_all(&mut *db).await?;
|
||||
let plans = rows
|
||||
.into_iter()
|
||||
.map(|v| serde_json::from_str(&v).map_err(|e| AppError::Internal(e.to_string())))
|
||||
.collect::<Result<Vec<Plan>>>()?;
|
||||
Ok(Self {
|
||||
registrations,
|
||||
plans,
|
||||
fences: crate::geofences::load(db).await?.entries,
|
||||
})
|
||||
}
|
||||
pub fn evaluate(&self, o: &Observation, time: u64) -> Assessment {
|
||||
let mut result = Assessment {
|
||||
target_id: o.target_id.clone(),
|
||||
class: "unknown".into(),
|
||||
reason: "登记状态待核验".into(),
|
||||
plan_id: None,
|
||||
fence_id: None,
|
||||
fence_name: None,
|
||||
list_kind: "none".into(),
|
||||
};
|
||||
let Some(registration) = self.registrations.get(&o.target_id) else {
|
||||
return result;
|
||||
};
|
||||
result.list_kind = registration
|
||||
.list_kind
|
||||
.clone()
|
||||
.unwrap_or_else(|| "none".into());
|
||||
let set = |result: &mut Assessment, class: &str, reason: &str| {
|
||||
result.class = class.into();
|
||||
result.reason = reason.into();
|
||||
};
|
||||
if registration.list_kind.as_deref() == Some("white") {
|
||||
set(&mut result, "whitelist", "白名单免告警");
|
||||
return result;
|
||||
}
|
||||
let position = o.coordinates().filter(|p| {
|
||||
*p != [0., 0.] && !o.telemetry.as_ref().is_some_and(|t| t.position_unverified)
|
||||
});
|
||||
if let Some(fence) = self
|
||||
.fences
|
||||
.iter()
|
||||
.find(|f| f.enabled && position.is_some_and(|p| f.geometry.contains(p)))
|
||||
{
|
||||
set(&mut result, "geofence_enter", "进入防控区");
|
||||
result.fence_id = Some(fence.id.clone());
|
||||
result.fence_name = Some(fence.name.clone());
|
||||
return result;
|
||||
}
|
||||
if registration.list_kind.as_deref() == Some("black") {
|
||||
set(&mut result, "blacklist", "黑名单目标");
|
||||
return result;
|
||||
}
|
||||
if !registration.registered {
|
||||
set(&mut result, "unregistered", "未在本地档案登记");
|
||||
return result;
|
||||
}
|
||||
let valid: Vec<_> = self
|
||||
.plans
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
p.enabled
|
||||
&& p.approval == "approved"
|
||||
&& Some(&p.record_id) == registration.record_id.as_ref()
|
||||
&& (p.start_ms as u64) <= time
|
||||
&& time < (p.end_ms as u64)
|
||||
})
|
||||
.collect();
|
||||
if let Some(plan) = valid
|
||||
.iter()
|
||||
.find(|p| position.is_some_and(|pos| p.geometry.contains(pos)))
|
||||
{
|
||||
set(&mut result, "authorized", "在报备时间和区域内");
|
||||
result.plan_id = Some(plan.id.clone());
|
||||
} else if valid.is_empty() {
|
||||
set(&mut result, "unfiled", "没有当前有效的飞行报备");
|
||||
} else if position.is_none() {
|
||||
set(&mut result, "unknown", "已有时段报备,位置待核验");
|
||||
} else {
|
||||
set(&mut result, "unfiled", "超出报备允许飞行区域");
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn alarming(class: &str) -> bool {
|
||||
matches!(
|
||||
class,
|
||||
"unregistered" | "unfiled" | "geofence_enter" | "blacklist"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn live_router(
|
||||
services: crate::services::Services,
|
||||
live: crate::realtime::TargetStore,
|
||||
) -> axum::Router {
|
||||
async fn statuses(
|
||||
axum::extract::State((services, live)): axum::extract::State<(
|
||||
crate::services::Services,
|
||||
crate::realtime::TargetStore,
|
||||
)>,
|
||||
) -> Result<axum::Json<serde_json::Value>> {
|
||||
let now = crate::realtime::now_ms();
|
||||
let targets = live
|
||||
.lock()
|
||||
.map_err(|_| AppError::Internal("实时状态不可用".into()))?
|
||||
.frame(None, now)
|
||||
.targets;
|
||||
let samples: Vec<_> = targets.into_iter().map(|t| (t.observation, now)).collect();
|
||||
Ok(axum::Json(
|
||||
serde_json::json!({"entries":services.flight_assessments(&samples).await?}),
|
||||
))
|
||||
}
|
||||
axum::Router::new()
|
||||
.route("/api/flight-status", axum::routing::get(statuses))
|
||||
.with_state((services, live))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const RECORD: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
fn plan() -> Plan {
|
||||
Plan {
|
||||
id: "test-plan".into(),
|
||||
record_id: RECORD.into(),
|
||||
name: "试飞".into(),
|
||||
start_ms: 1000,
|
||||
end_ms: 2000,
|
||||
geometry: Geometry::Circle {
|
||||
center: [120., 30.],
|
||||
radius_m: 500.,
|
||||
},
|
||||
note: String::new(),
|
||||
enabled: true,
|
||||
revision: 0,
|
||||
approval: "pending".into(),
|
||||
reviewed_by: None,
|
||||
reviewed_at_ms: None,
|
||||
review_note: String::new(),
|
||||
}
|
||||
}
|
||||
fn observation() -> Observation {
|
||||
Observation {
|
||||
target_id: "DRONE-A".into(),
|
||||
receiver_id: "RX-A".into(),
|
||||
source_epoch: 1,
|
||||
sequence: 1,
|
||||
longitude: Some(120.),
|
||||
latitude: Some(30.),
|
||||
altitude_m: Some(30.),
|
||||
heading_deg: None,
|
||||
telemetry: None,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn approval_time_area_and_whitelist_have_one_consistent_priority() {
|
||||
let mut policy = Policy {
|
||||
registrations: HashMap::from([(
|
||||
"DRONE-A".into(),
|
||||
RegistrationStatus {
|
||||
target_id: "DRONE-A".into(),
|
||||
registered: true,
|
||||
record_id: Some(RECORD.into()),
|
||||
list_kind: None,
|
||||
},
|
||||
)]),
|
||||
plans: vec![plan()],
|
||||
fences: vec![],
|
||||
};
|
||||
let mut o = observation();
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "unfiled"); // pending is not permission
|
||||
policy.plans[0].approval = "approved".into();
|
||||
for (time, expected) in [
|
||||
(999, "unfiled"),
|
||||
(1000, "authorized"),
|
||||
(1999, "authorized"),
|
||||
(2000, "unfiled"),
|
||||
] {
|
||||
assert_eq!(policy.evaluate(&o, time).class, expected);
|
||||
}
|
||||
o.longitude = Some(121.);
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "unfiled");
|
||||
o.longitude = None;
|
||||
o.latitude = None;
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "unknown");
|
||||
o = observation();
|
||||
policy.plans[0].enabled = false;
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "unfiled");
|
||||
policy.plans[0].enabled = true;
|
||||
policy.fences.push(Fence {
|
||||
id: "zone".into(),
|
||||
name: "防控区".into(),
|
||||
enabled: true,
|
||||
geometry: plan().geometry,
|
||||
});
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "geofence_enter");
|
||||
policy.registrations.get_mut("DRONE-A").unwrap().registered = false;
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "geofence_enter");
|
||||
policy.registrations.get_mut("DRONE-A").unwrap().list_kind = Some("white".into());
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "whitelist");
|
||||
policy.registrations.get_mut("DRONE-A").unwrap().list_kind = None;
|
||||
policy.fences.clear();
|
||||
assert_eq!(policy.evaluate(&o, 1500).class, "unregistered");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn submissions_cannot_self_approve_and_edits_invalidate_approval() {
|
||||
let mut db = SqliteConnection::connect("sqlite::memory:").await.unwrap();
|
||||
sqlx::query("CREATE TABLE records(id TEXT PRIMARY KEY)")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO records VALUES(?)")
|
||||
.bind(RECORD)
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
init(&mut db).await.unwrap();
|
||||
let mut input = plan();
|
||||
input.start_ms = crate::realtime::now_ms() as i64;
|
||||
input.end_ms = input.start_ms + 3600000;
|
||||
input.approval = "approved".into();
|
||||
input.reviewed_by = Some("forged".into());
|
||||
let pending = save(&mut db, "test-plan", input).await.unwrap();
|
||||
assert_eq!(pending.approval, "pending");
|
||||
assert!(pending.reviewed_by.is_none());
|
||||
assert!(
|
||||
review(
|
||||
&mut db,
|
||||
"test-plan",
|
||||
Decision {
|
||||
approved: true,
|
||||
expected_revision: 0,
|
||||
note: String::new()
|
||||
},
|
||||
"admin"
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let approved = review(
|
||||
&mut db,
|
||||
"test-plan",
|
||||
Decision {
|
||||
approved: true,
|
||||
expected_revision: pending.revision,
|
||||
note: "允许".into(),
|
||||
},
|
||||
"admin",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(approved.approval, "approved");
|
||||
assert_eq!(approved.reviewed_by.as_deref(), Some("admin"));
|
||||
assert!(save(&mut db, "test-plan", pending).await.is_err());
|
||||
let edited = save(&mut db, "test-plan", approved).await.unwrap();
|
||||
assert_eq!(edited.approval, "pending");
|
||||
assert!(edited.reviewed_at_ms.is_none());
|
||||
assert!(
|
||||
review(
|
||||
&mut db,
|
||||
"test-plan",
|
||||
Decision {
|
||||
approved: false,
|
||||
expected_revision: edited.revision,
|
||||
note: String::new()
|
||||
},
|
||||
"admin"
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let rejected = review(
|
||||
&mut db,
|
||||
"test-plan",
|
||||
Decision {
|
||||
approved: false,
|
||||
expected_revision: edited.revision,
|
||||
note: "区域需调整".into(),
|
||||
},
|
||||
"admin",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rejected.approval, "rejected");
|
||||
let mut expired = rejected;
|
||||
expired.end_ms = 1;
|
||||
expired.start_ms = 0;
|
||||
assert!(save(&mut db, "test-plan", expired).await.is_err());
|
||||
assert_eq!(list(&mut db).await.unwrap()[0].approval, "rejected");
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ use crate::error::{AppError, Result};
|
||||
use rid_shared::{
|
||||
Observation, Target,
|
||||
geofences::{Alert, Fence, Mutation, Snapshot},
|
||||
target_lists::ListKind,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{Connection, Row, SqliteConnection};
|
||||
@@ -49,6 +48,10 @@ pub async fn init(db: &mut SqliteConnection) -> Result<()> {
|
||||
").execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
}
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS monitoring_acknowledgements(event_id INTEGER PRIMARY KEY REFERENCES monitoring_events(id) ON DELETE CASCADE, acknowledged_at_ms INTEGER NOT NULL, acknowledged_by TEXT NOT NULL)")
|
||||
.execute(&mut *db).await?;
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS monitoring_dismissals(username TEXT NOT NULL,event_id INTEGER NOT NULL REFERENCES monitoring_events(id) ON DELETE CASCADE,PRIMARY KEY(username,event_id))")
|
||||
.execute(&mut *db).await?;
|
||||
Ok(())
|
||||
}
|
||||
pub async fn load(db: &mut SqliteConnection) -> Result<Snapshot> {
|
||||
@@ -122,15 +125,16 @@ pub async fn remove(db: &mut SqliteConnection, id: &str, revision: u64) -> Resul
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct Engine {
|
||||
black: HashSet<String>,
|
||||
inside: HashSet<(String, String)>,
|
||||
#[serde(default)]
|
||||
assessments: HashMap<String, String>,
|
||||
last_seen: HashMap<String, u64>,
|
||||
#[serde(default)]
|
||||
revisions: Option<(u64, u64)>,
|
||||
#[serde(default)]
|
||||
membership: HashMap<String, i64>,
|
||||
#[serde(skip)]
|
||||
observation_assessments: Vec<crate::flight_plans::Assessment>,
|
||||
}
|
||||
impl Engine {
|
||||
pub fn observation_assessments(&self) -> &[crate::flight_plans::Assessment] {
|
||||
&self.observation_assessments
|
||||
}
|
||||
pub async fn restore(db: &mut SqliteConnection) -> Result<Self> {
|
||||
let value: Option<String> =
|
||||
sqlx::query_scalar("SELECT value FROM monitoring_state WHERE id=1")
|
||||
@@ -141,72 +145,6 @@ impl Engine {
|
||||
.transpose()
|
||||
.map(Option::unwrap_or_default)
|
||||
}
|
||||
fn observe(
|
||||
&mut self,
|
||||
o: &Observation,
|
||||
time: u64,
|
||||
event_time: u64,
|
||||
kinds: &HashMap<String, ListKind>,
|
||||
fences: &[Fence],
|
||||
events: &mut Vec<Alert>,
|
||||
) {
|
||||
if !o.validate() {
|
||||
return;
|
||||
}
|
||||
let id = &o.target_id;
|
||||
if self
|
||||
.last_seen
|
||||
.get(id)
|
||||
.is_some_and(|t| time.saturating_sub(*t) >= 30000)
|
||||
{
|
||||
self.black.remove(id);
|
||||
self.inside.retain(|(target, _)| target != id);
|
||||
}
|
||||
self.last_seen.insert(id.clone(), time);
|
||||
let kind = kinds.get(id).copied();
|
||||
let white = kind == Some(ListKind::White);
|
||||
let black = kind == Some(ListKind::Black);
|
||||
let mut emit = |event_type: &str, fence: Option<&Fence>| {
|
||||
events.push(Alert {
|
||||
id: 0,
|
||||
occurred_at_ms: event_time,
|
||||
event_type: event_type.into(),
|
||||
target_id: id.clone(),
|
||||
fence_id: fence.map(|f| f.id.clone()),
|
||||
fence_name: fence.map(|f| f.name.clone()),
|
||||
longitude: o.longitude,
|
||||
latitude: o.latitude,
|
||||
list_kind: match kind {
|
||||
Some(ListKind::White) => "white",
|
||||
Some(ListKind::Black) => "black",
|
||||
None => "unknown",
|
||||
}
|
||||
.into(),
|
||||
})
|
||||
};
|
||||
if black {
|
||||
if self.black.insert(id.clone()) {
|
||||
emit("blacklist", None);
|
||||
}
|
||||
} else {
|
||||
self.black.remove(id);
|
||||
}
|
||||
let Some(coordinates) = o.coordinates() else {
|
||||
// Invalidate membership silently; position loss is not an exit event.
|
||||
self.inside.retain(|(target, _)| target != id);
|
||||
return;
|
||||
};
|
||||
for fence in fences.iter().filter(|f| f.enabled) {
|
||||
let key = (id.clone(), fence.id.clone());
|
||||
if !white && fence.geometry.contains(coordinates) {
|
||||
if self.inside.insert(key) {
|
||||
emit("geofence_enter", Some(fence));
|
||||
}
|
||||
} else {
|
||||
self.inside.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub async fn process(
|
||||
&mut self,
|
||||
db: &mut SqliteConnection,
|
||||
@@ -215,56 +153,91 @@ impl Engine {
|
||||
now: u64,
|
||||
) -> Result<usize> {
|
||||
let mut tx = db.begin().await?;
|
||||
let lists = crate::target_lists::load(&mut tx).await?;
|
||||
let list_revision = lists.revision;
|
||||
let kinds = lists
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|e| (e.target_id, e.list_kind))
|
||||
let active: Vec<_> = active
|
||||
.iter()
|
||||
.filter(|t| now.saturating_sub(t.received_at_ms) < 30000)
|
||||
.collect();
|
||||
let snapshot = load(&mut tx).await?;
|
||||
let revisions = (list_revision, snapshot.revision);
|
||||
let fences = snapshot.entries;
|
||||
let mut next = self.clone();
|
||||
let membership: HashMap<String, i64> = sqlx::query_as::<_, (String, i64)>(
|
||||
let ids: HashSet<_> = observations
|
||||
.iter()
|
||||
.map(|(o, _)| o.target_id.as_str())
|
||||
.chain(active.iter().map(|t| t.observation.target_id.as_str()))
|
||||
.collect();
|
||||
let policy =
|
||||
crate::flight_plans::Policy::load(&mut tx, &ids.into_iter().collect::<Vec<_>>())
|
||||
.await?;
|
||||
let memberships: HashMap<String, i64> = sqlx::query_as::<_, (String, i64)>(
|
||||
"SELECT target_id,version FROM monitoring_membership",
|
||||
)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect();
|
||||
next.black
|
||||
.retain(|id| next.membership.get(id) == membership.get(id));
|
||||
next.membership = membership;
|
||||
next.inside
|
||||
.retain(|(_, id)| fences.iter().any(|f| f.enabled && &f.id == id));
|
||||
let mut next = self.clone();
|
||||
// History and alarms share this transaction's policy snapshot.
|
||||
next.observation_assessments = observations
|
||||
.iter()
|
||||
.map(|(o, time)| policy.evaluate(o, *time))
|
||||
.collect();
|
||||
let mut events = Vec::new();
|
||||
for (o, time) in observations {
|
||||
next.observe(o, *time, *time, &kinds, &fences, &mut events);
|
||||
}
|
||||
if next.revisions != Some(revisions) {
|
||||
for t in active
|
||||
.iter()
|
||||
.filter(|t| now.saturating_sub(t.received_at_ms) < 30000)
|
||||
{
|
||||
next.observe(
|
||||
&t.observation,
|
||||
t.received_at_ms,
|
||||
now,
|
||||
&kinds,
|
||||
&fences,
|
||||
&mut events,
|
||||
);
|
||||
// One authoritative classification, emitted on transitions, never on every packet.
|
||||
let mut assess = |o: &Observation, sample_time: u64, event_time: u64| {
|
||||
if !o.validate() {
|
||||
return;
|
||||
}
|
||||
if next
|
||||
.last_seen
|
||||
.get(&o.target_id)
|
||||
.is_some_and(|t| sample_time.saturating_sub(*t) >= 30000)
|
||||
{
|
||||
next.assessments.remove(&o.target_id);
|
||||
}
|
||||
next.last_seen.insert(o.target_id.clone(), sample_time);
|
||||
let assessment = policy.evaluate(o, event_time);
|
||||
let membership = if assessment.class == "blacklist" {
|
||||
memberships.get(&o.target_id).copied().unwrap_or_default()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let key = format!(
|
||||
"{}:{}:{membership}",
|
||||
assessment.class,
|
||||
assessment.fence_id.as_deref().unwrap_or("")
|
||||
);
|
||||
if next
|
||||
.assessments
|
||||
.insert(o.target_id.clone(), key.clone())
|
||||
.as_ref()
|
||||
== Some(&key)
|
||||
|| !crate::flight_plans::alarming(&assessment.class)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let coordinates = o.coordinates().filter(|p| {
|
||||
*p != [0., 0.] && !o.telemetry.as_ref().is_some_and(|t| t.position_unverified)
|
||||
});
|
||||
events.push(Alert {
|
||||
id: 0,
|
||||
occurred_at_ms: event_time,
|
||||
event_type: assessment.class,
|
||||
target_id: o.target_id.clone(),
|
||||
fence_id: assessment.fence_id,
|
||||
fence_name: assessment.fence_name,
|
||||
longitude: coordinates.map(|p| p[0]),
|
||||
latitude: coordinates.map(|p| p[1]),
|
||||
list_kind: assessment.list_kind,
|
||||
});
|
||||
};
|
||||
for (o, time) in observations {
|
||||
assess(o, *time, *time);
|
||||
}
|
||||
// Re-evaluate on time/registration/filing changes, including expiry without new frames.
|
||||
for t in active {
|
||||
assess(&t.observation, t.received_at_ms, now);
|
||||
}
|
||||
next.revisions = Some(revisions);
|
||||
// A service restart has an empty live store until the next receiver frame.
|
||||
// Keep persisted membership for the same 30s TTL instead of alerting again.
|
||||
next.last_seen
|
||||
.retain(|_, time| now.saturating_sub(*time) < 30000);
|
||||
next.black.retain(|id| next.last_seen.contains_key(id));
|
||||
next.inside
|
||||
.retain(|(id, _)| next.last_seen.contains_key(id));
|
||||
next.assessments
|
||||
.retain(|id, _| next.last_seen.contains_key(id));
|
||||
for e in &events {
|
||||
sqlx::query("INSERT INTO monitoring_events(occurred_at_ms,event_type,target_id,fence_id,fence_name,longitude,latitude,list_kind) VALUES(?1,?2,?3,?4,?5,?6,?7,?8)")
|
||||
.bind(i64::try_from(e.occurred_at_ms).map_err(|_|AppError::Validation("事件时间无效".into()))?).bind(&e.event_type).bind(&e.target_id).bind(&e.fence_id).bind(&e.fence_name).bind(e.longitude).bind(e.latitude).bind(&e.list_kind).execute(&mut *tx).await?;
|
||||
@@ -279,6 +252,14 @@ impl Engine {
|
||||
pub async fn events(
|
||||
db: &mut SqliteConnection,
|
||||
p: &HashMap<String, String>,
|
||||
) -> Result<serde_json::Value> {
|
||||
center_events(db, p, None).await
|
||||
}
|
||||
|
||||
pub async fn center_events(
|
||||
db: &mut SqliteConnection,
|
||||
p: &HashMap<String, String>,
|
||||
viewer: Option<&str>,
|
||||
) -> Result<serde_json::Value> {
|
||||
let number = |name: &str, default: u64| -> Result<u64> {
|
||||
p.get(name)
|
||||
@@ -290,25 +271,85 @@ pub async fn events(
|
||||
};
|
||||
let after = number("after", 0)?;
|
||||
let before = number("before", i64::MAX as u64)?;
|
||||
let from = number("from_ms", 0)?;
|
||||
let to = number("to_ms", i64::MAX as u64)?;
|
||||
let limit = number("limit", 50)?.clamp(1, 200);
|
||||
if after > i64::MAX as u64 || before > i64::MAX as u64 {
|
||||
let offset = number("offset", 0)?;
|
||||
if [after, before, from, to, offset]
|
||||
.iter()
|
||||
.any(|value| *value > i64::MAX as u64)
|
||||
|| from > to
|
||||
{
|
||||
return Err("告警游标无效".into());
|
||||
}
|
||||
let kind = p.get("type").map_or("", String::as_str);
|
||||
if !matches!(kind, "" | "blacklist" | "geofence_enter") {
|
||||
if !matches!(
|
||||
kind,
|
||||
"" | "blacklist" | "geofence_enter" | "unregistered" | "unfiled"
|
||||
) {
|
||||
return Err("告警类型无效".into());
|
||||
}
|
||||
let target = p.get("target_id").map_or("", String::as_str);
|
||||
let fence = p.get("fence_id").map_or("", String::as_str);
|
||||
let keyword = p.get("q").map_or("", String::as_str);
|
||||
if keyword.len() > 192 {
|
||||
return Err("告警关键词过长".into());
|
||||
}
|
||||
let handled = match p.get("handled").map(String::as_str) {
|
||||
None | Some("") => -1,
|
||||
Some("0") => 0,
|
||||
Some("1") => 1,
|
||||
_ => return Err("告警处置筛选无效".into()),
|
||||
};
|
||||
let order = if p.get("order").is_some_and(|v| v == "asc") {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut sql = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
|
||||
"SELECT id,occurred_at_ms,event_type,target_id,fence_id,fence_name,longitude,latitude,list_kind FROM monitoring_events WHERE id>?1 AND id<?2 AND (?3='' OR event_type=?3) AND (?4='' OR target_id=?4) AND (?5='' OR fence_id=?5) ORDER BY id ",
|
||||
let matching = |projection: &str| {
|
||||
let mut sql = sqlx::QueryBuilder::<sqlx::Sqlite>::new(projection);
|
||||
sql.push(
|
||||
" FROM monitoring_events LEFT JOIN monitoring_acknowledgements ON event_id=id
|
||||
WHERE id>?1 AND id<?2 AND (?3='' OR event_type=?3) AND (?4='' OR target_id=?4)
|
||||
AND (?5='' OR fence_id=?5) AND occurred_at_ms BETWEEN ?6 AND ?7
|
||||
AND (?8='' OR instr(lower(target_id),lower(?8))>0 OR instr(lower(COALESCE(fence_name,'')),lower(?8))>0 OR instr(event_type,?8)>0)
|
||||
AND (?9=-1 OR (acknowledged_at_ms IS NOT NULL)=?9)
|
||||
AND (?10 IS NULL OR NOT EXISTS(SELECT 1 FROM monitoring_dismissals WHERE username=?10 AND event_id=monitoring_events.id))",
|
||||
);
|
||||
sql
|
||||
};
|
||||
let mut tx = db.begin().await?;
|
||||
let with_counts = p.get("counts").is_some_and(|v| v == "1");
|
||||
let counts = if p.contains_key("offset") || with_counts {
|
||||
Some(
|
||||
matching("SELECT COUNT(*), COUNT(acknowledged_at_ms)")
|
||||
.build_query_as::<(i64, i64)>()
|
||||
.bind(after as i64)
|
||||
.bind(before as i64)
|
||||
.bind(kind)
|
||||
.bind(target)
|
||||
.bind(fence)
|
||||
.bind(from as i64)
|
||||
.bind(to as i64)
|
||||
.bind(keyword)
|
||||
.bind(handled)
|
||||
.bind(viewer)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut sql = matching(
|
||||
"SELECT id,occurred_at_ms,event_type,target_id,fence_id,fence_name,longitude,latitude,list_kind,acknowledged_at_ms,acknowledged_by",
|
||||
);
|
||||
sql.push(order).push(" LIMIT ?6");
|
||||
sql.push(if viewer.is_some() {
|
||||
" ORDER BY (acknowledged_at_ms IS NOT NULL) ASC,id "
|
||||
} else {
|
||||
" ORDER BY id "
|
||||
})
|
||||
.push(order)
|
||||
.push(" LIMIT ?11 OFFSET ?12");
|
||||
let rows = sql
|
||||
.build()
|
||||
.bind(after as i64)
|
||||
@@ -316,36 +357,122 @@ pub async fn events(
|
||||
.bind(kind)
|
||||
.bind(target)
|
||||
.bind(fence)
|
||||
.bind(from as i64)
|
||||
.bind(to as i64)
|
||||
.bind(keyword)
|
||||
.bind(handled)
|
||||
.bind(viewer)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(db)
|
||||
.bind(offset as i64)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let entries = rows
|
||||
.iter()
|
||||
.map(|r| -> Result<Alert> {
|
||||
Ok(Alert {
|
||||
id: unsigned(r, 0)?,
|
||||
occurred_at_ms: unsigned(r, 1)?,
|
||||
event_type: r.try_get(2)?,
|
||||
target_id: r.try_get(3)?,
|
||||
fence_id: r.try_get(4)?,
|
||||
fence_name: r.try_get(5)?,
|
||||
longitude: r.try_get(6)?,
|
||||
latitude: r.try_get(7)?,
|
||||
list_kind: r.try_get(8)?,
|
||||
})
|
||||
.map(|r| -> Result<(Alert, Option<i64>, Option<String>)> {
|
||||
Ok((
|
||||
Alert {
|
||||
id: unsigned(r, 0)?,
|
||||
occurred_at_ms: unsigned(r, 1)?,
|
||||
event_type: r.try_get(2)?,
|
||||
target_id: r.try_get(3)?,
|
||||
fence_id: r.try_get(4)?,
|
||||
fence_name: r.try_get(5)?,
|
||||
longitude: r.try_get(6)?,
|
||||
latitude: r.try_get(7)?,
|
||||
list_kind: r.try_get(8)?,
|
||||
},
|
||||
r.try_get(9)?,
|
||||
r.try_get(10)?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(serde_json::json!({"next_before":entries.last().map(|e|e.id),"entries":entries}))
|
||||
let next_before = entries.last().map(|(event, _, _)| event.id);
|
||||
let entries: Vec<_> = entries
|
||||
.into_iter()
|
||||
.map(|(event, at, by)| {
|
||||
let mut value = serde_json::json!(event);
|
||||
value["acknowledged_at_ms"] = serde_json::json!(at);
|
||||
value["acknowledged_by"] = serde_json::json!(by);
|
||||
value
|
||||
})
|
||||
.collect();
|
||||
let mut result = serde_json::json!({"next_before":next_before,"entries":entries});
|
||||
if let Some((total, read)) = counts {
|
||||
result["total"] = serde_json::json!(total);
|
||||
if with_counts {
|
||||
result["read"] = serde_json::json!(read);
|
||||
result["unread"] = serde_json::json!(total - read);
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn acknowledge(db: &mut SqliteConnection, id: i64, actor: &str) -> Result<()> {
|
||||
let now = i64::try_from(crate::realtime::now_ms()).unwrap_or(i64::MAX);
|
||||
let result = sqlx::query("INSERT OR IGNORE INTO monitoring_acknowledgements(event_id,acknowledged_at_ms,acknowledged_by) SELECT id,?,? FROM monitoring_events WHERE id=?")
|
||||
.bind(now).bind(actor).bind(id).execute(&mut *db).await?;
|
||||
if result.rows_affected() == 0 {
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM monitoring_acknowledgements WHERE event_id=?)",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if !exists {
|
||||
return Err(AppError::NotFound("告警不存在"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn dismiss(db: &mut SqliteConnection, id: i64, actor: &str) -> Result<()> {
|
||||
let exists: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM monitoring_events WHERE id=?)")
|
||||
.bind(id)
|
||||
.fetch_one(&mut *db)
|
||||
.await?;
|
||||
if !exists {
|
||||
return Err(AppError::NotFound("告警不存在"));
|
||||
}
|
||||
sqlx::query("INSERT OR IGNORE INTO monitoring_dismissals(username,event_id) VALUES(?,?)")
|
||||
.bind(actor)
|
||||
.bind(id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rid_shared::{geofences::Geometry, target_lists::Mutation as ListMutation};
|
||||
use rid_shared::{
|
||||
geofences::Geometry,
|
||||
target_lists::{ListKind, Mutation as ListMutation},
|
||||
};
|
||||
async fn db() -> SqliteConnection {
|
||||
let mut db = SqliteConnection::connect("sqlite::memory:").await.unwrap();
|
||||
sqlx::query("CREATE TABLE records(id TEXT PRIMARY KEY, serial_no TEXT UNIQUE)")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO records VALUES ('record-a','DRONE-A')")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::target_bindings::init(&mut db).await.unwrap();
|
||||
crate::target_lists::init(&mut db).await.unwrap();
|
||||
init(&mut db).await.unwrap();
|
||||
crate::flight_plans::init(&mut db).await.unwrap();
|
||||
// Baseline registered aircraft has an approved allowed area outside the fences too.
|
||||
let plan = serde_json::json!({"id":"baseline","recordId":"record-a","name":"测试报备",
|
||||
"startMs":1,"endMs":1000000000,"geometry":{"type":"circle","center":[120.,30.],"radius_m":200000.},
|
||||
"note":"","enabled":true,"revision":1,"approval":"approved"});
|
||||
sqlx::query("INSERT INTO flight_plans VALUES('baseline','record-a',?)")
|
||||
.bind(plan.to_string())
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
db
|
||||
}
|
||||
fn fence(id: &str) -> Fence {
|
||||
@@ -359,6 +486,27 @@ mod tests {
|
||||
},
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn dismissing_one_center_alert_preserves_other_events_history_and_accounts() {
|
||||
let mut db = db().await;
|
||||
sqlx::query("INSERT INTO monitoring_events(occurred_at_ms,event_type,target_id,list_kind) VALUES(1,'unregistered','A','none'),(2,'unregistered','B','none')").execute(&mut db).await.unwrap();
|
||||
let query = HashMap::from([("counts".into(), "1".into())]);
|
||||
let original = events(&mut db, &query).await.unwrap();
|
||||
let id = original["entries"][0]["id"].as_i64().unwrap();
|
||||
dismiss(&mut db, id, "alice").await.unwrap();
|
||||
dismiss(&mut db, id, "alice").await.unwrap();
|
||||
init(&mut db).await.unwrap();
|
||||
let alice = center_events(&mut db, &query, Some("alice")).await.unwrap();
|
||||
assert_eq!(alice["total"], 1);
|
||||
assert_eq!(alice["unread"], 1);
|
||||
assert_eq!(alice["entries"][0]["target_id"], "A");
|
||||
assert_eq!(events(&mut db, &query).await.unwrap()["total"], 2);
|
||||
assert_eq!(
|
||||
center_events(&mut db, &query, Some("bob")).await.unwrap()["total"],
|
||||
2
|
||||
);
|
||||
assert!(dismiss(&mut db, 999, "alice").await.is_err());
|
||||
}
|
||||
fn observation(lon: f64, sequence: u64) -> Observation {
|
||||
Observation {
|
||||
target_id: "DRONE-A".into(),
|
||||
@@ -408,6 +556,52 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn registration_alert_is_durable_without_a_position_and_rearms_after_loss() {
|
||||
let mut db = db().await;
|
||||
let mut unknown = observation(120.0, 1);
|
||||
unknown.target_id = "UNREGISTERED".into();
|
||||
unknown.longitude = None;
|
||||
unknown.latitude = None;
|
||||
let mut engine = Engine::default();
|
||||
assert_eq!(
|
||||
step(&mut engine, &mut db, observation(120.0, 1), 1000).await,
|
||||
0
|
||||
);
|
||||
assert_eq!(step(&mut engine, &mut db, unknown.clone(), 1000).await, 1);
|
||||
let mut restarted = Engine::restore(&mut db).await.unwrap();
|
||||
assert_eq!(
|
||||
step(&mut restarted, &mut db, unknown.clone(), 1001).await,
|
||||
0
|
||||
);
|
||||
let filtered = events(
|
||||
&mut db,
|
||||
&HashMap::from([("type".into(), "unregistered".into())]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(filtered["entries"][0]["target_id"], "UNREGISTERED");
|
||||
assert!(filtered["entries"][0]["longitude"].is_null());
|
||||
|
||||
sqlx::query("INSERT INTO target_record_bindings VALUES ('UNREGISTERED','record-a')")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
step(&mut restarted, &mut db, unknown.clone(), 1002).await,
|
||||
0
|
||||
);
|
||||
sqlx::query("DELETE FROM target_record_bindings WHERE target_id='UNREGISTERED'")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
step(&mut restarted, &mut db, unknown.clone(), 1003).await,
|
||||
1
|
||||
);
|
||||
assert_eq!(step(&mut restarted, &mut db, unknown, 31003).await, 1);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn unlocated_blacklist_is_recorded_without_fence_entry() {
|
||||
let mut db = db().await;
|
||||
@@ -442,7 +636,7 @@ mod tests {
|
||||
let mut o = observation(120., 3);
|
||||
o.longitude = None;
|
||||
o.latitude = None;
|
||||
assert_eq!(step(&mut engine, &mut db, o, 1002).await, 0);
|
||||
assert_eq!(step(&mut engine, &mut db, o, 1002).await, 1);
|
||||
assert_eq!(
|
||||
step(&mut engine, &mut db, observation(120., 4), 1003).await,
|
||||
1
|
||||
@@ -545,7 +739,7 @@ mod tests {
|
||||
let mut engine = Engine::default();
|
||||
assert_eq!(
|
||||
step(&mut engine, &mut db, observation(120.0, 1), 1000).await,
|
||||
2
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
step(&mut engine, &mut db, observation(120.0, 2), 1001).await,
|
||||
@@ -569,7 +763,7 @@ mod tests {
|
||||
.process(&mut db, &batch, &active, 1004)
|
||||
.await
|
||||
.unwrap(),
|
||||
2
|
||||
1
|
||||
);
|
||||
classify(&mut db, ListKind::White).await;
|
||||
assert_eq!(
|
||||
@@ -593,7 +787,7 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
3
|
||||
1
|
||||
);
|
||||
let mut restarted = Engine::restore(&mut db).await.unwrap();
|
||||
assert_eq!(restarted.process(&mut db, &[], &[], 1006).await.unwrap(), 0);
|
||||
@@ -603,7 +797,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
step(&mut restarted, &mut db, observation(120.0, 8), 32007).await,
|
||||
3
|
||||
1
|
||||
);
|
||||
let filtered = events(
|
||||
&mut db,
|
||||
@@ -644,7 +838,7 @@ mod tests {
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(engine.black.is_empty());
|
||||
assert!(engine.assessments.is_empty());
|
||||
sqlx::raw_sql("DROP TRIGGER reject_event")
|
||||
.execute(&mut db)
|
||||
.await
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Persist sampled, verified positions separately from the registry database.
|
||||
use crate::{config::SqliteConfig, error::Result};
|
||||
use crate::{config::SqliteConfig, error::Result, observations::Recorder};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
routing::get,
|
||||
};
|
||||
use rid_shared::Observation;
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{
|
||||
Row, SqlitePool,
|
||||
@@ -22,7 +22,7 @@ use std::{
|
||||
};
|
||||
|
||||
const SAMPLE_MS: u64 = 1_000;
|
||||
const GAP_MS: u64 = 30_000;
|
||||
const GAP_MS: u64 = crate::realtime::TARGET_TTL_MS;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Cursor {
|
||||
@@ -42,12 +42,69 @@ struct PendingPoint {
|
||||
latitude: f64,
|
||||
altitude_m: Option<f32>,
|
||||
heading_deg: Option<f32>,
|
||||
flight_key: String,
|
||||
osd: Option<PlaybackOsd>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PlaybackOsd {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
speed_mps: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
vertical_speed_mps: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
rssi: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
height_agl_m: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
relative_height_m: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pressure_altitude_m: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
geometric_altitude_m: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pilot_position: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl PlaybackOsd {
|
||||
fn from_telemetry(value: &rid_shared::DeviceTelemetry) -> Option<Self> {
|
||||
let fields = [
|
||||
value.speed_mps,
|
||||
value.vertical_speed_mps,
|
||||
value.rssi,
|
||||
value.height_agl_m,
|
||||
value.relative_height_m,
|
||||
value.geometric_altitude_m,
|
||||
value.pressure_altitude_m,
|
||||
];
|
||||
(fields.iter().any(Option::is_some) || value.pilot_position.is_some()).then_some(Self {
|
||||
speed_mps: value.speed_mps,
|
||||
vertical_speed_mps: value.vertical_speed_mps,
|
||||
rssi: value.rssi,
|
||||
height_agl_m: value.height_agl_m,
|
||||
relative_height_m: value.relative_height_m,
|
||||
pressure_altitude_m: value.pressure_altitude_m,
|
||||
geometric_altitude_m: value.geometric_altitude_m,
|
||||
pilot_position: value.pilot_position,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HistoryState {
|
||||
tracks: HashMap<String, Cursor>,
|
||||
observations: Recorder,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct History {
|
||||
pool: SqlitePool,
|
||||
cursors: Arc<tokio::sync::Mutex<HashMap<String, Cursor>>>,
|
||||
pub(crate) pool: SqlitePool,
|
||||
state: Arc<tokio::sync::Mutex<HistoryState>>,
|
||||
}
|
||||
|
||||
fn reception(entry: &(Observation, u64, bool)) -> (&Observation, u64, bool) {
|
||||
(&entry.0, entry.1, entry.2)
|
||||
}
|
||||
|
||||
fn sql_time(value: u64) -> Result<i64> {
|
||||
@@ -59,10 +116,12 @@ async fn insert_point(
|
||||
point: &PendingPoint,
|
||||
segment: bool,
|
||||
) -> Result<()> {
|
||||
sqlx::query("INSERT INTO track_points(target_id,receiver_id,received_at_ms,longitude,latitude,altitude_m,heading_deg,segment_start) VALUES(?,?,?,?,?,?,?,?)")
|
||||
sqlx::query("INSERT INTO track_points(target_id,receiver_id,received_at_ms,longitude,latitude,altitude_m,heading_deg,segment_start,flight_key,osd) VALUES(?,?,?,?,?,?,?,?,?,?)")
|
||||
.bind(&point.target_id).bind(&point.receiver_id).bind(sql_time(point.received_at_ms)?)
|
||||
.bind(point.longitude).bind(point.latitude).bind(point.altitude_m).bind(point.heading_deg)
|
||||
.bind(i64::from(segment)).execute(&mut **tx).await?;
|
||||
.bind(i64::from(segment)).bind(&point.flight_key)
|
||||
.bind(point.osd.as_ref().map(serde_json::to_string).transpose().map_err(|error| error.to_string())?)
|
||||
.execute(&mut **tx).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -117,6 +176,7 @@ impl History {
|
||||
located INTEGER NOT NULL
|
||||
);",
|
||||
).execute(&pool).await?;
|
||||
crate::observations::prepare(&pool).await?;
|
||||
let mut cursors = HashMap::new();
|
||||
for row in sqlx::query(
|
||||
"SELECT target_id,last_seen_ms,last_recorded_ms,receiver_id,located FROM track_state",
|
||||
@@ -140,7 +200,10 @@ impl History {
|
||||
}
|
||||
Ok(Self {
|
||||
pool,
|
||||
cursors: Arc::new(tokio::sync::Mutex::new(cursors)),
|
||||
state: Arc::new(tokio::sync::Mutex::new(HistoryState {
|
||||
tracks: cursors,
|
||||
observations: Recorder::default(),
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -150,44 +213,97 @@ impl History {
|
||||
|
||||
/// Store at most one ordinary point per target per second; a new source,
|
||||
/// missing position, or a 30-second gap starts a separate segment.
|
||||
#[cfg(test)]
|
||||
pub async fn record(&self, observations: &[(Observation, u64)]) -> Result<()> {
|
||||
self.record_at(observations, crate::realtime::now_ms(), false)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Flush the last accepted position before a graceful shutdown.
|
||||
pub async fn flush(&self) -> Result<()> {
|
||||
self.record_at(&[], crate::realtime::now_ms(), true).await
|
||||
pub async fn record_monitored(
|
||||
&self,
|
||||
observations: &crate::realtime::ObservationBatch,
|
||||
) -> Result<()> {
|
||||
self.record_entries(
|
||||
observations.iter().map(reception),
|
||||
crate::realtime::now_ms(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Flush the last accepted position and reception time before shutdown.
|
||||
pub async fn flush(&self) -> Result<()> {
|
||||
self.record_entries(std::iter::empty(), crate::realtime::now_ms(), true)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn record_at(
|
||||
&self,
|
||||
observations: &[(Observation, u64)],
|
||||
now_ms: u64,
|
||||
force: bool,
|
||||
) -> Result<()> {
|
||||
let mut state = self.cursors.lock().await;
|
||||
let needs_idle_work = state.values().any(|cursor| {
|
||||
self.record_entries(
|
||||
observations
|
||||
.iter()
|
||||
.map(|(observation, now)| (observation, *now, true)),
|
||||
now_ms,
|
||||
force,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn record_entries<'a>(
|
||||
&self,
|
||||
observations: impl Iterator<Item = (&'a Observation, u64, bool)> + Send,
|
||||
now_ms: u64,
|
||||
force: bool,
|
||||
) -> Result<()> {
|
||||
let mut observations = observations.peekable();
|
||||
let mut state = self.state.lock().await;
|
||||
let sql_now = sql_time(now_ms)?;
|
||||
let needs_idle_work = state.tracks.values().any(|cursor| {
|
||||
(cursor.pending.is_some()
|
||||
&& (force || now_ms.saturating_sub(cursor.last_recorded_ms) >= SAMPLE_MS))
|
||||
|| (now_ms >= cursor.last_seen_ms
|
||||
&& now_ms.saturating_sub(cursor.last_seen_ms) >= GAP_MS)
|
||||
});
|
||||
if observations.is_empty() && !needs_idle_work {
|
||||
if observations.peek().is_none()
|
||||
&& !needs_idle_work
|
||||
&& !state.observations.needs_flush(sql_now, force)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let mut next = state.clone();
|
||||
let mut dirty = HashSet::new();
|
||||
let mut tx = self.pool.begin().await?;
|
||||
for (observation, now) in observations {
|
||||
let cursor = next.entry(observation.target_id.clone()).or_default();
|
||||
for (observation, now, received) in observations {
|
||||
if !received {
|
||||
if let Some(cursor) = next.tracks.get_mut(&observation.target_id)
|
||||
&& cursor.located
|
||||
{
|
||||
flush_cursor(&mut tx, cursor).await?;
|
||||
cursor.located = false;
|
||||
dirty.insert(observation.target_id.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let flight_key = next
|
||||
.observations
|
||||
.record(&mut tx, observation, sql_time(now)?)
|
||||
.await?;
|
||||
let cursor = next
|
||||
.tracks
|
||||
.entry(observation.target_id.clone())
|
||||
.or_default();
|
||||
let was_seen = cursor.last_seen_ms != 0;
|
||||
let segment = !cursor.located
|
||||
|| cursor.receiver_id != observation.receiver_id
|
||||
|| (was_seen
|
||||
&& (*now < cursor.last_seen_ms
|
||||
&& (now < cursor.last_seen_ms
|
||||
|| now.saturating_sub(cursor.last_seen_ms) >= GAP_MS));
|
||||
cursor.last_seen_ms = *now;
|
||||
cursor.last_seen_ms = now;
|
||||
let position = if observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
@@ -208,11 +324,16 @@ impl History {
|
||||
let point = PendingPoint {
|
||||
target_id: observation.target_id.clone(),
|
||||
receiver_id: observation.receiver_id.clone(),
|
||||
received_at_ms: *now,
|
||||
received_at_ms: now,
|
||||
longitude,
|
||||
latitude,
|
||||
altitude_m: observation.altitude_m,
|
||||
heading_deg: observation.heading_deg,
|
||||
flight_key,
|
||||
osd: observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
.and_then(PlaybackOsd::from_telemetry),
|
||||
};
|
||||
if segment || now.saturating_sub(cursor.last_recorded_ms) >= SAMPLE_MS {
|
||||
if segment && cursor.located {
|
||||
@@ -221,7 +342,7 @@ impl History {
|
||||
cursor.pending = None;
|
||||
}
|
||||
insert_point(&mut tx, &point, segment).await?;
|
||||
cursor.last_recorded_ms = *now;
|
||||
cursor.last_recorded_ms = now;
|
||||
cursor.receiver_id.clone_from(&observation.receiver_id);
|
||||
cursor.located = true;
|
||||
dirty.insert(observation.target_id.clone());
|
||||
@@ -229,7 +350,7 @@ impl History {
|
||||
cursor.pending = Some(point);
|
||||
}
|
||||
}
|
||||
for (id, cursor) in &mut next {
|
||||
for (id, cursor) in &mut next.tracks {
|
||||
if cursor.pending.is_some()
|
||||
&& (force || now_ms.saturating_sub(cursor.last_recorded_ms) >= SAMPLE_MS)
|
||||
&& flush_cursor(&mut tx, cursor).await?
|
||||
@@ -238,13 +359,14 @@ impl History {
|
||||
}
|
||||
}
|
||||
for id in dirty {
|
||||
if let Some(cursor) = next.get(&id) {
|
||||
if let Some(cursor) = next.tracks.get(&id) {
|
||||
sqlx::query("INSERT INTO track_state(target_id,last_seen_ms,last_recorded_ms,receiver_id,located) VALUES(?,?,?,?,?) ON CONFLICT(target_id) DO UPDATE SET last_seen_ms=excluded.last_seen_ms,last_recorded_ms=excluded.last_recorded_ms,receiver_id=excluded.receiver_id,located=excluded.located")
|
||||
.bind(id).bind(sql_time(cursor.last_seen_ms)?).bind(sql_time(cursor.last_recorded_ms)?)
|
||||
.bind(&cursor.receiver_id).bind(i64::from(cursor.located)).execute(&mut *tx).await?;
|
||||
}
|
||||
}
|
||||
let stale: Vec<_> = next
|
||||
.tracks
|
||||
.iter()
|
||||
.filter(|(_, cursor)| {
|
||||
now_ms >= cursor.last_seen_ms
|
||||
@@ -253,12 +375,13 @@ impl History {
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
for id in stale {
|
||||
next.remove(&id);
|
||||
next.tracks.remove(&id);
|
||||
sqlx::query("DELETE FROM track_state WHERE target_id=?")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
next.observations.finish(&mut tx, sql_now, force).await?;
|
||||
tx.commit().await?;
|
||||
*state = next;
|
||||
Ok(())
|
||||
@@ -294,20 +417,53 @@ impl History {
|
||||
}
|
||||
let after = sql_time(query.after.unwrap_or(0))?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000);
|
||||
let rows = sqlx::query("SELECT id,received_at_ms,longitude,latitude,altitude_m,heading_deg,receiver_id,segment_start FROM track_points WHERE target_id=? AND received_at_ms>=? AND received_at_ms<=? AND id>? ORDER BY id LIMIT ?")
|
||||
.bind(&query.target_id).bind(from).bind(to).bind(after).bind(i64::from(limit))
|
||||
let rows = sqlx::query(
|
||||
"SELECT id,received_at_ms,longitude,latitude,altitude_m,heading_deg,receiver_id,segment_start,osd
|
||||
FROM track_points WHERE target_id=? AND received_at_ms>=? AND received_at_ms<=? AND id>? ORDER BY id LIMIT ?",
|
||||
).bind(&query.target_id).bind(from).bind(to).bind(after).bind(i64::from(limit))
|
||||
.fetch_all(&self.pool).await?;
|
||||
let mut entries = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
entries.push(json!({"id":row.try_get::<i64,_>(0)?,"timeMs":row.try_get::<i64,_>(1)?,"longitude":row.try_get::<f64,_>(2)?,"latitude":row.try_get::<f64,_>(3)?,"altitudeM":row.try_get::<Option<f64>,_>(4)?,"headingDeg":row.try_get::<Option<f64>,_>(5)?,"receiverId":row.try_get::<String,_>(6)?,"segmentStart":row.try_get::<i64,_>(7)?!=0}));
|
||||
}
|
||||
let next_after = if entries.len() == limit as usize {
|
||||
entries.last().and_then(|entry| entry["id"].as_i64())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"entries":entries,"nextAfter":next_after,"sampleIntervalMs":SAMPLE_MS}))
|
||||
point_response(rows, limit)
|
||||
}
|
||||
|
||||
async fn flight_points(&self, query: &FlightPointQuery) -> Result<Value> {
|
||||
if query.flight_key.len() != 32 || !query.flight_key.bytes().all(|c| c.is_ascii_hexdigit())
|
||||
{
|
||||
return Err("记录标识无效".into());
|
||||
}
|
||||
let after = sql_time(query.after.unwrap_or(0))?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000);
|
||||
let rows = sqlx::query(
|
||||
"SELECT id,received_at_ms,longitude,latitude,altitude_m,heading_deg,receiver_id,segment_start,osd
|
||||
FROM track_points WHERE flight_key=? AND id>? ORDER BY id LIMIT ?",
|
||||
).bind(&query.flight_key).bind(after).bind(i64::from(limit))
|
||||
.fetch_all(&self.pool).await?;
|
||||
point_response(rows, limit)
|
||||
}
|
||||
}
|
||||
|
||||
fn point_response(rows: Vec<sqlx::sqlite::SqliteRow>, limit: u32) -> Result<Value> {
|
||||
let mut entries = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let osd: Option<String> = row.try_get(8)?;
|
||||
let osd = osd
|
||||
.as_deref()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.transpose()
|
||||
.map_err(|error| error.to_string())?;
|
||||
entries.push(json!({
|
||||
"id":row.try_get::<i64,_>(0)?,"timeMs":row.try_get::<i64,_>(1)?,
|
||||
"longitude":row.try_get::<f64,_>(2)?,"latitude":row.try_get::<f64,_>(3)?,
|
||||
"altitudeM":row.try_get::<Option<f64>,_>(4)?,"headingDeg":row.try_get::<Option<f64>,_>(5)?,
|
||||
"receiverId":row.try_get::<String,_>(6)?,"segmentStart":row.try_get::<i64,_>(7)?!=0,
|
||||
"osd":osd
|
||||
}));
|
||||
}
|
||||
let next_after = if entries.len() == limit as usize {
|
||||
entries.last().and_then(|entry| entry["id"].as_i64())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"entries":entries,"nextAfter":next_after,"sampleIntervalMs":SAMPLE_MS}))
|
||||
}
|
||||
|
||||
fn range(from: u64, to: u64) -> Result<(i64, i64)> {
|
||||
@@ -337,13 +493,51 @@ struct PointQuery {
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct FlightPointQuery {
|
||||
flight_key: String,
|
||||
after: Option<u64>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
pub(crate) fn router(history: History) -> Router {
|
||||
Router::new()
|
||||
.route("/api/history/targets", get(targets))
|
||||
.route("/api/history/points", get(points))
|
||||
.route("/api/history/flight-points", get(flight_points))
|
||||
.route("/api/history/summary", get(summary))
|
||||
.with_state(history)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HistorySummaryQuery {
|
||||
from_ms: u64,
|
||||
}
|
||||
|
||||
async fn summary(
|
||||
State(history): State<History>,
|
||||
headers: HeaderMap,
|
||||
Query(query): Query<HistorySummaryQuery>,
|
||||
) -> Result<Json<Value>> {
|
||||
if !crate::maps::local_request(&headers) {
|
||||
return Err(crate::error::AppError::Validation("仅允许本机访问".into()));
|
||||
}
|
||||
let (total, since): (i64, i64) = sqlx::query_as(
|
||||
"SELECT COUNT(*), COUNT(CASE WHEN received_at_ms>=? THEN 1 END) FROM track_points",
|
||||
)
|
||||
.bind(sql_time(query.from_ms)?)
|
||||
.fetch_one(&history.pool)
|
||||
.await?;
|
||||
let rows = sqlx::query("SELECT target_id,received_at_ms,latitude,longitude FROM track_points ORDER BY received_at_ms DESC,id DESC LIMIT 6")
|
||||
.fetch_all(&history.pool).await?;
|
||||
let recent = rows.into_iter().map(|row| -> Result<Value> {
|
||||
Ok(json!({"targetId":row.try_get::<String,_>(0)?,"timeMs":row.try_get::<i64,_>(1)?,"latitude":row.try_get::<f64,_>(2)?,"longitude":row.try_get::<f64,_>(3)?}))
|
||||
}).collect::<Result<Vec<_>>>()?;
|
||||
Ok(Json(json!({"total":total,"since":since,"recent":recent})))
|
||||
}
|
||||
|
||||
async fn targets(
|
||||
State(history): State<History>,
|
||||
headers: HeaderMap,
|
||||
@@ -372,6 +566,20 @@ async fn points(
|
||||
}
|
||||
}
|
||||
|
||||
async fn flight_points(
|
||||
State(history): State<History>,
|
||||
headers: HeaderMap,
|
||||
Query(query): Query<FlightPointQuery>,
|
||||
) -> Response {
|
||||
if !crate::maps::local_request(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
match history.flight_points(&query).await {
|
||||
Ok(value) => Json(value).into_response(),
|
||||
Err(error) => error.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -388,6 +596,241 @@ mod tests {
|
||||
telemetry: None,
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn continuous_receive_updates_one_record_without_thinning_track_points() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let history = History::open(dir.path(), &SqliteConfig::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let frame = |sequence, receiver| {
|
||||
let mut observation = sample("TRACK-A", receiver, Some([118.0, 32.0]));
|
||||
observation.sequence = sequence;
|
||||
observation.telemetry = Some(rid_shared::DeviceTelemetry {
|
||||
rssi: Some(-60.0 - sequence as f64 / 100.0),
|
||||
..Default::default()
|
||||
});
|
||||
observation
|
||||
};
|
||||
async fn records(history: &History) -> Vec<(i64, i64)> {
|
||||
sqlx::query_as::<_, (i64, i64)>(
|
||||
"SELECT time_ms,last_seen_ms FROM rid_observations ORDER BY id",
|
||||
)
|
||||
.fetch_all(&history.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
let start = 10_000;
|
||||
for i in 0..300 {
|
||||
let now = start + i * 200;
|
||||
history
|
||||
.record_at(&[(frame(i, "RX1"), now)], now, false)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let latest = start + 299 * 200;
|
||||
assert_eq!(records(&history).await.len(), 1);
|
||||
assert_eq!(records(&history).await[0].1, 65_000);
|
||||
history.record_at(&[], latest, true).await.unwrap();
|
||||
let saved = records(&history).await;
|
||||
assert_eq!((saved[0].0, saved[0].1), (start as i64, latest as i64));
|
||||
let points: i64 = sqlx::query_scalar("SELECT count(*) FROM track_points")
|
||||
.fetch_one(&history.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(points, 61);
|
||||
history.close().await;
|
||||
|
||||
let history = History::open(dir.path(), &SqliteConfig::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let resumed = latest + 29_999;
|
||||
history
|
||||
.record_at(&[(frame(300, "RX1"), resumed)], resumed, false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(records(&history).await.len(), 1);
|
||||
assert_eq!(records(&history).await[0].1, resumed as i64);
|
||||
let after_gap = resumed + 30_000;
|
||||
history
|
||||
.record_at(
|
||||
&[(frame(301, "RX1"), after_gap), (frame(1, "RX2"), after_gap)],
|
||||
after_gap,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let saved = records(&history).await;
|
||||
assert_eq!(saved.len(), 2);
|
||||
assert_eq!(saved[1].0, after_gap as i64);
|
||||
history.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flight_uses_actual_reception_lifetime_and_keeps_osd_with_its_points() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let history = History::open(dir.path(), &SqliteConfig::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut first = sample("TARGET", "RX1", Some([118.0, 32.0]));
|
||||
first.telemetry = Some(rid_shared::DeviceTelemetry {
|
||||
speed_mps: Some(0.0),
|
||||
rssi: Some(-65.0),
|
||||
pressure_altitude_m: Some(0.0),
|
||||
relative_height_m: Some(4.0),
|
||||
pilot_position: Some([118.01, 32.01]),
|
||||
..Default::default()
|
||||
});
|
||||
let mut handoff = sample("TARGET", "RX2", Some([118.001, 32.001]));
|
||||
handoff.telemetry = Some(rid_shared::DeviceTelemetry {
|
||||
speed_mps: Some(3.0),
|
||||
rssi: Some(-74.0),
|
||||
..Default::default()
|
||||
});
|
||||
let end = 2000;
|
||||
let next_start = end + GAP_MS;
|
||||
history
|
||||
.record_entries(
|
||||
[
|
||||
(&first, 1000, true),
|
||||
(&handoff, end, true),
|
||||
(&handoff, next_start - 1, false),
|
||||
(&first, next_start, true),
|
||||
]
|
||||
.into_iter(),
|
||||
next_start,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let records: Vec<(String, i64, i64)> = sqlx::query_as(
|
||||
"SELECT flight_key,time_ms,last_seen_ms FROM rid_observations ORDER BY time_ms",
|
||||
)
|
||||
.fetch_all(&history.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!((records[0].1, records[0].2), (1000, end as i64));
|
||||
assert_eq!(
|
||||
(records[1].1, records[1].2),
|
||||
(next_start as i64, next_start as i64)
|
||||
);
|
||||
let mut query = FlightPointQuery {
|
||||
flight_key: records[0].0.clone(),
|
||||
after: None,
|
||||
limit: None,
|
||||
};
|
||||
let prior = history.flight_points(&query).await.unwrap();
|
||||
assert_eq!(prior["entries"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(prior["entries"][0]["osd"]["speedMps"], 0.0);
|
||||
assert_eq!(prior["entries"][0]["osd"]["pressureAltitudeM"], 0.0);
|
||||
assert_eq!(prior["entries"][0]["osd"]["relativeHeightM"], 4.0);
|
||||
assert!(prior["entries"][0]["osd"]["heightAglM"].is_null());
|
||||
assert_eq!(
|
||||
prior["entries"][0]["osd"]["pilotPosition"],
|
||||
json!([118.01, 32.01])
|
||||
);
|
||||
assert_eq!(prior["entries"][1]["receiverId"], "RX2");
|
||||
assert_eq!(prior["entries"][1]["osd"]["rssi"], -74.0);
|
||||
query.flight_key.clone_from(&records[1].0);
|
||||
let following = history.flight_points(&query).await.unwrap();
|
||||
assert_eq!(following["entries"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(following["entries"][0]["timeMs"], next_start);
|
||||
history.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upgrades_legacy_observation_rows_and_queries_overlapping_sessions() {
|
||||
use axum::{body::Body, http::Request};
|
||||
use tower::ServiceExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("registry/data/track-history.sqlite");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.connect_with(
|
||||
SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::raw_sql(
|
||||
"CREATE TABLE rid_observations (
|
||||
id INTEGER PRIMARY KEY, time_ms INTEGER NOT NULL, receiver_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL, epoch BLOB NOT NULL, sequence BLOB NOT NULL, model TEXT,
|
||||
bssid TEXT, rssi REAL, altitude_m REAL, speed_mps REAL, latitude REAL, longitude REAL,
|
||||
UNIQUE(receiver_id,target_id,epoch,sequence)
|
||||
);
|
||||
CREATE INDEX rid_observations_time ON rid_observations(time_ms,id);
|
||||
CREATE TABLE track_points (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, target_id TEXT NOT NULL, receiver_id TEXT NOT NULL,
|
||||
received_at_ms INTEGER NOT NULL, longitude REAL NOT NULL, latitude REAL NOT NULL,
|
||||
altitude_m REAL, heading_deg REAL, segment_start INTEGER NOT NULL
|
||||
);
|
||||
INSERT INTO track_points (target_id,receiver_id,received_at_ms,longitude,latitude,segment_start)
|
||||
VALUES ('TRACK-A','RX',1100,118.0,32.0,1), ('TRACK-A','RX',32000,118.1,32.1,1);
|
||||
INSERT INTO rid_observations (time_ms,receiver_id,target_id,epoch,sequence,model,bssid,rssi,speed_mps)
|
||||
VALUES (1000,'RX','TRACK-A',x'0000000000000001',x'0000000000000000','Old Model','ABCDEF012345',-77,0);",
|
||||
).execute(&pool).await.unwrap();
|
||||
pool.close().await;
|
||||
|
||||
let history = History::open(dir.path(), &SqliteConfig::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let first = sample("TRACK-A", "RX", None);
|
||||
let mut latest = first.clone();
|
||||
latest.sequence = 2;
|
||||
history
|
||||
.record_at(&[(first, 2000), (latest, 3000)], 3000, true)
|
||||
.await
|
||||
.unwrap();
|
||||
let api = crate::observations::router(history.clone());
|
||||
let read = |range| {
|
||||
api.clone().oneshot(
|
||||
Request::builder()
|
||||
.uri(format!(
|
||||
"/api/workbench/observations?{range}&q=track&sessionsOnly=true"
|
||||
))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let read_json = |result: std::result::Result<Response, std::convert::Infallible>| async {
|
||||
let response = result.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = axum::body::to_bytes(response.into_body(), 8192)
|
||||
.await
|
||||
.unwrap();
|
||||
serde_json::from_slice::<Value>(&bytes).unwrap()
|
||||
};
|
||||
let all = read_json(read("fromMs=0&toMs=4000").await).await;
|
||||
assert_eq!(all["total"], 1);
|
||||
assert_eq!(all["entries"][0]["timeMs"], 1000);
|
||||
assert_eq!(all["entries"][0]["lastSeenMs"], 3000);
|
||||
assert_eq!(all["entries"][0]["endMs"], 3000);
|
||||
assert_eq!(all["entries"][0]["rssi"], -77.0);
|
||||
assert_eq!(all["entries"][0]["speedMps"], 0.0);
|
||||
assert_eq!(all["entries"][0]["latitude"], 32.0);
|
||||
assert_eq!(all["entries"][0]["longitude"], 118.0);
|
||||
assert_eq!(all["entries"][0]["altitudeM"], Value::Null);
|
||||
let overlap = read_json(read("fromMs=2500&toMs=2600").await).await;
|
||||
assert_eq!(overlap["total"], 1);
|
||||
assert_eq!(overlap["entries"][0]["timeMs"], 1000);
|
||||
assert_eq!(overlap["entries"][0]["lastSeenMs"], 3000);
|
||||
let playback = history
|
||||
.flight_points(&FlightPointQuery {
|
||||
flight_key: overlap["entries"][0]["flightKey"].as_str().unwrap().into(),
|
||||
after: None,
|
||||
limit: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(playback["entries"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(playback["entries"][0]["timeMs"], 1100);
|
||||
assert_eq!(playback["entries"][0]["osd"], Value::Null);
|
||||
history.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_sampled_segments_and_restores_after_restart() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -142,7 +142,18 @@ async fn static_or_missing(req: Request) -> Response {
|
||||
if req.method() == Method::GET
|
||||
&& let Some((bytes, mime)) = crate::web_assets::resource(req.uri().path())
|
||||
{
|
||||
return binary(bytes.to_vec(), mime, None, None);
|
||||
let csp = match req.uri().path() {
|
||||
"/workbench/module.html" => Some(
|
||||
"default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'self'; object-src 'none'",
|
||||
),
|
||||
"/workbench" | "/workbench/" | "/workbench/login.html" | "/workbench/platform.html" => {
|
||||
Some(
|
||||
"default-src 'self'; img-src 'self' data: blob:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' ws://127.0.0.1:8787 ws://localhost:8787; frame-src 'self'; form-action 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
return binary(bytes.to_vec(), mime, None, csp);
|
||||
}
|
||||
missing().await
|
||||
}
|
||||
|
||||
@@ -2,9 +2,20 @@ use super::*;
|
||||
|
||||
pub(super) fn router() -> Router<Services> {
|
||||
Router::new()
|
||||
.route("/api/flight-plans", get(plans))
|
||||
.route("/api/flight-plans/{id}/approval", put(review_plan))
|
||||
.route("/api/flight-plans/{id}", put(save_plan).delete(remove_plan))
|
||||
.route("/api/geofences", get(fences))
|
||||
.route("/api/geofences/{id}", put(save_fence).delete(remove_fence))
|
||||
.route("/api/monitoring/events", get(events))
|
||||
.route("/api/monitoring/center", get(center))
|
||||
.route("/api/monitoring/events/{id}/dismissal", put(dismiss))
|
||||
.route("/api/monitoring/summary", get(summary))
|
||||
.route("/api/monitoring/rankings", get(rankings))
|
||||
.route(
|
||||
"/api/monitoring/events/{id}/acknowledgement",
|
||||
put(acknowledge),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fences(State(s): State<Services>) -> Result<Json<rid_shared::geofences::Snapshot>> {
|
||||
@@ -35,3 +46,90 @@ async fn events(
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(s.events(&p.0).await?))
|
||||
}
|
||||
|
||||
async fn center(
|
||||
State(s): State<Services>,
|
||||
Extension(p): Extension<Parameters>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(s.center_events(&p.0, &actor.0).await?))
|
||||
}
|
||||
|
||||
async fn dismiss(
|
||||
State(s): State<Services>,
|
||||
Path(id): Path<i64>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
) -> Result<Json<Value>> {
|
||||
s.dismiss_event(id, &actor.0).await?;
|
||||
Ok(Json(json!({"ok":true})))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SummaryQuery {
|
||||
from_ms: i64,
|
||||
}
|
||||
|
||||
async fn summary(
|
||||
State(s): State<Services>,
|
||||
axum::extract::Query(query): axum::extract::Query<SummaryQuery>,
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(s.event_counts(query.from_ms).await?))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RankingQuery {
|
||||
from_ms: i64,
|
||||
to_ms: i64,
|
||||
}
|
||||
|
||||
async fn rankings(
|
||||
State(s): State<Services>,
|
||||
axum::extract::Query(query): axum::extract::Query<RankingQuery>,
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(s.event_rankings(query.from_ms, query.to_ms).await?))
|
||||
}
|
||||
|
||||
async fn acknowledge(
|
||||
State(s): State<Services>,
|
||||
Path(id): Path<i64>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
) -> Result<Json<Value>> {
|
||||
s.acknowledge_event(id, &actor.0).await?;
|
||||
Ok(Json(json!({"ok":true})))
|
||||
}
|
||||
|
||||
async fn plans(State(s): State<Services>) -> Result<Json<Value>> {
|
||||
Ok(Json(json!({"entries":s.flight_plans().await?})))
|
||||
}
|
||||
async fn save_plan(
|
||||
State(s): State<Services>,
|
||||
Path(id): Path<String>,
|
||||
Extension(Payload(body)): Extension<Payload>,
|
||||
) -> Result<Json<crate::flight_plans::Plan>> {
|
||||
Ok(Json(
|
||||
s.save_flight_plan(&id, decode(body, "报备参数无效")?)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
async fn remove_plan(
|
||||
State(s): State<Services>,
|
||||
Path(id): Path<String>,
|
||||
Extension(p): Extension<Parameters>,
|
||||
) -> Result<Json<Value>> {
|
||||
s.remove_flight_plan(&id, revision(&p, "请提供报备版本")?)
|
||||
.await?;
|
||||
Ok(Json(json!({"ok":true})))
|
||||
}
|
||||
|
||||
async fn review_plan(
|
||||
State(s): State<Services>,
|
||||
Path(id): Path<String>,
|
||||
Extension(Payload(body)): Extension<Payload>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
) -> Result<Json<crate::flight_plans::Plan>> {
|
||||
Ok(Json(
|
||||
s.review_flight_plan(&id, decode(body, "审批参数无效")?, &actor.0)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -5,6 +5,28 @@ pub(super) fn router() -> Router<Services> {
|
||||
.route("/api/target-lists", get(lists))
|
||||
.route("/api/target-lists/{id}", put(save_list).delete(remove_list))
|
||||
.route("/api/target-bindings/{id}", get(binding).put(save_binding))
|
||||
.route("/api/target-registration-status", get(registration_status))
|
||||
}
|
||||
|
||||
async fn registration_status(
|
||||
State(s): State<Services>,
|
||||
Extension(p): Extension<Parameters>,
|
||||
) -> Result<Json<Value>> {
|
||||
let ids: Vec<_> =
|
||||
p.0.get("ids")
|
||||
.map_or("", String::as_str)
|
||||
.split(',')
|
||||
.collect();
|
||||
if ids.len() > 96
|
||||
|| !ids
|
||||
.iter()
|
||||
.all(|id| rid_shared::target_lists::valid_target_id(id))
|
||||
{
|
||||
return Err("目标标识无效或数量超过 96 个".into());
|
||||
}
|
||||
Ok(Json(
|
||||
json!({"entries":s.registration_statuses(&ids).await?}),
|
||||
))
|
||||
}
|
||||
|
||||
async fn lists(State(s): State<Services>, Extension(p): Extension<Parameters>) -> Result<Response> {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! Open the local UI only after the HTTP service responds successfully.
|
||||
|
||||
use std::time::Duration;
|
||||
const START_PAGE: &str = "/workbench/";
|
||||
|
||||
pub(crate) async fn open_existing(port: u16) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
let url = format!("http://127.0.0.1:{port}{START_PAGE}");
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.timeout(Duration::from_secs(2))
|
||||
.build()?;
|
||||
let Some((expected, _)) = crate::web_assets::resource("/") else {
|
||||
let Some((expected, _)) = crate::web_assets::resource(START_PAGE) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Ok(response) = client.get(&url).send().await else {
|
||||
@@ -30,7 +31,7 @@ pub(crate) async fn open_existing(port: u16) -> Result<bool, Box<dyn std::error:
|
||||
}
|
||||
|
||||
pub(crate) async fn open_when_ready(port: u16) {
|
||||
let url = format!("http://127.0.0.1:{port}/");
|
||||
let url = format!("http://127.0.0.1:{port}{START_PAGE}");
|
||||
let result = async {
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
@@ -55,7 +56,7 @@ pub(crate) async fn open_when_ready(port: u16) {
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
eprintln!("无法自动打开浏览器:{error}。请手动访问 http://127.0.0.1:{port}/");
|
||||
eprintln!("无法自动打开浏览器:{error}。请手动访问 http://127.0.0.1:{port}{START_PAGE}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#![cfg_attr(all(windows, feature = "portable"), windows_subsystem = "windows")]
|
||||
|
||||
mod app;
|
||||
mod appearance;
|
||||
mod archive;
|
||||
mod auth;
|
||||
mod config;
|
||||
mod database;
|
||||
mod error;
|
||||
mod flight_plans;
|
||||
mod geofences;
|
||||
mod history;
|
||||
mod http;
|
||||
@@ -12,12 +16,16 @@ mod lifecycle;
|
||||
mod map_settings;
|
||||
mod maps;
|
||||
mod monitoring;
|
||||
mod observations;
|
||||
#[cfg(all(windows, feature = "portable"))]
|
||||
mod portable_console;
|
||||
mod realtime;
|
||||
mod receiver;
|
||||
mod services;
|
||||
mod store;
|
||||
mod target_bindings;
|
||||
mod target_lists;
|
||||
mod workbench;
|
||||
mod web_assets {
|
||||
include!(concat!(env!("OUT_DIR"), "/web_assets.rs"));
|
||||
}
|
||||
@@ -26,5 +34,33 @@ mod tests;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
app::run().await
|
||||
let args = std::env::args().skip(1);
|
||||
#[cfg(all(windows, feature = "portable"))]
|
||||
let mut args = args.peekable();
|
||||
#[cfg(all(windows, feature = "portable"))]
|
||||
let console = if args.peek().is_none() {
|
||||
return portable_console::launch().map_err(|error| {
|
||||
portable_console::show_error(&error.to_string());
|
||||
error.into()
|
||||
});
|
||||
} else if args.peek().is_some_and(|arg| arg == "--rid-console") {
|
||||
args.next();
|
||||
Some(portable_console::attach_window().map_err(|error| {
|
||||
portable_console::show_error(&error.to_string());
|
||||
error
|
||||
})?)
|
||||
} else {
|
||||
portable_console::attach_parent();
|
||||
None
|
||||
};
|
||||
|
||||
let outcome = app::run(args).await;
|
||||
#[cfg(all(windows, feature = "portable"))]
|
||||
if let Err(error) = &outcome
|
||||
&& console.is_some()
|
||||
{
|
||||
eprintln!("RID 启动失败:{error}\n\n按 Enter 关闭此窗口。");
|
||||
let _ = std::io::stdin().read_line(&mut String::new());
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ struct Job {
|
||||
}
|
||||
struct Manager {
|
||||
root: PathBuf,
|
||||
offline_directory: PathBuf,
|
||||
preferences: Mutex<Result<Preferences, String>>,
|
||||
job: Mutex<Option<Job>>,
|
||||
cancel: AtomicBool,
|
||||
@@ -39,6 +40,10 @@ struct Manager {
|
||||
port: u16,
|
||||
}
|
||||
|
||||
#[cfg(feature = "portable")]
|
||||
const EMBEDDED_DOWNLOADER: &[u8] =
|
||||
include_bytes!(concat!(env!("OUT_DIR"), "/rid-map-downloader.bin"));
|
||||
|
||||
fn executable() -> Option<PathBuf> {
|
||||
resolve_executable(
|
||||
std::env::var_os("RID_MAP_DOWNLOADER").map(PathBuf::from),
|
||||
@@ -54,12 +59,14 @@ fn resolve_executable(
|
||||
adjacent.is_file().then_some(adjacent)
|
||||
})
|
||||
}
|
||||
pub(crate) fn prepare_offline_directory(root: &Path) -> std::io::Result<PathBuf> {
|
||||
let offline = root.join("offline");
|
||||
if !crate::maps::allowed(root, &offline) {
|
||||
fn prepare_offline_directory(offline: &Path) -> std::io::Result<PathBuf> {
|
||||
if !offline
|
||||
.parent()
|
||||
.is_some_and(|root| crate::maps::allowed(root, offline))
|
||||
{
|
||||
return Err(std::io::Error::other("地图下载目录无效"));
|
||||
}
|
||||
std::fs::create_dir_all(&offline)?;
|
||||
std::fs::create_dir_all(offline)?;
|
||||
std::fs::canonicalize(offline)
|
||||
}
|
||||
fn read_preferences(root: &Path) -> Result<Preferences, String> {
|
||||
@@ -109,11 +116,12 @@ impl Shutdown {
|
||||
self.0.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
pub fn router(root: PathBuf, port: u16) -> (Router, Shutdown) {
|
||||
let root = root.join("maps");
|
||||
pub fn router(data_root: PathBuf, offline_directory: PathBuf, port: u16) -> (Router, Shutdown) {
|
||||
let root = data_root.join("maps");
|
||||
let manager = Arc::new(Manager {
|
||||
preferences: Mutex::new(read_preferences(&root)),
|
||||
root,
|
||||
offline_directory,
|
||||
job: Mutex::new(None),
|
||||
cancel: AtomicBool::new(false),
|
||||
stopping: AtomicBool::new(false),
|
||||
@@ -204,7 +212,10 @@ async fn status(State(s): State<Arc<Manager>>, headers: HeaderMap) -> Response {
|
||||
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||
}
|
||||
match s.job.lock() {
|
||||
Ok(job) => Json(json!({"available":s.executable.is_some(),"job":*job})).into_response(),
|
||||
Ok(job) => Json(
|
||||
json!({"available":cfg!(feature = "portable") || s.executable.is_some(),"job":*job}),
|
||||
)
|
||||
.into_response(),
|
||||
Err(_) => error(StatusCode::INTERNAL_SERVER_ERROR, "下载状态暂不可用"),
|
||||
}
|
||||
}
|
||||
@@ -237,12 +248,12 @@ async fn start(
|
||||
Ok(n) => n,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
let Some(executable) = s.executable.clone() else {
|
||||
if !cfg!(feature = "portable") && s.executable.is_none() {
|
||||
return error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Go 地图下载器未安装,请运行 scripts/build-map-downloader.ps1 或使用完整发布包",
|
||||
);
|
||||
};
|
||||
}
|
||||
{
|
||||
let Ok(mut job) = s.job.lock() else {
|
||||
return error(StatusCode::INTERNAL_SERVER_ERROR, "下载状态暂不可用");
|
||||
@@ -265,14 +276,24 @@ async fn start(
|
||||
message: "正在准备下载".into(),
|
||||
});
|
||||
}
|
||||
tokio::task::spawn_blocking(move || run(s, executable, request));
|
||||
tokio::task::spawn_blocking(move || run(s, request));
|
||||
(StatusCode::ACCEPTED, Json(json!({"total":total}))).into_response()
|
||||
}
|
||||
fn run(s: Arc<Manager>, executable: PathBuf, request: DownloadRequest) {
|
||||
fn run(s: Arc<Manager>, request: DownloadRequest) {
|
||||
let outcome = (|| -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let offline = prepare_offline_directory(&s.root)?;
|
||||
let offline = prepare_offline_directory(&s.offline_directory)?;
|
||||
let payload = json!({"bounds":request.bounds,"minZoom":request.min_zoom,"maxZoom":request.max_zoom,
|
||||
"layers":request.layers(),"output":offline,"baseUrl":format!("http://127.0.0.1:{}/api/maps/tile",s.port)});
|
||||
#[cfg(feature = "portable")]
|
||||
let embedded_directory = tempfile::Builder::new().prefix("rid-map-").tempdir()?;
|
||||
#[cfg(feature = "portable")]
|
||||
let executable = {
|
||||
let path = embedded_directory.path().join("rid-map-downloader.exe");
|
||||
std::fs::write(&path, EMBEDDED_DOWNLOADER)?;
|
||||
path
|
||||
};
|
||||
#[cfg(not(feature = "portable"))]
|
||||
let executable = s.executable.as_ref().ok_or("地图下载器不可用")?;
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
.stdin(Stdio::piped())
|
||||
@@ -336,7 +357,13 @@ fn run(s: Arc<Manager>, executable: PathBuf, request: DownloadRequest) {
|
||||
j.message = "已取消,完成的瓦片已保留;重新下载可跳过已有瓦片".into();
|
||||
} else if outcome.is_ok_and(|ok| ok) && j.done == j.total && j.failed == 0 {
|
||||
j.state = "completed".into();
|
||||
j.message = "离线地图准备完成,所有瓦片已通过图像校验".into();
|
||||
j.message = format!(
|
||||
"离线地图下载完成,已保存到 {} 文件夹",
|
||||
s.offline_directory
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
);
|
||||
} else {
|
||||
j.state = "failed".into();
|
||||
j.message = format!(
|
||||
@@ -358,22 +385,24 @@ mod tests {
|
||||
#[test]
|
||||
fn offline_directory_is_created_and_existing_tiles_are_preserved() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("新建地图目录/maps");
|
||||
let root = temp.path().join("新建地图目录");
|
||||
assert!(!root.exists());
|
||||
let offline = prepare_offline_directory(&root).unwrap();
|
||||
let directory = root.join("map_cache");
|
||||
let offline = prepare_offline_directory(&directory).unwrap();
|
||||
assert!(offline.is_absolute());
|
||||
assert!(offline.is_dir());
|
||||
assert_eq!(offline.file_name().unwrap(), "map_cache");
|
||||
let tile = offline.join("existing.png");
|
||||
std::fs::write(&tile, b"existing tile").unwrap();
|
||||
assert_eq!(prepare_offline_directory(&root).unwrap(), offline);
|
||||
assert_eq!(prepare_offline_directory(&directory).unwrap(), offline);
|
||||
assert_eq!(std::fs::read(tile).unwrap(), b"existing tile");
|
||||
}
|
||||
#[test]
|
||||
fn offline_directory_does_not_replace_a_conflicting_file() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let offline = temp.path().join("offline");
|
||||
let offline = temp.path().join("map_cache");
|
||||
std::fs::write(&offline, b"keep this file").unwrap();
|
||||
assert!(prepare_offline_directory(temp.path()).is_err());
|
||||
assert!(prepare_offline_directory(&offline).is_err());
|
||||
assert_eq!(std::fs::read(offline).unwrap(), b"keep this file");
|
||||
}
|
||||
#[test]
|
||||
@@ -402,6 +431,7 @@ mod tests {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let s = Arc::new(Manager {
|
||||
root: temp.path().into(),
|
||||
offline_directory: temp.path().join("map_cache"),
|
||||
preferences: Mutex::new(Ok(Preferences::default())),
|
||||
job: Mutex::new(None),
|
||||
cancel: AtomicBool::new(false),
|
||||
@@ -430,7 +460,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn preferences_persist_conflict_and_reject_cross_origin() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (app, _shutdown) = router(temp.path().into(), 8787);
|
||||
let (app, _shutdown) = router(temp.path().into(), temp.path().join("map_cache"), 8787);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
|
||||
@@ -22,10 +22,12 @@ const MAX_TILE_BYTES: usize = 2 * 1024 * 1024;
|
||||
const TILE_SIZE: u32 = 256;
|
||||
const MAX_PARENT_LEVELS: u8 = 3;
|
||||
const LAYERS: &[&str] = &["vec_w", "cva_w", "img_w", "cia_w"];
|
||||
pub(crate) const OFFLINE_DIRECTORY: &str = "map_cache";
|
||||
const DEFAULT_TIANDITU_TOKEN: &str = "759bdda106dd9375168ad8b79bfbf02a";
|
||||
#[derive(Clone)]
|
||||
struct Maps {
|
||||
root: PathBuf,
|
||||
offline_roots: Arc<[PathBuf]>,
|
||||
extra_offline: Option<PathBuf>,
|
||||
upstream: String,
|
||||
key: Option<String>,
|
||||
@@ -134,6 +136,7 @@ impl Maps {
|
||||
}
|
||||
pub fn router(
|
||||
root: PathBuf,
|
||||
executable_tiles: PathBuf,
|
||||
configured: Option<String>,
|
||||
extra_offline: Option<PathBuf>,
|
||||
) -> Result<Router, reqwest::Error> {
|
||||
@@ -147,8 +150,15 @@ pub fn router(
|
||||
.timeout(Duration::from_secs(5))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()?;
|
||||
let data_tiles = root.join(OFFLINE_DIRECTORY);
|
||||
let mut offline_roots = vec![data_tiles.clone()];
|
||||
if executable_tiles != data_tiles {
|
||||
offline_roots.push(executable_tiles);
|
||||
}
|
||||
offline_roots.push(root.join("maps/offline"));
|
||||
let maps = Maps {
|
||||
root: root.join("maps"),
|
||||
offline_roots: offline_roots.into(),
|
||||
extra_offline,
|
||||
upstream: "https://t0.tianditu.gov.cn".into(),
|
||||
key,
|
||||
@@ -189,7 +199,7 @@ async fn status(State(maps): State<Maps>, headers: HeaderMap) -> Response {
|
||||
let layers = maps.layers.lock().map(|v| v.clone()).unwrap_or_default();
|
||||
let retry = layers.values().map(|s| s.retry_after_ms).max().unwrap_or(0);
|
||||
let response = axum::Json(
|
||||
json!({"provider":"tianditu","configError":maps.config_error,"layers":layers,"keyConfigured":maps.key.is_some(),"mode":if maps.key.is_none()||retry>crate::realtime::now_ms(){"offline"}else{"online-preferred"},"retryAfterMs":retry,"servedOnline":maps.online.load(Ordering::Relaxed),"servedOffline":maps.offline.load(Ordering::Relaxed),"missingTiles":maps.missing.load(Ordering::Relaxed),"cacheLimitBytes":maps.cache_limit,"extraOfflineConfigured":maps.extra_offline.is_some(),"extraOfflineAvailable":maps.extra_offline.as_ref().is_some_and(|root| root.is_dir() && !root.is_symlink()),"offlineLayout":"maps/offline/{layer}/{z}/{x}/{y}.png or maps/offline/{layer}.mbtiles"}),
|
||||
json!({"provider":"tianditu","configError":maps.config_error,"layers":layers,"keyConfigured":maps.key.is_some(),"mode":if maps.key.is_none()||retry>crate::realtime::now_ms(){"offline"}else{"online-preferred"},"retryAfterMs":retry,"servedOnline":maps.online.load(Ordering::Relaxed),"servedOffline":maps.offline.load(Ordering::Relaxed),"missingTiles":maps.missing.load(Ordering::Relaxed),"cacheLimitBytes":maps.cache_limit,"extraOfflineConfigured":maps.extra_offline.is_some(),"extraOfflineAvailable":maps.extra_offline.as_ref().is_some_and(|root| root.is_dir() && !root.is_symlink()),"offlineLayout":"map_cache/{layer}/{z}/{x}/{y}.png or map_cache/{layer}.mbtiles"}),
|
||||
);
|
||||
let mut response = response.into_response();
|
||||
response
|
||||
@@ -266,11 +276,7 @@ fn offline_xyz(root: &FsPath, layer: &str, z: u8, x: u32, y: u32) -> Option<Vec<
|
||||
}
|
||||
|
||||
async fn offline(maps: &Maps, layer: &str, z: u8, x: u32, y: u32) -> Option<Vec<u8>> {
|
||||
let mut roots = vec![maps.root.join("offline")];
|
||||
if let Some(extra) = &maps.extra_offline {
|
||||
roots.push(extra.clone());
|
||||
}
|
||||
for root in roots {
|
||||
for root in maps.offline_roots.iter().chain(maps.extra_offline.as_ref()) {
|
||||
let xyz_root = root.clone();
|
||||
let layer_copy = layer.to_owned();
|
||||
if let Some(bytes) =
|
||||
@@ -281,7 +287,7 @@ async fn offline(maps: &Maps, layer: &str, z: u8, x: u32, y: u32) -> Option<Vec<
|
||||
{
|
||||
return Some(bytes);
|
||||
}
|
||||
if let Some(bytes) = offline_mbtiles(maps, &root, layer, z, x, y).await {
|
||||
if let Some(bytes) = offline_mbtiles(maps, root, layer, z, x, y).await {
|
||||
return Some(bytes);
|
||||
}
|
||||
}
|
||||
@@ -656,6 +662,7 @@ mod tests {
|
||||
use super::*;
|
||||
fn state(root: PathBuf) -> Maps {
|
||||
Maps {
|
||||
offline_roots: [root.join("offline")].into(),
|
||||
root,
|
||||
extra_offline: None,
|
||||
upstream: "https://t0.tianditu.gov.cn".into(),
|
||||
@@ -701,6 +708,45 @@ mod tests {
|
||||
assert!(offline_path.is_file());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_map_cache_beside_executable_even_with_separate_data_root() {
|
||||
use axum::{body::Body, http::Request};
|
||||
use tower::ServiceExt;
|
||||
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let executable = tempfile::tempdir().unwrap();
|
||||
let png = b"\x89PNG\r\n\x1a\nportable";
|
||||
let tile_path = "img_w/2/1/2.png";
|
||||
let adjacent = executable.path().join(OFFLINE_DIRECTORY).join(tile_path);
|
||||
std::fs::create_dir_all(adjacent.parent().unwrap()).unwrap();
|
||||
std::fs::write(&adjacent, png).unwrap();
|
||||
let response = router(
|
||||
data.path().into(),
|
||||
executable.path().join(OFFLINE_DIRECTORY),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/maps/tile/img_w/2/1/2")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["x-map-source"], "offline");
|
||||
assert_eq!(
|
||||
axum::body::to_bytes(response.into_body(), MAX_TILE_BYTES)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_ref(),
|
||||
png
|
||||
);
|
||||
assert!(!data.path().join(OFFLINE_DIRECTORY).exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_offline_tiles_are_used_before_network_without_changing_data_root() {
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -48,6 +48,7 @@ pub fn start(
|
||||
let mut engine = None;
|
||||
struct Pending {
|
||||
observations: ObservationBatch,
|
||||
alert_observations: Vec<(rid_shared::Observation, u64)>,
|
||||
active: Vec<rid_shared::Target>,
|
||||
now: u64,
|
||||
alerts_done: bool,
|
||||
@@ -78,8 +79,13 @@ pub fn start(
|
||||
while let Ok(batch) = rx.try_recv() {
|
||||
observations.extend(batch);
|
||||
}
|
||||
let alert_observations = observations
|
||||
.iter()
|
||||
.map(|(observation, time, _)| (observation.clone(), *time))
|
||||
.collect();
|
||||
pending = Some(Pending {
|
||||
observations,
|
||||
alert_observations,
|
||||
active: store.frame(None, now).targets,
|
||||
now,
|
||||
alerts_done: false,
|
||||
@@ -94,17 +100,26 @@ pub fn start(
|
||||
match services
|
||||
.monitor(
|
||||
engine.clone(),
|
||||
&batch.observations,
|
||||
&batch.alert_observations,
|
||||
&batch.active,
|
||||
batch.now,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(next) => {
|
||||
engine = Some(next);
|
||||
if let Some(batch) = pending.as_mut() {
|
||||
for ((o, _, _), assessment) in batch
|
||||
.observations
|
||||
.iter_mut()
|
||||
.zip(next.observation_assessments())
|
||||
{
|
||||
o.telemetry
|
||||
.get_or_insert_with(Default::default)
|
||||
.flight_status = Some(assessment.class.clone());
|
||||
}
|
||||
batch.alerts_done = true;
|
||||
}
|
||||
engine = Some(next);
|
||||
}
|
||||
Err(error) => {
|
||||
if stop.is_cancelled() {
|
||||
@@ -120,7 +135,7 @@ pub fn start(
|
||||
let Some(batch) = pending.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
match history.record(&batch.observations).await {
|
||||
match history.record_monitored(&batch.observations).await {
|
||||
Ok(()) => {
|
||||
pending = None;
|
||||
if let Ok(mut status) = state.error.lock() {
|
||||
@@ -380,6 +395,33 @@ mod tests {
|
||||
let points = value["entries"].as_array().unwrap();
|
||||
assert_eq!(points.len(), 2);
|
||||
assert_eq!(points[1]["longitude"], 118.1);
|
||||
let saved: String = sqlx::query_scalar(
|
||||
"SELECT flight_statuses FROM rid_observations WHERE target_id='TEST'",
|
||||
)
|
||||
.fetch_one(&history.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let classifications: Vec<String> = serde_json::from_str(&saved).unwrap();
|
||||
assert_eq!(classifications, vec!["unregistered"]);
|
||||
// Later registration/list changes cannot rewrite the historical assessment.
|
||||
services
|
||||
.save_list(
|
||||
"TEST",
|
||||
rid_shared::target_lists::Mutation {
|
||||
list_kind: rid_shared::target_lists::ListKind::White,
|
||||
note: String::new(),
|
||||
expected_revision: 0,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let after: String = sqlx::query_scalar(
|
||||
"SELECT flight_statuses FROM rid_observations WHERE target_id='TEST'",
|
||||
)
|
||||
.fetch_one(&history.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(saved, after);
|
||||
history.close().await;
|
||||
services.close().await;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
//! Query and rank accepted receive records, including those without a verified position.
|
||||
use crate::{error::Result, history::History};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
routing::get,
|
||||
};
|
||||
use rid_shared::Observation;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{QueryBuilder, Row, SqlitePool, SqliteTransaction};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const GAP_MS: i64 = crate::realtime::TARGET_TTL_MS as i64;
|
||||
const WRITE_INTERVAL_MS: i64 = 5_000;
|
||||
const RETENTION_MS: i64 = 30 * 24 * 60 * 60 * 1000;
|
||||
const PRUNE_INTERVAL_MS: i64 = 60_000;
|
||||
|
||||
pub async fn prepare(pool: &SqlitePool) -> Result<()> {
|
||||
let mut tx = pool.begin().await?;
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS rid_observations(
|
||||
id INTEGER PRIMARY KEY,
|
||||
time_ms INTEGER NOT NULL,
|
||||
last_seen_ms INTEGER,
|
||||
receiver_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
epoch BLOB NOT NULL,
|
||||
sequence BLOB NOT NULL,
|
||||
model TEXT,
|
||||
bssid TEXT,
|
||||
rssi REAL,
|
||||
altitude_m REAL,
|
||||
speed_mps REAL,
|
||||
latitude REAL,
|
||||
longitude REAL,
|
||||
UNIQUE(receiver_id,target_id,epoch,sequence)
|
||||
)",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let has_last_seen: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('rid_observations') WHERE name='last_seen_ms')",
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !has_last_seen {
|
||||
sqlx::query("ALTER TABLE rid_observations ADD COLUMN last_seen_ms INTEGER")
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
let has_flight_key: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('rid_observations') WHERE name='flight_key')",
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !has_flight_key {
|
||||
sqlx::raw_sql(
|
||||
"ALTER TABLE rid_observations ADD COLUMN flight_key TEXT;
|
||||
ALTER TABLE track_points ADD COLUMN flight_key TEXT;
|
||||
ALTER TABLE track_points ADD COLUMN osd TEXT;",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
let has_status: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pragma_table_info('rid_observations') WHERE name='flight_statuses')").fetch_one(&mut *tx).await?;
|
||||
if !has_status {
|
||||
sqlx::query(
|
||||
"ALTER TABLE rid_observations ADD COLUMN flight_statuses TEXT NOT NULL DEFAULT '[]'",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
sqlx::raw_sql(
|
||||
"CREATE INDEX IF NOT EXISTS rid_observations_end ON rid_observations(COALESCE(last_seen_ms,time_ms),id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS rid_flight_key ON rid_observations(flight_key) WHERE flight_key IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS rid_flight_target ON rid_observations(target_id,time_ms,last_seen_ms)
|
||||
WHERE flight_key IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS rid_flight_points ON track_points(flight_key,id) WHERE flight_key IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS rid_legacy_target_time ON rid_observations(target_id,time_ms,id)
|
||||
WHERE flight_key IS NULL;
|
||||
DROP INDEX IF EXISTS rid_observations_time;
|
||||
DROP INDEX IF EXISTS rid_observations_session;",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !has_flight_key {
|
||||
// Infer earlier sessions from the time ranges and point times that exist on disk.
|
||||
sqlx::query(
|
||||
"WITH samples AS (
|
||||
SELECT target_id,receiver_id,time_ms AS start_ms,COALESCE(last_seen_ms,time_ms) AS end_ms,model,bssid
|
||||
FROM rid_observations
|
||||
UNION ALL
|
||||
SELECT target_id,receiver_id,received_at_ms,received_at_ms,NULL,NULL FROM track_points
|
||||
), previous AS (
|
||||
SELECT *,MAX(end_ms) OVER (PARTITION BY target_id ORDER BY start_ms,end_ms,receiver_id
|
||||
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS previous_end
|
||||
FROM samples
|
||||
), grouped AS (
|
||||
SELECT *,SUM(CASE WHEN previous_end IS NULL OR start_ms-previous_end>=? THEN 1 ELSE 0 END)
|
||||
OVER (PARTITION BY target_id ORDER BY start_ms,end_ms,receiver_id) AS episode
|
||||
FROM previous
|
||||
)
|
||||
INSERT INTO rid_observations (target_id,receiver_id,time_ms,last_seen_ms,epoch,sequence,model,bssid,flight_key)
|
||||
SELECT target_id,MAX(receiver_id),MIN(start_ms),MAX(end_ms),randomblob(8),zeroblob(8),MAX(model),MAX(bssid),lower(hex(randomblob(16)))
|
||||
FROM grouped GROUP BY target_id,episode",
|
||||
)
|
||||
.bind(GAP_MS)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE track_points AS point SET flight_key=(
|
||||
SELECT flight_key FROM rid_observations AS episode
|
||||
WHERE episode.flight_key IS NOT NULL AND episode.target_id=point.target_id
|
||||
AND episode.time_ms<=point.received_at_ms AND episode.last_seen_ms>=point.received_at_ms
|
||||
ORDER BY episode.time_ms DESC LIMIT 1
|
||||
)",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Recorder {
|
||||
active: HashMap<String, Session>,
|
||||
next_prune_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Session {
|
||||
id: i64,
|
||||
saved_ms: i64,
|
||||
seen_ms: i64,
|
||||
flight_key: String,
|
||||
pending: Option<RecordMetadata>,
|
||||
statuses: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RecordMetadata {
|
||||
receiver_id: String,
|
||||
model: Option<String>,
|
||||
bssid: Option<String>,
|
||||
rssi: Option<f64>,
|
||||
altitude_m: Option<f32>,
|
||||
speed_mps: Option<f64>,
|
||||
position: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl From<&Observation> for RecordMetadata {
|
||||
fn from(observation: &Observation) -> Self {
|
||||
let telemetry = observation.telemetry.as_ref();
|
||||
Self {
|
||||
receiver_id: observation.receiver_id.clone(),
|
||||
model: telemetry.and_then(|value| value.model.clone().or_else(|| value.name.clone())),
|
||||
bssid: telemetry.and_then(|value| value.mac.clone()),
|
||||
rssi: telemetry.and_then(|value| value.rssi),
|
||||
altitude_m: observation.altitude_m,
|
||||
speed_mps: telemetry.and_then(|value| value.speed_mps),
|
||||
position: observation
|
||||
.coordinates()
|
||||
.filter(|_| !telemetry.is_some_and(|value| value.position_unverified)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
pub fn needs_flush(&self, now: i64, force: bool) -> bool {
|
||||
self.active.values().any(|session| {
|
||||
(session.pending.is_some()
|
||||
&& (force || now.saturating_sub(session.saved_ms) >= WRITE_INTERVAL_MS))
|
||||
|| now.saturating_sub(session.seen_ms) >= GAP_MS
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn record(
|
||||
&mut self,
|
||||
tx: &mut SqliteTransaction<'_>,
|
||||
observation: &Observation,
|
||||
now: i64,
|
||||
) -> Result<String> {
|
||||
let target = &observation.target_id;
|
||||
if !self.active.contains_key(target)
|
||||
&& let Some((id, seen_ms, flight_key, statuses)) =
|
||||
sqlx::query_as::<_, (i64, i64, String, String)>(
|
||||
"SELECT id,last_seen_ms,flight_key,flight_statuses FROM rid_observations
|
||||
WHERE target_id=? AND flight_key IS NOT NULL AND last_seen_ms>? AND last_seen_ms<=?
|
||||
ORDER BY time_ms DESC,id DESC LIMIT 1",
|
||||
)
|
||||
.bind(target)
|
||||
.bind(now.saturating_sub(GAP_MS))
|
||||
.bind(now)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
{
|
||||
self.active.insert(
|
||||
target.clone(),
|
||||
Session {
|
||||
id,
|
||||
seen_ms,
|
||||
saved_ms: seen_ms,
|
||||
flight_key,
|
||||
pending: None,
|
||||
statuses: serde_json::from_str(&statuses).unwrap_or_default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(session) = self.active.get_mut(target) {
|
||||
if (0..GAP_MS).contains(&now.saturating_sub(session.seen_ms)) {
|
||||
session.seen_ms = now;
|
||||
session.pending = Some(RecordMetadata::from(observation));
|
||||
if let Some(status) = observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
.and_then(|t| t.flight_status.as_ref())
|
||||
{
|
||||
session.statuses.insert(status.clone());
|
||||
}
|
||||
return Ok(session.flight_key.clone());
|
||||
}
|
||||
session.flush(tx, now).await?;
|
||||
}
|
||||
|
||||
let flight_key = format!("{:032x}", rand::random::<u128>());
|
||||
let metadata = RecordMetadata::from(observation);
|
||||
let statuses: HashSet<String> = observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
.and_then(|t| t.flight_status.clone())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let status_json = serde_json::to_string(&statuses).map_err(|e| e.to_string())?;
|
||||
let id = sqlx::query_scalar(
|
||||
"INSERT INTO rid_observations(epoch,sequence,model,bssid,time_ms,last_seen_ms,receiver_id,target_id,flight_key,
|
||||
rssi,altitude_m,speed_mps,latitude,longitude,flight_statuses)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) RETURNING id",
|
||||
)
|
||||
.bind(rand::random::<u64>().to_be_bytes().to_vec())
|
||||
.bind(observation.sequence.to_be_bytes().to_vec())
|
||||
.bind(metadata.model)
|
||||
.bind(metadata.bssid)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.bind(metadata.receiver_id)
|
||||
.bind(target)
|
||||
.bind(&flight_key)
|
||||
.bind(metadata.rssi)
|
||||
.bind(metadata.altitude_m)
|
||||
.bind(metadata.speed_mps)
|
||||
.bind(metadata.position.map(|point| point[1]))
|
||||
.bind(metadata.position.map(|point| point[0]))
|
||||
.bind(status_json)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
self.active.insert(
|
||||
target.clone(),
|
||||
Session {
|
||||
id,
|
||||
saved_ms: now,
|
||||
seen_ms: now,
|
||||
flight_key: flight_key.clone(),
|
||||
pending: None,
|
||||
statuses,
|
||||
},
|
||||
);
|
||||
Ok(flight_key)
|
||||
}
|
||||
|
||||
pub async fn finish(
|
||||
&mut self,
|
||||
tx: &mut SqliteTransaction<'_>,
|
||||
now: i64,
|
||||
force: bool,
|
||||
) -> Result<()> {
|
||||
for session in self.active.values_mut() {
|
||||
if force
|
||||
|| now.saturating_sub(session.saved_ms) >= WRITE_INTERVAL_MS
|
||||
|| now.saturating_sub(session.seen_ms) >= GAP_MS
|
||||
{
|
||||
session.flush(tx, now).await?;
|
||||
}
|
||||
}
|
||||
self.active
|
||||
.retain(|_, session| now.saturating_sub(session.seen_ms) < GAP_MS);
|
||||
if self.next_prune_ms.is_none_or(|next| now >= next) {
|
||||
let expired = sqlx::query_scalar::<_, i64>(
|
||||
"DELETE FROM rid_observations WHERE COALESCE(last_seen_ms,time_ms) < ?
|
||||
AND NOT EXISTS (SELECT 1 FROM track_points WHERE flight_key=rid_observations.flight_key)
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(now.saturating_sub(RETENTION_MS))
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
let overflow = sqlx::query_scalar::<_, i64>(
|
||||
"DELETE FROM rid_observations WHERE id IN
|
||||
(SELECT id FROM rid_observations
|
||||
WHERE NOT EXISTS (SELECT 1 FROM track_points WHERE flight_key=rid_observations.flight_key)
|
||||
ORDER BY COALESCE(last_seen_ms,time_ms) DESC,id DESC
|
||||
LIMIT -1 OFFSET 300000) RETURNING id",
|
||||
)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
if !expired.is_empty() || !overflow.is_empty() {
|
||||
let removed: HashSet<_> = expired.into_iter().chain(overflow).collect();
|
||||
self.active
|
||||
.retain(|_, session| !removed.contains(&session.id));
|
||||
}
|
||||
self.next_prune_ms = Some(now.saturating_add(PRUNE_INTERVAL_MS));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
async fn flush(&mut self, tx: &mut SqliteTransaction<'_>, now: i64) -> Result<()> {
|
||||
let Some(metadata) = self.pending.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
sqlx::query(
|
||||
"UPDATE rid_observations SET model=?,bssid=?,last_seen_ms=?,receiver_id=?,
|
||||
rssi=?,altitude_m=?,speed_mps=?,latitude=?,longitude=?,flight_statuses=? WHERE id=?",
|
||||
)
|
||||
.bind(metadata.model)
|
||||
.bind(metadata.bssid)
|
||||
.bind(self.seen_ms)
|
||||
.bind(metadata.receiver_id)
|
||||
.bind(metadata.rssi)
|
||||
.bind(metadata.altitude_m)
|
||||
.bind(metadata.speed_mps)
|
||||
.bind(metadata.position.map(|point| point[1]))
|
||||
.bind(metadata.position.map(|point| point[0]))
|
||||
.bind(serde_json::to_string(&self.statuses).map_err(|e| e.to_string())?)
|
||||
.bind(self.id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
self.saved_ms = now;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Filter {
|
||||
from_ms: i64,
|
||||
to_ms: i64,
|
||||
#[serde(default)]
|
||||
q: String,
|
||||
#[serde(default)]
|
||||
offset: u32,
|
||||
limit: Option<u32>,
|
||||
dimension: Option<Dimension>,
|
||||
flight_keys: Option<String>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
fn validate(&self) -> Result<()> {
|
||||
if self.from_ms < 0
|
||||
|| self.from_ms > self.to_ms
|
||||
|| self.q.len() > 256
|
||||
|| self.offset > 1_000_000
|
||||
{
|
||||
return Err("请检查查询时间范围、搜索关键字和页码".into());
|
||||
}
|
||||
if let Some(keys) = &self.flight_keys
|
||||
&& (keys.len() > 6600
|
||||
|| !keys
|
||||
.split(',')
|
||||
.all(|key| key.len() == 32 && key.bytes().all(|c| c.is_ascii_hexdigit())))
|
||||
{
|
||||
return Err("记录标识无效".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn conditions(&self, sql: &mut QueryBuilder<sqlx::Sqlite>) {
|
||||
sql.push(" FROM rid_observations WHERE COALESCE(last_seen_ms,time_ms) >= ")
|
||||
.push_bind(self.from_ms)
|
||||
.push(" AND time_ms <= ")
|
||||
.push_bind(self.to_ms);
|
||||
sql.push(" AND flight_key IS NOT NULL");
|
||||
if let Some(keys) = &self.flight_keys {
|
||||
sql.push(" AND flight_key IN (");
|
||||
let mut params = sql.separated(",");
|
||||
for key in keys.split(',') {
|
||||
params.push_bind(key.to_owned());
|
||||
}
|
||||
params.push_unseparated(")");
|
||||
}
|
||||
let q = self.q.trim().to_lowercase();
|
||||
if !q.is_empty() {
|
||||
sql.push(" AND (instr(lower(target_id),")
|
||||
.push_bind(q.clone())
|
||||
.push(")>0 OR instr(lower(model),")
|
||||
.push_bind(q.clone())
|
||||
.push(")>0 OR instr(lower(bssid),")
|
||||
.push_bind(q.clone())
|
||||
.push(")>0 OR instr(lower(receiver_id),")
|
||||
.push_bind(q)
|
||||
.push(")>0)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn records(
|
||||
State(history): State<History>,
|
||||
Query(filter): Query<Filter>,
|
||||
) -> Result<Json<Value>> {
|
||||
filter.validate()?;
|
||||
let mut tx = history.pool.begin().await?;
|
||||
let mut count = QueryBuilder::new("SELECT count(*)");
|
||||
filter.conditions(&mut count);
|
||||
let total: i64 = count.build_query_scalar().fetch_one(&mut *tx).await?;
|
||||
let mut query = QueryBuilder::new(
|
||||
"WITH page AS (
|
||||
SELECT id,time_ms,receiver_id,target_id,model,bssid,last_seen_ms,flight_key,
|
||||
rssi,altitude_m,speed_mps,latitude,longitude,flight_statuses",
|
||||
);
|
||||
filter.conditions(&mut query);
|
||||
query
|
||||
.push(" ORDER BY COALESCE(last_seen_ms,time_ms) DESC,id DESC LIMIT ")
|
||||
.push_bind(filter.limit.unwrap_or(50).clamp(1, 200))
|
||||
.push(" OFFSET ")
|
||||
.push_bind(filter.offset)
|
||||
.push(
|
||||
") SELECT session.time_ms,session.receiver_id,session.target_id,session.model,session.bssid,
|
||||
session.last_seen_ms,session.flight_key,
|
||||
COALESCE(session.rssi,json_extract(point.osd,'$.rssi'),legacy.rssi),
|
||||
COALESCE(session.altitude_m,point.altitude_m,legacy.altitude_m,json_extract(point.osd,'$.geometricAltitudeM')),
|
||||
COALESCE(session.speed_mps,json_extract(point.osd,'$.speedMps'),legacy.speed_mps),
|
||||
COALESCE(session.latitude,point.latitude,legacy.latitude),
|
||||
COALESCE(session.longitude,point.longitude,legacy.longitude),session.flight_statuses
|
||||
FROM page AS session
|
||||
LEFT JOIN track_points AS point ON point.id=(
|
||||
SELECT id FROM track_points WHERE flight_key=session.flight_key ORDER BY id DESC LIMIT 1
|
||||
)
|
||||
LEFT JOIN rid_observations AS legacy ON legacy.id=(
|
||||
SELECT id FROM rid_observations WHERE flight_key IS NULL AND target_id=session.target_id
|
||||
AND time_ms BETWEEN session.time_ms AND session.last_seen_ms ORDER BY time_ms DESC,id DESC LIMIT 1
|
||||
)
|
||||
ORDER BY session.last_seen_ms DESC,session.id DESC",
|
||||
);
|
||||
let rows = query.build().fetch_all(&mut *tx).await?;
|
||||
let now = i64::try_from(crate::realtime::now_ms()).unwrap_or(i64::MAX);
|
||||
let entries = rows
|
||||
.into_iter()
|
||||
.map(|row| -> Result<_> {
|
||||
let last_seen: i64 = row.try_get(5)?;
|
||||
let active = now.saturating_sub(last_seen) < GAP_MS;
|
||||
Ok(json!({
|
||||
"flightKey": row.try_get::<String,_>(6)?,
|
||||
"flightStatuses": serde_json::from_str::<Vec<String>>(&row.try_get::<String,_>(12)?).unwrap_or_default(),
|
||||
"endMs": (!active).then_some(last_seen),
|
||||
"timeMs": row.try_get::<i64,_>(0)?,
|
||||
"lastSeenMs": last_seen,
|
||||
"receiverId": row.try_get::<String,_>(1)?,
|
||||
"targetId": row.try_get::<String,_>(2)?,
|
||||
"model": row.try_get::<Option<String>,_>(3)?,
|
||||
"bssid": row.try_get::<Option<String>,_>(4)?,
|
||||
"rssi": row.try_get::<Option<f64>,_>(7)?,
|
||||
"altitudeM": row.try_get::<Option<f64>,_>(8)?,
|
||||
"speedMps": row.try_get::<Option<f64>,_>(9)?,
|
||||
"latitude": row.try_get::<Option<f64>,_>(10)?,
|
||||
"longitude": row.try_get::<Option<f64>,_>(11)?,
|
||||
}))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({"entries":entries,"total":total})))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Dimension {
|
||||
Target,
|
||||
Model,
|
||||
Receiver,
|
||||
FlightStatus,
|
||||
}
|
||||
|
||||
async fn rankings(
|
||||
State(history): State<History>,
|
||||
Query(filter): Query<Filter>,
|
||||
) -> Result<Json<Value>> {
|
||||
filter.validate()?;
|
||||
let group = match filter.dimension.unwrap_or(Dimension::Target) {
|
||||
Dimension::Target => "target_id",
|
||||
Dimension::Model => "COALESCE(NULLIF(model,''),'未上报机型')",
|
||||
Dimension::Receiver => "receiver_id",
|
||||
Dimension::FlightStatus => {
|
||||
"CASE WHEN flight_statuses='[]' THEN 'unknown' ELSE (SELECT CASE WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='geofence_enter') THEN 'geofence_enter' WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='blacklist') THEN 'blacklist' WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='unregistered') THEN 'unregistered' WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='unfiled') THEN 'unfiled' WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='whitelist') THEN 'whitelist' WHEN EXISTS(SELECT 1 FROM json_each(flight_statuses) WHERE value='authorized') THEN 'authorized' ELSE 'unknown' END) END"
|
||||
}
|
||||
};
|
||||
let mut sql = QueryBuilder::new("SELECT ");
|
||||
sql.push(group).push(" AS name,count(*) AS count");
|
||||
filter.conditions(&mut sql);
|
||||
sql.push(" GROUP BY name ORDER BY count DESC,name LIMIT ")
|
||||
.push_bind(filter.limit.unwrap_or(50).clamp(1, 200));
|
||||
let entries = sql
|
||||
.build_query_as::<(String, i64)>()
|
||||
.fetch_all(&history.pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(name, count)| json!({"name":name,"count":count}))
|
||||
.collect::<Vec<_>>();
|
||||
Ok(Json(json!({"entries":entries})))
|
||||
}
|
||||
|
||||
pub fn router(history: History) -> Router {
|
||||
Router::new()
|
||||
.route("/api/workbench/observations", get(records))
|
||||
.route("/api/workbench/rankings", get(rankings))
|
||||
.with_state(history)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Keep an independent, branded console for the portable Windows executable.
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsString,
|
||||
io, mem,
|
||||
os::windows::{
|
||||
ffi::{OsStrExt, OsStringExt},
|
||||
process::CommandExt,
|
||||
},
|
||||
path::PathBuf,
|
||||
process::Command,
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::{
|
||||
Win32::{
|
||||
Foundation::HWND,
|
||||
System::{
|
||||
Com::{
|
||||
COINIT_APARTMENTTHREADED, CoInitializeEx, CoUninitialize,
|
||||
StructuredStorage::PROPVARIANT,
|
||||
},
|
||||
Console::{
|
||||
ATTACH_PARENT_PROCESS, AttachConsole, GetConsoleWindow, SetConsoleCtrlHandler,
|
||||
SetConsoleTitleW,
|
||||
},
|
||||
LibraryLoader::GetModuleHandleW,
|
||||
SystemInformation::GetSystemDirectoryW,
|
||||
Variant::VT_LPWSTR,
|
||||
},
|
||||
UI::{
|
||||
Shell::PropertiesSystem::{PROPERTYKEY, SHGetPropertyStoreForWindow},
|
||||
WindowsAndMessaging::{
|
||||
ICON_BIG, ICON_SMALL, LoadIconW, MB_ICONERROR, MB_OK, MessageBoxW,
|
||||
SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETICON,
|
||||
},
|
||||
},
|
||||
},
|
||||
core::{GUID, HRESULT},
|
||||
w,
|
||||
};
|
||||
|
||||
pub(crate) fn launch() -> io::Result<()> {
|
||||
let mut directory = [0u16; 1024];
|
||||
// SAFETY: The buffer is writable for the supplied number of UTF-16 units.
|
||||
let len =
|
||||
unsafe { GetSystemDirectoryW(directory.as_mut_ptr(), directory.len() as u32) } as usize;
|
||||
if len == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if len >= directory.len() {
|
||||
return Err(io::Error::other("无法定位 Windows 控制台"));
|
||||
}
|
||||
let system = PathBuf::from(OsString::from_wide(&directory[..len]));
|
||||
// Launch inside the classic console. Start-Process passes the executable path
|
||||
// directly to Windows, including spaces and shell metacharacters in folder names.
|
||||
Command::new(system.join("conhost.exe"))
|
||||
.arg(system.join("WindowsPowerShell/v1.0/powershell.exe"))
|
||||
.args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"])
|
||||
.raw_arg(r#""Start-Process -FilePath $env:RID_PORTABLE_CONSOLE_EXE -ArgumentList '--rid-console' -NoNewWindow -Wait""#)
|
||||
.env("RID_PORTABLE_CONSOLE_EXE", env::current_exe()?)
|
||||
.spawn()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn attach_parent() {
|
||||
// SAFETY: Attach this process to its parent's console if one exists.
|
||||
unsafe { AttachConsole(ATTACH_PARENT_PROCESS) };
|
||||
}
|
||||
|
||||
pub(crate) fn attach_window() -> io::Result<ConsoleWindow> {
|
||||
attach_parent();
|
||||
// SAFETY: These calls apply only to the new console of the portable launcher.
|
||||
let window = unsafe {
|
||||
let window = GetConsoleWindow();
|
||||
if window == 0 {
|
||||
return Err(io::Error::other("无法连接到 RID 命令窗口"));
|
||||
}
|
||||
SetConsoleCtrlHandler(None, 0);
|
||||
SetConsoleTitleW(w!("RID 侦测平台"));
|
||||
window
|
||||
};
|
||||
|
||||
// SAFETY: ID 1 is the shared application icon embedded in the exe by build.rs.
|
||||
let icon = unsafe { LoadIconW(GetModuleHandleW(ptr::null()), ptr::without_provenance(1)) };
|
||||
let mut previous = [None; 2];
|
||||
if icon != 0 {
|
||||
for (slot, size) in previous.iter_mut().zip([ICON_SMALL, ICON_BIG]) {
|
||||
*slot = set_window_icon(window, size as usize, icon);
|
||||
}
|
||||
}
|
||||
let mut resource = env::current_exe()?.into_os_string();
|
||||
resource.push(",0");
|
||||
let mut resource: Vec<_> = resource.encode_wide().chain(Some(0)).collect();
|
||||
let mut application_id: Vec<_> = "RID.Portable.Console"
|
||||
.encode_utf16()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
set_taskbar_properties(window, Some(&mut resource), Some(&mut application_id));
|
||||
Ok(ConsoleWindow { window, previous })
|
||||
}
|
||||
|
||||
pub(crate) struct ConsoleWindow {
|
||||
window: HWND,
|
||||
previous: [Option<isize>; 2],
|
||||
}
|
||||
|
||||
impl Drop for ConsoleWindow {
|
||||
fn drop(&mut self) {
|
||||
set_taskbar_properties(self.window, None, None);
|
||||
for (previous, size) in self.previous.into_iter().zip([ICON_SMALL, ICON_BIG]) {
|
||||
if let Some(icon) = previous {
|
||||
set_window_icon(self.window, size as usize, icon);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_window_icon(window: HWND, size: usize, icon: isize) -> Option<isize> {
|
||||
let mut previous = 0;
|
||||
// SAFETY: Send only an icon handle to the verified console window and wait briefly.
|
||||
let sent = unsafe {
|
||||
SendMessageTimeoutW(
|
||||
window,
|
||||
WM_SETICON,
|
||||
size,
|
||||
icon,
|
||||
SMTO_ABORTIFHUNG,
|
||||
500,
|
||||
&mut previous,
|
||||
)
|
||||
};
|
||||
(sent != 0).then_some(previous as isize)
|
||||
}
|
||||
|
||||
pub(crate) fn show_error(error: &str) {
|
||||
let message: Vec<_> = error.encode_utf16().chain(Some(0)).collect();
|
||||
// SAFETY: The UTF-16 strings remain valid through the dialog call.
|
||||
unsafe {
|
||||
MessageBoxW(
|
||||
0,
|
||||
message.as_ptr(),
|
||||
w!("RID 启动失败"),
|
||||
MB_OK | MB_ICONERROR,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct PropertyStore {
|
||||
vtable: *const PropertyStoreVtable,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct PropertyStoreVtable {
|
||||
query_interface: usize,
|
||||
add_ref: usize,
|
||||
release: unsafe extern "system" fn(*mut PropertyStore) -> u32,
|
||||
get_count: usize,
|
||||
get_at: usize,
|
||||
get_value: usize,
|
||||
set_value: unsafe extern "system" fn(
|
||||
*mut PropertyStore,
|
||||
*const PROPERTYKEY,
|
||||
*const PROPVARIANT,
|
||||
) -> HRESULT,
|
||||
}
|
||||
|
||||
fn set_taskbar_properties(
|
||||
window: HWND,
|
||||
icon: Option<&mut [u16]>,
|
||||
application_id: Option<&mut [u16]>,
|
||||
) {
|
||||
const STORE_IID: GUID = GUID::from_u128(0x886d8eeb_8cf2_4446_8d02_cdba1dbdcf99);
|
||||
const APP_MODEL: GUID = GUID::from_u128(0x9f4c2855_9f79_4b39_a8d0_e1d42de1d5f3);
|
||||
const ICON_RESOURCE: u32 = 3;
|
||||
const APPLICATION_ID: u32 = 5;
|
||||
// SAFETY: Request IPropertyStore with its exact IID and ABI. SetValue copies
|
||||
// the null-terminated strings within the call, including during cleanup.
|
||||
unsafe {
|
||||
if CoInitializeEx(ptr::null(), COINIT_APARTMENTTHREADED as u32) < 0 {
|
||||
return;
|
||||
}
|
||||
let mut store = ptr::null_mut::<PropertyStore>();
|
||||
if SHGetPropertyStoreForWindow(
|
||||
window,
|
||||
&STORE_IID,
|
||||
(&mut store as *mut *mut PropertyStore).cast(),
|
||||
) >= 0
|
||||
&& !store.is_null()
|
||||
{
|
||||
let methods = &*(*store).vtable;
|
||||
// Setting the application ID last refreshes the taskbar with the new icon.
|
||||
for (pid, text) in [(ICON_RESOURCE, icon), (APPLICATION_ID, application_id)] {
|
||||
let key = PROPERTYKEY {
|
||||
fmtid: APP_MODEL,
|
||||
pid,
|
||||
};
|
||||
let mut value: PROPVARIANT = mem::zeroed();
|
||||
if let Some(text) = text {
|
||||
let inner = &mut value.Anonymous.Anonymous;
|
||||
inner.vt = VT_LPWSTR;
|
||||
inner.Anonymous.pwszVal = text.as_mut_ptr();
|
||||
}
|
||||
(methods.set_value)(store, &key, &value);
|
||||
}
|
||||
(methods.release)(store);
|
||||
}
|
||||
CoUninitialize();
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,9 @@ pub fn router(simulation_api: bool) -> Router {
|
||||
with_store(simulation_api, new_store())
|
||||
}
|
||||
|
||||
pub(crate) type ObservationBatch = Vec<(Observation, u64)>;
|
||||
pub(crate) const TARGET_TTL_MS: u64 = 30_000;
|
||||
|
||||
pub(crate) type ObservationBatch = Vec<(Observation, u64, bool)>;
|
||||
|
||||
/// Serializes acceptance with a bounded monitoring feed without holding a
|
||||
/// blocking lock while waiting for capacity.
|
||||
@@ -86,6 +88,23 @@ impl TargetStore {
|
||||
&self,
|
||||
batch: Vec<Observation>,
|
||||
now: u64,
|
||||
) -> Result<(usize, Metrics), &'static str> {
|
||||
self.apply(batch, now, false).await
|
||||
}
|
||||
|
||||
pub async fn apply_rid_batch(
|
||||
&self,
|
||||
batch: Vec<Observation>,
|
||||
now: u64,
|
||||
) -> Result<(usize, Metrics), &'static str> {
|
||||
self.apply(batch, now, true).await
|
||||
}
|
||||
|
||||
async fn apply(
|
||||
&self,
|
||||
batch: Vec<Observation>,
|
||||
now: u64,
|
||||
resolve_mac: bool,
|
||||
) -> Result<(usize, Metrics), &'static str> {
|
||||
let _admission = self.admission.lock().await;
|
||||
let sender = self.sender()?;
|
||||
@@ -98,12 +117,36 @@ impl TargetStore {
|
||||
let mut observations = Vec::new();
|
||||
for observation in batch {
|
||||
let id = observation.target_id.clone();
|
||||
let alias = observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
.filter(|t| resolve_mac && t.serial.is_some())
|
||||
.and_then(|t| t.mac.as_ref())
|
||||
.map(|mac| (format!("MAC-{mac}"), observation.receiver_id.clone()));
|
||||
let previous = permit
|
||||
.as_ref()
|
||||
.and_then(|_| store.selected_observation(&id))
|
||||
.map(|point| {
|
||||
(
|
||||
point.receiver_id.clone(),
|
||||
point.source_epoch,
|
||||
point.sequence,
|
||||
)
|
||||
});
|
||||
if store.apply(observation, now) {
|
||||
accepted += 1;
|
||||
if let Some((alias, receiver)) = alias {
|
||||
store.remove_source(&alias, &receiver, now);
|
||||
}
|
||||
if permit.is_some()
|
||||
&& let Some(selected) = store.selected_observation(&id)
|
||||
&& !previous.as_ref().is_some_and(|(source, epoch, sequence)| {
|
||||
*source == selected.receiver_id
|
||||
&& *epoch == selected.source_epoch
|
||||
&& *sequence == selected.sequence
|
||||
})
|
||||
{
|
||||
observations.push((selected.clone(), now));
|
||||
observations.push((selected.clone(), now, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,7 +187,7 @@ impl TargetStore {
|
||||
permit.send(
|
||||
changed
|
||||
.into_iter()
|
||||
.map(|observation| (observation, now))
|
||||
.map(|observation| (observation, now, false))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
@@ -154,7 +197,12 @@ impl TargetStore {
|
||||
|
||||
pub(crate) fn new_store() -> TargetStore {
|
||||
TargetStore {
|
||||
store: Arc::new(Mutex::new(Store::new(10000, 40000, 30000, rand::random()))),
|
||||
store: Arc::new(Mutex::new(Store::new(
|
||||
10000,
|
||||
40000,
|
||||
TARGET_TTL_MS,
|
||||
rand::random(),
|
||||
))),
|
||||
admission: Arc::new(tokio::sync::Mutex::new(())),
|
||||
feed: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
@@ -203,7 +251,7 @@ async fn status(State(live): State<Live>, headers: HeaderMap) -> Response {
|
||||
let Ok(store) = live.store.lock() else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
Json(json!({"mode":if live.simulation_api {"synthetic-input-enabled"} else {"receiver-input"},"metrics":store.metrics(),"clients":live.clients.load(Ordering::Relaxed),"maxClients":4,"ttlMs":30000,"pushIntervalMs":20,"ackTimeoutMs":1000})).into_response()
|
||||
Json(json!({"mode":if live.simulation_api {"synthetic-input-enabled"} else {"receiver-input"},"metrics":store.metrics(),"clients":live.clients.load(Ordering::Relaxed),"maxClients":4,"ttlMs":TARGET_TTL_MS,"pushIntervalMs":20,"ackTimeoutMs":1000})).into_response()
|
||||
}
|
||||
|
||||
async fn snapshot(State(live): State<Live>, headers: HeaderMap) -> Response {
|
||||
@@ -278,10 +326,26 @@ async fn ingest(
|
||||
}
|
||||
}
|
||||
|
||||
async fn upgrade(State(live): State<Live>, headers: HeaderMap, ws: WebSocketUpgrade) -> Response {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct StreamFormat {
|
||||
format: Option<String>,
|
||||
}
|
||||
|
||||
async fn upgrade(
|
||||
State(live): State<Live>,
|
||||
axum::extract::Query(format): axum::extract::Query<StreamFormat>,
|
||||
lease: Option<axum::Extension<crate::auth::SessionLease>>,
|
||||
headers: HeaderMap,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
if !local_origin(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let json = match format.format.as_deref() {
|
||||
None | Some("postcard") => false,
|
||||
Some("json") => true,
|
||||
_ => return StatusCode::BAD_REQUEST.into_response(),
|
||||
};
|
||||
if live.shutdown.is_cancelled() {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
}
|
||||
@@ -297,7 +361,7 @@ async fn upgrade(State(live): State<Live>, headers: HeaderMap, ws: WebSocketUpgr
|
||||
let permit = ClientPermit(live.clients.clone());
|
||||
ws.max_message_size(1024)
|
||||
.max_frame_size(1024)
|
||||
.on_upgrade(move |socket| stream(socket, live, permit))
|
||||
.on_upgrade(move |socket| stream(socket, live, permit, json, lease.map(|lease| lease.0)))
|
||||
}
|
||||
|
||||
struct ClientPermit(Arc<AtomicUsize>);
|
||||
@@ -307,28 +371,47 @@ impl Drop for ClientPermit {
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream(mut socket: WebSocket, live: Live, _permit: ClientPermit) {
|
||||
async fn stream(
|
||||
mut socket: WebSocket,
|
||||
live: Live,
|
||||
_permit: ClientPermit,
|
||||
json: bool,
|
||||
lease: Option<crate::auth::SessionLease>,
|
||||
) {
|
||||
let mut since = None;
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(if json { 125 } else { 20 }));
|
||||
let mut check_at = tokio::time::Instant::now();
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {_=live.shutdown.cancelled()=>break,_=tick.tick()=>{}}
|
||||
if let Some(lease) = &lease
|
||||
&& tokio::time::Instant::now() >= check_at
|
||||
{
|
||||
if !lease.active().await {
|
||||
break;
|
||||
}
|
||||
check_at = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
}
|
||||
let frame = {
|
||||
let Ok(store) = live.store.lock() else {
|
||||
break;
|
||||
};
|
||||
store.frame(since, now_ms())
|
||||
};
|
||||
let Ok(bytes) = postcard::to_allocvec(&frame) else {
|
||||
break;
|
||||
let message = if json {
|
||||
let Ok(text) = serde_json::to_string(&frame) else {
|
||||
break;
|
||||
};
|
||||
Message::Text(text.into())
|
||||
} else {
|
||||
let Ok(bytes) = postcard::to_allocvec(&frame) else {
|
||||
break;
|
||||
};
|
||||
Message::Binary(bytes.into())
|
||||
};
|
||||
let sequence = frame.sequence;
|
||||
if !matches!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(200),
|
||||
socket.send(Message::Binary(bytes.into()))
|
||||
)
|
||||
.await,
|
||||
tokio::time::timeout(Duration::from_millis(200), socket.send(message)).await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
break;
|
||||
@@ -451,7 +534,7 @@ mod tests {
|
||||
async fn source_expiration_is_deferred_until_monitoring_has_capacity() {
|
||||
let store = new_store();
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
|
||||
store.install_feed(sender).unwrap();
|
||||
store.install_feed(sender.clone()).unwrap();
|
||||
let a = sample("A", "RX1", 1);
|
||||
let mut b = sample("A", "RX2", 1);
|
||||
b.longitude = None;
|
||||
@@ -459,6 +542,7 @@ mod tests {
|
||||
store.apply_batch(vec![a], 1).await.unwrap();
|
||||
receiver.recv().await.unwrap();
|
||||
store.apply_batch(vec![b], 10).await.unwrap();
|
||||
sender.try_send(Vec::new()).unwrap();
|
||||
let before = store.lock().unwrap().frame(None, 10).sequence;
|
||||
store.expire(30_001).await.unwrap();
|
||||
let hidden = store.lock().unwrap().frame(Some(before), 30_001);
|
||||
@@ -481,7 +565,7 @@ mod tests {
|
||||
async fn suppressed_target_can_recover_after_clock_moves_backwards() {
|
||||
let store = new_store();
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
|
||||
store.install_feed(sender).unwrap();
|
||||
store.install_feed(sender.clone()).unwrap();
|
||||
store
|
||||
.apply_batch(vec![sample("A", "RX1", 1)], 1)
|
||||
.await
|
||||
@@ -491,6 +575,7 @@ mod tests {
|
||||
later.longitude = None;
|
||||
later.latitude = None;
|
||||
store.apply_batch(vec![later], 10).await.unwrap();
|
||||
sender.try_send(Vec::new()).unwrap();
|
||||
store.expire(30_001).await.unwrap();
|
||||
assert!(store.lock().unwrap().frame(None, 30_001).targets.is_empty());
|
||||
receiver.recv().await.unwrap();
|
||||
@@ -527,7 +612,10 @@ mod tests {
|
||||
store.apply_batch(vec![a], 1).await.unwrap();
|
||||
store.apply_batch(vec![b], 10).await.unwrap();
|
||||
receiver.recv().await.unwrap();
|
||||
receiver.recv().await.unwrap();
|
||||
assert!(
|
||||
receiver.try_recv().is_err(),
|
||||
"standby observations must not add track samples"
|
||||
);
|
||||
store.expire(30_001).await.unwrap();
|
||||
let batch = receiver.recv().await.unwrap();
|
||||
assert_eq!(batch.len(), 1);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
mod device;
|
||||
mod gb46750;
|
||||
mod manager;
|
||||
mod nmea;
|
||||
mod tcp;
|
||||
mod uid;
|
||||
mod usb_ports;
|
||||
|
||||
@@ -25,8 +27,8 @@ use std::{
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt},
|
||||
net::{TcpListener, UdpSocket},
|
||||
task::{JoinHandle, JoinSet},
|
||||
net::UdpSocket,
|
||||
task::JoinHandle,
|
||||
};
|
||||
use tokio_serial::SerialPortBuilderExt;
|
||||
|
||||
@@ -68,6 +70,8 @@ struct Config {
|
||||
baud_rate: u32,
|
||||
bind_ip: String,
|
||||
port: u16,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
peer_ip: Option<IpAddr>,
|
||||
}
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
@@ -80,11 +84,17 @@ impl Default for Config {
|
||||
baud_rate: 115200,
|
||||
bind_ip: "127.0.0.1".into(),
|
||||
port: 8788,
|
||||
peer_ip: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Config {
|
||||
fn validate(&self) -> Result<(), &'static str> {
|
||||
if self.peer_ip.is_some_and(|ip| {
|
||||
self.transport != Transport::TcpListen || ip.is_unspecified() || ip.is_multicast()
|
||||
}) {
|
||||
return Err("来源 IP 须为 TCP 接收器的单个设备地址");
|
||||
}
|
||||
if !self.enabled {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -121,18 +131,26 @@ struct Status {
|
||||
rejected_frames: u64,
|
||||
accepted_observations: u64,
|
||||
ignored_lines: u64,
|
||||
heartbeat_frames: u64,
|
||||
invalid_targets: u64,
|
||||
last_data_ms: Option<u64>,
|
||||
last_valid_frame_ms: Option<u64>,
|
||||
last_peer_ip: Option<IpAddr>,
|
||||
last_error: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
notice: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
gnss: Option<nmea::Snapshot>,
|
||||
capture_hex: String,
|
||||
}
|
||||
struct Monitor {
|
||||
status: Status,
|
||||
gnss: nmea::Gnss,
|
||||
capture: VecDeque<u8>,
|
||||
identity_samples: VecDeque<serde_json::Value>,
|
||||
source_epoch: u64,
|
||||
sequence: u64,
|
||||
mac_bindings: device::MacBindings,
|
||||
}
|
||||
impl Default for Monitor {
|
||||
fn default() -> Self {
|
||||
@@ -142,11 +160,26 @@ impl Default for Monitor {
|
||||
..Status::default()
|
||||
},
|
||||
capture: VecDeque::new(),
|
||||
identity_samples: VecDeque::new(),
|
||||
gnss: nmea::Gnss::default(),
|
||||
source_epoch: now_ms(),
|
||||
sequence: 0,
|
||||
mac_bindings: device::MacBindings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Monitor {
|
||||
fn snapshot(&self) -> Status {
|
||||
let mut status = self.status.clone();
|
||||
if matches!(
|
||||
status.state.as_str(),
|
||||
"tcp-listening" | "udp-listening" | "serial-open"
|
||||
) {
|
||||
status.gnss = self.gnss.snapshot(status.last_peer_ip, now_ms());
|
||||
}
|
||||
status
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Receiver {
|
||||
id: String,
|
||||
@@ -174,25 +207,21 @@ pub(crate) async fn router(root: PathBuf, targets: TargetStore) -> Router {
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
#[cfg(test)]
|
||||
async fn start(&self, config: Config) {
|
||||
self.configure(config, false).await;
|
||||
}
|
||||
|
||||
async fn configure(&self, config: Config, shared_tcp: bool) {
|
||||
let mut task = self.task.lock().await;
|
||||
if let Some(old) = task.take() {
|
||||
old.abort();
|
||||
let _ = old.await;
|
||||
}
|
||||
*self.config.lock().unwrap() = config.clone();
|
||||
if !config.enabled {
|
||||
self.monitor.lock().unwrap().status.state = "stopped".into();
|
||||
self.set_config(&config);
|
||||
if !config.enabled || (shared_tcp && config.transport == Transport::TcpListen) {
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
let epoch = now_ms().max(monitor.source_epoch.saturating_add(1));
|
||||
*monitor = Monitor {
|
||||
source_epoch: epoch,
|
||||
..Monitor::default()
|
||||
};
|
||||
}
|
||||
let receiver = self.clone();
|
||||
*task = Some(tokio::spawn(async move {
|
||||
loop {
|
||||
@@ -207,22 +236,48 @@ impl Receiver {
|
||||
}
|
||||
}));
|
||||
}
|
||||
fn received(&self, bytes: &[u8]) {
|
||||
fn set_config(&self, config: &Config) {
|
||||
*self.config.lock().unwrap() = config.clone();
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
if config.enabled {
|
||||
let epoch = now_ms().max(monitor.source_epoch.saturating_add(1));
|
||||
*monitor = Monitor {
|
||||
source_epoch: epoch,
|
||||
..Monitor::default()
|
||||
};
|
||||
monitor.status.state = "connecting".into();
|
||||
} else {
|
||||
monitor.status.state = "stopped".into();
|
||||
}
|
||||
}
|
||||
fn received(&self, bytes: &[u8], peer_ip: Option<IpAddr>) {
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.received_bytes += bytes.len() as u64;
|
||||
monitor.status.last_data_ms = Some(now_ms());
|
||||
monitor.status.last_peer_ip = peer_ip;
|
||||
let tail = &bytes[bytes.len().saturating_sub(4096)..];
|
||||
let excess = (monitor.capture.len() + tail.len()).saturating_sub(4096);
|
||||
monitor.capture.drain(..excess);
|
||||
monitor.capture.extend(tail.iter().copied());
|
||||
}
|
||||
async fn decode(&self, format: Format, bytes: &[u8]) -> std::io::Result<()> {
|
||||
async fn decode(
|
||||
&self,
|
||||
format: Format,
|
||||
bytes: &[u8],
|
||||
peer: Option<IpAddr>,
|
||||
) -> std::io::Result<()> {
|
||||
let _decode = self.decode_gate.lock().await;
|
||||
let uid_identity = self.config.lock().unwrap().uid_identity;
|
||||
let now = now_ms();
|
||||
let batch = {
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
let result: Result<Vec<Observation>, ()> = match format {
|
||||
Format::RidDeviceJson | Format::UidJson => {
|
||||
if bytes.trim_ascii().starts_with(b"$")
|
||||
&& monitor.gnss.observe(bytes, peer, now_ms())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(notice) = gb46750::notice(bytes) {
|
||||
monitor.status.ignored_lines += 1;
|
||||
monitor.status.notice = Some(notice);
|
||||
@@ -236,8 +291,12 @@ impl Receiver {
|
||||
} {
|
||||
Ok(decoded) => {
|
||||
monitor.status.invalid_targets += decoded.invalid_targets;
|
||||
if decoded.ignored {
|
||||
if decoded.kind != device::FrameKind::Data {
|
||||
monitor.status.ignored_lines += 1;
|
||||
if decoded.kind == device::FrameKind::Heartbeat {
|
||||
monitor.status.heartbeat_frames += 1;
|
||||
monitor.status.last_valid_frame_ms = Some(now);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Ok(decoded.observations)
|
||||
@@ -305,15 +364,47 @@ impl Receiver {
|
||||
}
|
||||
}
|
||||
}
|
||||
if format == Format::RidDeviceJson {
|
||||
monitor.mac_bindings.resolve(&mut batch, now);
|
||||
}
|
||||
// Keep the first parsed frame for each identity, independently of the rolling
|
||||
// byte tail. A repeated heartbeat must not erase evidence for a second ID.
|
||||
for observation in &batch {
|
||||
if monitor
|
||||
.identity_samples
|
||||
.iter()
|
||||
.any(|sample| sample["targetId"] == observation.target_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if monitor.identity_samples.len() == 64 {
|
||||
monitor.identity_samples.pop_front();
|
||||
}
|
||||
let raw = String::from_utf8_lossy(&bytes[..bytes.len().min(16_384)]).into_owned();
|
||||
monitor.identity_samples.push_back(json!({
|
||||
"targetId":observation.target_id, "receiverId":self.id, "peerIp":peer,
|
||||
"receivedAtMs":now, "format":format, "telemetry":observation.telemetry,
|
||||
"raw":raw, "truncated":bytes.len()>16_384
|
||||
}));
|
||||
}
|
||||
monitor.status.decoded_frames += 1;
|
||||
batch
|
||||
};
|
||||
if batch.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.targets.apply_batch(batch, now_ms()).await {
|
||||
let result = if format == Format::RidDeviceJson {
|
||||
self.targets.apply_rid_batch(batch, now).await
|
||||
} else {
|
||||
self.targets.apply_batch(batch, now).await
|
||||
};
|
||||
match result {
|
||||
Ok((accepted, _)) => {
|
||||
self.monitor.lock().unwrap().status.accepted_observations += accepted as u64;
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.accepted_observations += accepted as u64;
|
||||
if accepted > 0 {
|
||||
monitor.status.last_valid_frame_ms = Some(now);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -327,6 +418,7 @@ impl Receiver {
|
||||
mut reader: R,
|
||||
format: Format,
|
||||
idle_timeout: Option<Duration>,
|
||||
peer_ip: Option<IpAddr>,
|
||||
) -> std::io::Result<()> {
|
||||
let mut chunk = [0u8; 8192];
|
||||
let mut buffer = Vec::new();
|
||||
@@ -343,11 +435,16 @@ impl Receiver {
|
||||
};
|
||||
if n == 0 {
|
||||
if !buffer.is_empty() {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
if format == Format::RidDeviceJson {
|
||||
// Some network serial bridges close after a complete frame without LF.
|
||||
self.decode(format, &buffer, peer_ip).await?;
|
||||
} else {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.received(&chunk[..n]);
|
||||
self.received(&chunk[..n], peer_ip);
|
||||
if matches!(format, Format::Raw) {
|
||||
continue;
|
||||
}
|
||||
@@ -370,7 +467,7 @@ impl Receiver {
|
||||
Format::JsonLines | Format::RidDeviceJson | Format::UidJson => {
|
||||
while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
|
||||
if end <= 65536 {
|
||||
self.decode(format, &buffer[..end]).await?;
|
||||
self.decode(format, &buffer[..end], peer_ip).await?;
|
||||
} else {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
}
|
||||
@@ -395,7 +492,7 @@ impl Receiver {
|
||||
if buffer.len() < length + 4 {
|
||||
break;
|
||||
}
|
||||
self.decode(format, &buffer[4..length + 4]).await?;
|
||||
self.decode(format, &buffer[4..length + 4], peer_ip).await?;
|
||||
buffer.drain(..length + 4);
|
||||
}
|
||||
}
|
||||
@@ -414,7 +511,7 @@ impl Receiver {
|
||||
monitor.status.last_error = None;
|
||||
monitor.status.endpoint = config.serial_port.clone();
|
||||
}
|
||||
self.stream(serial, config.format, None).await
|
||||
self.stream(serial, config.format, None, None).await
|
||||
}
|
||||
Transport::Udp => {
|
||||
let socket = UdpSocket::bind(config.address()).await?;
|
||||
@@ -426,48 +523,42 @@ impl Receiver {
|
||||
}
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let (n, _) = socket.recv_from(&mut buffer).await?;
|
||||
self.received(&buffer[..n]);
|
||||
self.decode(config.format, &buffer[..n]).await?;
|
||||
let (n, peer) = socket.recv_from(&mut buffer).await?;
|
||||
self.received(&buffer[..n], Some(peer.ip().to_canonical()));
|
||||
self.decode(config.format, &buffer[..n], Some(peer.ip().to_canonical()))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Transport::TcpListen => {
|
||||
let listener = TcpListener::bind(config.address()).await?;
|
||||
{
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.state = "tcp-listening".into();
|
||||
monitor.status.last_error = None;
|
||||
monitor.status.endpoint = listener.local_addr()?.to_string();
|
||||
}
|
||||
let mut clients = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
incoming=listener.accept()=>{let(socket,_)=incoming?;if clients.len()<8{let receiver=self.clone();let format=config.format;clients.spawn(async move{let _=receiver.stream(socket,format,Some(Duration::from_secs(30))).await;});}},
|
||||
_=clients.join_next(),if !clients.is_empty()=>{}
|
||||
}
|
||||
}
|
||||
let (_routes, active) = tokio::sync::watch::channel(tcp::Binding {
|
||||
routes: vec![tcp::Route::new(self.clone(), config)],
|
||||
discovery: false,
|
||||
});
|
||||
tcp::receive(config.address(), active, None, None).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn status(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
fn status(receiver: Receiver, headers: HeaderMap, can_capture: bool) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
let mut status = monitor.status.clone();
|
||||
status.capture_hex = monitor
|
||||
.capture
|
||||
.iter()
|
||||
.rev()
|
||||
.take(64)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let mut status = monitor.snapshot();
|
||||
if can_capture {
|
||||
status.capture_hex = monitor
|
||||
.capture
|
||||
.iter()
|
||||
.rev()
|
||||
.take(64)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
}
|
||||
Json(status).into_response()
|
||||
}
|
||||
async fn capture(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
@@ -481,7 +572,8 @@ async fn capture(State(receiver): State<Receiver>, headers: HeaderMap) -> Respon
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
Json(json!({"encoding":"hex","bytes":monitor.capture.len(),"data":hex,"lastDataMs":monitor.status.last_data_ms})).into_response()
|
||||
Json(json!({"encoding":"hex","bytes":monitor.capture.len(),"data":hex,"lastDataMs":monitor.status.last_data_ms,
|
||||
"identitySamples":monitor.identity_samples})).into_response()
|
||||
}
|
||||
async fn config(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
@@ -527,11 +619,12 @@ mod tests {
|
||||
b.id = "second".into();
|
||||
b.targets = a.targets.clone();
|
||||
let packet=br#"{"message":"RID","uav":[{"serial":"KNOWN-SN","lon":120,"lat":30},{"MAC":"aa:bb:cc:dd:ee:ff","lon":120,"lat":30},{"serial":"MAC-AABBCCDDEEFF","lon":120,"lat":30}]}"#;
|
||||
a.decode(Format::RidDeviceJson, packet).await.unwrap();
|
||||
b.decode(Format::RidDeviceJson, packet).await.unwrap();
|
||||
a.decode(Format::RidDeviceJson, packet, None).await.unwrap();
|
||||
b.decode(Format::RidDeviceJson, packet, None).await.unwrap();
|
||||
a.decode(
|
||||
Format::UidJson,
|
||||
br#"{"uid":"KNOWN-SN","ua_longitude":120,"ua_latitude":30}"#,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -563,8 +656,8 @@ mod tests {
|
||||
b.id = "second".into();
|
||||
b.targets = a.targets.clone();
|
||||
let packet = br#"{"uid":"AIRCRAFT-1","ua_longitude":120,"ua_latitude":30}"#;
|
||||
a.decode(Format::UidJson, packet).await.unwrap();
|
||||
b.decode(Format::UidJson, packet).await.unwrap();
|
||||
a.decode(Format::UidJson, packet, None).await.unwrap();
|
||||
b.decode(Format::UidJson, packet, None).await.unwrap();
|
||||
assert_eq!(
|
||||
a.targets
|
||||
.lock()
|
||||
@@ -581,8 +674,8 @@ mod tests {
|
||||
d.targets = c.targets.clone();
|
||||
c.config.lock().unwrap().uid_identity = UidIdentity::GlobalDevice;
|
||||
d.config.lock().unwrap().uid_identity = UidIdentity::GlobalDevice;
|
||||
c.decode(Format::UidJson, packet).await.unwrap();
|
||||
d.decode(Format::UidJson, packet).await.unwrap();
|
||||
c.decode(Format::UidJson, packet, None).await.unwrap();
|
||||
d.decode(Format::UidJson, packet, None).await.unwrap();
|
||||
let frame = c.targets.lock().unwrap().frame(None, now_ms());
|
||||
assert_eq!(frame.targets.len(), 1);
|
||||
assert_eq!(frame.targets[0].sources.len(), 2);
|
||||
@@ -603,12 +696,41 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn serial_identity_evidence_is_not_replaced_by_ssid_or_heartbeat_tail() {
|
||||
let receiver = receiver();
|
||||
let peer = Some("192.168.1.98".parse().unwrap());
|
||||
let packet = br#"{"message":"RID","uav":[{"serial":"FPV00000000000000000","ssid":"RID_FPV12111111","MAC":"46:59:64:c6:69:05","lon":0,"lat":0}]}"#;
|
||||
for _ in 0..3 {
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, packet, peer)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
receiver.received(&vec![b'x'; 8192], peer);
|
||||
let targets = receiver
|
||||
.targets
|
||||
.lock()
|
||||
.unwrap()
|
||||
.frame(None, now_ms())
|
||||
.targets;
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].observation.target_id, "FPV00000000000000000");
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
assert_eq!(monitor.identity_samples.len(), 1);
|
||||
assert_eq!(monitor.identity_samples[0]["peerIp"], "192.168.1.98");
|
||||
assert_eq!(
|
||||
monitor.identity_samples[0]["raw"],
|
||||
String::from_utf8_lossy(packet).as_ref()
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn gb46750_diagnostic_is_not_a_protocol_mismatch() {
|
||||
let receiver = receiver();
|
||||
receiver
|
||||
.decode(
|
||||
Format::RidDeviceJson,
|
||||
b"[GB46750] Invalid: format_header=0xF1, expect 0xFF\r\n",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -634,6 +756,96 @@ mod tests {
|
||||
telemetry: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_matches_the_source_ip_and_counts_heartbeats_without_targets() {
|
||||
use tokio::{io::AsyncWriteExt, net::TcpStream, time::timeout};
|
||||
|
||||
async fn bound(receiver: &Receiver) -> String {
|
||||
timeout(Duration::from_secs(3), async {
|
||||
loop {
|
||||
let status = receiver.monitor.lock().unwrap().status.clone();
|
||||
if status.state == "tcp-listening" {
|
||||
return status.endpoint;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
let receiver = receiver();
|
||||
let mut config = Config {
|
||||
enabled: true,
|
||||
transport: Transport::TcpListen,
|
||||
format: Format::RidDeviceJson,
|
||||
port: 0,
|
||||
peer_ip: Some("127.0.0.2".parse().unwrap()),
|
||||
..Config::default()
|
||||
};
|
||||
receiver.start(config.clone()).await;
|
||||
let mut other = TcpStream::connect(bound(&receiver).await).await.unwrap();
|
||||
assert!(matches!(
|
||||
timeout(Duration::from_secs(3), other.read(&mut [0])).await,
|
||||
Ok(Ok(0) | Err(_))
|
||||
));
|
||||
assert_eq!(receiver.monitor.lock().unwrap().status.received_bytes, 0);
|
||||
|
||||
config.peer_ip = Some("127.0.0.1".parse().unwrap());
|
||||
receiver.start(config).await;
|
||||
let mut device = TcpStream::connect(bound(&receiver).await).await.unwrap();
|
||||
// A network serial bridge may close after a complete packet without LF.
|
||||
device
|
||||
.write_all(b"$GNRMC,V,,,,,,\r\n{\"message\":\"heartbeat\",\"uav\":[]}")
|
||||
.await
|
||||
.unwrap();
|
||||
device.shutdown().await.unwrap();
|
||||
let status = timeout(Duration::from_secs(3), async {
|
||||
loop {
|
||||
let status = receiver.monitor.lock().unwrap().status.clone();
|
||||
if status.heartbeat_frames == 1 {
|
||||
return status;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(status.last_peer_ip, Some("127.0.0.1".parse().unwrap()));
|
||||
assert!(status.received_bytes > 0);
|
||||
assert_eq!(status.ignored_lines, 2);
|
||||
assert_eq!(status.rejected_frames, 0);
|
||||
assert_eq!(status.accepted_observations, 0);
|
||||
assert!(status.last_valid_frame_ms.is_some());
|
||||
receiver.start(Config::default()).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn raw_serial_traffic_does_not_confirm_a_receiver() {
|
||||
let receiver = receiver();
|
||||
let bytes = b"unrelated serial log\r\n";
|
||||
receiver.received(bytes, None);
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, bytes, None)
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
assert!(monitor.status.last_data_ms.is_some());
|
||||
assert!(monitor.status.last_valid_frame_ms.is_none());
|
||||
}
|
||||
receiver
|
||||
.decode(
|
||||
Format::RidDeviceJson,
|
||||
br#"{"message":"heartbeat","uav":[]}"#,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
assert!(monitor.status.last_valid_frame_ms.is_some());
|
||||
assert_eq!(monitor.status.accepted_observations, 0);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn fragmented_serial_like_json_is_decoded_without_hardware() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
@@ -642,7 +854,7 @@ mod tests {
|
||||
let reader = receiver.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
reader
|
||||
.stream(worker, Format::JsonLines, None)
|
||||
.stream(worker, Format::JsonLines, None, None)
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
@@ -719,7 +931,7 @@ mod tests {
|
||||
let (stream, mut writer) = tokio::io::duplex(2048);
|
||||
let task = tokio::spawn(async move {
|
||||
reader
|
||||
.stream(stream, Format::RidDeviceJson, None)
|
||||
.stream(stream, Format::RidDeviceJson, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
@@ -766,7 +978,7 @@ mod tests {
|
||||
let lat = parts.next().unwrap().parse::<f64>().unwrap();
|
||||
let packet = json!({"message":"RID","uav":[{"serial":"TEST-A","lon":lon,"lat":lat}]});
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes())
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut store = receiver.targets.lock().unwrap();
|
||||
@@ -790,7 +1002,7 @@ mod tests {
|
||||
for serial in ["TEST-A", "TEST-B", "TEST-A", "TEST-B"] {
|
||||
let packet = json!({"message":"RID","uav":[{"serial":serial,"lon":0.0,"lat":0.0}]});
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes())
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -816,12 +1028,89 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mac_alias_promotes_to_serial_and_ignores_controller_only_frames() {
|
||||
let receiver = receiver();
|
||||
let mac = "f1:d0:ca:71:56:1b";
|
||||
let pilot_only =
|
||||
json!({"MAC":mac,"pilot_lat":41.014128,"pilot_lon":117.903272,"lat":0,"lon":0});
|
||||
let aircraft = json!({"MAC":mac,"lat":41.014170,"lon":117.903273,"AltitudeG":396.5});
|
||||
let serial = json!({"serial":"TEST-SN","MAC":"F1D0CA71561B","lat":41.014170,"lon":117.903273,"AltitudeG":396.5});
|
||||
for (payload, expected) in [
|
||||
(pilot_only.clone(), None),
|
||||
(aircraft.clone(), Some("MAC-F1D0CA71561B")),
|
||||
(serial, Some("TEST-SN")),
|
||||
(pilot_only, Some("TEST-SN")),
|
||||
(aircraft, Some("TEST-SN")),
|
||||
] {
|
||||
let packet = json!({"message":"RID","uav":[payload]});
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let targets = receiver
|
||||
.targets
|
||||
.lock()
|
||||
.unwrap()
|
||||
.frame(None, now_ms())
|
||||
.targets;
|
||||
if let Some(identity) = expected {
|
||||
assert_eq!(targets.len(), 1);
|
||||
assert_eq!(targets[0].observation.target_id, identity);
|
||||
assert_eq!(
|
||||
targets[0].observation.coordinates(),
|
||||
Some([117.903273, 41.014170])
|
||||
);
|
||||
assert_eq!(
|
||||
targets[0]
|
||||
.observation
|
||||
.telemetry
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.geometric_altitude_m,
|
||||
Some(396.5)
|
||||
);
|
||||
} else {
|
||||
assert!(targets.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_mac_does_not_merge_two_reported_serial_numbers() {
|
||||
let receiver = receiver();
|
||||
let mac = "AABBCCDDEEFF";
|
||||
let packet = json!({"message":"RID","uav":[
|
||||
{"serial":"TEST-A","MAC":mac,"lat":30,"lon":120},
|
||||
{"serial":"TEST-B","MAC":mac,"lat":31,"lon":121},
|
||||
{"MAC":mac,"lat":32,"lon":122}
|
||||
]});
|
||||
receiver
|
||||
.decode(Format::RidDeviceJson, packet.to_string().as_bytes(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let frame = receiver.targets.lock().unwrap().frame(None, now_ms());
|
||||
assert_eq!(frame.targets.len(), 2);
|
||||
assert!(
|
||||
frame
|
||||
.targets
|
||||
.iter()
|
||||
.any(|t| t.observation.target_id == "TEST-A")
|
||||
);
|
||||
assert!(
|
||||
frame
|
||||
.targets
|
||||
.iter()
|
||||
.any(|t| t.observation.target_id == "TEST-B")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_capture_never_fabricates_targets() {
|
||||
let receiver = receiver();
|
||||
receiver.received(&vec![0xAA; 10000]);
|
||||
receiver.received(&vec![0xAA; 10000], None);
|
||||
receiver
|
||||
.decode(Format::Raw, b"unknown vendor bytes")
|
||||
.decode(Format::Raw, b"unknown vendor bytes", None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(receiver.monitor.lock().unwrap().capture.len(), 4096);
|
||||
|
||||
@@ -1,11 +1,104 @@
|
||||
//! Adapter for the receiver's RID/uav JSON envelope. No transport or device writes.
|
||||
use rid_shared::{DeviceTelemetry, MAX_BATCH, Observation};
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const MAC_BINDING_TTL_MS: u64 = crate::realtime::TARGET_TTL_MS;
|
||||
const MAX_MAC_BINDINGS: usize = 4096;
|
||||
|
||||
struct MacBinding {
|
||||
identity: Option<(String, String)>,
|
||||
confirmed_at: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MacBindings {
|
||||
entries: HashMap<String, MacBinding>,
|
||||
last_cleanup: u64,
|
||||
}
|
||||
|
||||
impl MacBindings {
|
||||
pub fn resolve(&mut self, batch: &mut Vec<Observation>, now: u64) {
|
||||
if now.saturating_sub(self.last_cleanup) >= MAC_BINDING_TTL_MS {
|
||||
self.entries
|
||||
.retain(|_, binding| now.saturating_sub(binding.confirmed_at) < MAC_BINDING_TTL_MS);
|
||||
self.last_cleanup = now;
|
||||
}
|
||||
let mut positioned_serials = HashSet::new();
|
||||
for observation in batch.iter() {
|
||||
let Some(telemetry) = &observation.telemetry else {
|
||||
continue;
|
||||
};
|
||||
let Some(serial) = &telemetry.serial else {
|
||||
continue;
|
||||
};
|
||||
if observation.coordinates().is_some() {
|
||||
positioned_serials.insert(observation.target_id.clone());
|
||||
}
|
||||
let Some(mac) = &telemetry.mac else { continue };
|
||||
let identity = (observation.target_id.clone(), serial.clone());
|
||||
if let Some(binding) = self.entries.get_mut(mac) {
|
||||
if now.saturating_sub(binding.confirmed_at) >= MAC_BINDING_TTL_MS {
|
||||
binding.identity = Some(identity);
|
||||
} else if binding.identity.as_ref() != Some(&identity) {
|
||||
// A shared MAC no longer identifies either aircraft on this receiver.
|
||||
binding.identity = None;
|
||||
}
|
||||
binding.confirmed_at = now;
|
||||
} else if self.entries.len() < MAX_MAC_BINDINGS {
|
||||
self.entries.insert(
|
||||
mac.clone(),
|
||||
MacBinding {
|
||||
identity: Some(identity),
|
||||
confirmed_at: now,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
batch.retain_mut(|observation| {
|
||||
let positioned = observation.coordinates().is_some();
|
||||
let Some(telemetry) = &mut observation.telemetry else {
|
||||
return true;
|
||||
};
|
||||
if telemetry.serial.is_some() {
|
||||
return true;
|
||||
}
|
||||
// A controller position alone does not establish an aircraft target.
|
||||
if !positioned {
|
||||
return false;
|
||||
}
|
||||
let Some(binding) = telemetry
|
||||
.mac
|
||||
.as_ref()
|
||||
.and_then(|mac| self.entries.get(mac))
|
||||
.filter(|binding| now.saturating_sub(binding.confirmed_at) < MAC_BINDING_TTL_MS)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let Some((target_id, serial)) = &binding.identity else {
|
||||
return false;
|
||||
};
|
||||
if positioned_serials.contains(target_id) {
|
||||
return false;
|
||||
}
|
||||
observation.target_id.clone_from(target_id);
|
||||
telemetry.serial = Some(serial.clone());
|
||||
true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(super) enum FrameKind {
|
||||
Data,
|
||||
Heartbeat,
|
||||
Ignored,
|
||||
}
|
||||
|
||||
pub(super) struct Decoded {
|
||||
pub observations: Vec<Observation>,
|
||||
pub invalid_targets: u64,
|
||||
pub ignored: bool,
|
||||
pub kind: FrameKind,
|
||||
}
|
||||
fn text(v: &Value, key: &str) -> Option<String> {
|
||||
v.get(key)?
|
||||
@@ -33,7 +126,7 @@ pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Dec
|
||||
return Ok(Decoded {
|
||||
observations: vec![],
|
||||
invalid_targets: 0,
|
||||
ignored: true,
|
||||
kind: FrameKind::Ignored,
|
||||
});
|
||||
}
|
||||
let envelope: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
@@ -46,7 +139,7 @@ pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Dec
|
||||
return Ok(Decoded {
|
||||
observations: vec![],
|
||||
invalid_targets: 0,
|
||||
ignored: true,
|
||||
kind: FrameKind::Heartbeat,
|
||||
});
|
||||
}
|
||||
if envelope.get("message").and_then(Value::as_str) != Some("RID") {
|
||||
@@ -59,7 +152,7 @@ pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Dec
|
||||
let mut decoded = Decoded {
|
||||
observations: Vec::with_capacity(entries.len()),
|
||||
invalid_targets: 0,
|
||||
ignored: false,
|
||||
kind: FrameKind::Data,
|
||||
};
|
||||
for v in entries {
|
||||
let serial = text(v, "serial");
|
||||
@@ -136,11 +229,12 @@ mod tests {
|
||||
#[test]
|
||||
fn malformed_envelopes_are_not_salvaged() {
|
||||
let mut seq = 0;
|
||||
assert!(decode(b"boot log", 1, &mut seq).unwrap().ignored);
|
||||
assert!(decode(b"boot log", 1, &mut seq).unwrap().kind == FrameKind::Ignored);
|
||||
assert!(
|
||||
decode(br#"{"message":"heartbeat","uav":[]}"#, 1, &mut seq)
|
||||
.unwrap()
|
||||
.ignored
|
||||
.kind
|
||||
== FrameKind::Heartbeat
|
||||
);
|
||||
for b in [b"{broken".as_slice(), br#"{"message":"RID","uav":null}"#] {
|
||||
assert!(decode(b, 1, &mut seq).is_err());
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
//! Verified NMEA 0183 status for the receiver itself.
|
||||
use serde::Serialize;
|
||||
use std::net::IpAddr;
|
||||
|
||||
const FRESH_MS: u64 = 15_000;
|
||||
const CONSTELLATIONS: [&str; 7] = ["GPS", "北斗", "GLONASS", "Galileo", "QZSS", "NavIC", "GNSS"];
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct Snapshot {
|
||||
pub fix_available: Option<bool>,
|
||||
pub fix_dimension: Option<u8>,
|
||||
pub latitude: Option<f64>,
|
||||
pub longitude: Option<f64>,
|
||||
pub altitude_msl_m: Option<f64>,
|
||||
pub fix_quality: Option<u8>,
|
||||
pub satellites_used: Option<u8>,
|
||||
pub satellites_visible: Option<u16>,
|
||||
pub satellites_by_system: Vec<SatelliteCount>,
|
||||
pub hdop: Option<f64>,
|
||||
pub pdop: Option<f64>,
|
||||
pub vdop: Option<f64>,
|
||||
pub speed_kmh: Option<f64>,
|
||||
pub course_deg: Option<f64>,
|
||||
pub utc_time: Option<String>,
|
||||
pub utc_date: Option<String>,
|
||||
pub antenna: Option<Antenna>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub(super) struct SatelliteCount {
|
||||
system: &'static str,
|
||||
count: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub(super) enum Antenna {
|
||||
Ok,
|
||||
Open,
|
||||
Short,
|
||||
}
|
||||
|
||||
type Point = [f64; 2];
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Recent<T> {
|
||||
value: T,
|
||||
at_ms: u64,
|
||||
}
|
||||
|
||||
impl<T> Recent<T> {
|
||||
fn fresh(&self, now: u64) -> Option<&T> {
|
||||
(now.saturating_sub(self.at_ms) <= FRESH_MS).then_some(&self.value)
|
||||
}
|
||||
}
|
||||
|
||||
struct Gga {
|
||||
point: Option<Point>,
|
||||
quality: u8,
|
||||
satellites: Option<u8>,
|
||||
hdop: Option<f64>,
|
||||
altitude_msl_m: Option<f64>,
|
||||
}
|
||||
|
||||
struct Gsa {
|
||||
dimension: u8,
|
||||
dop: [Option<f64>; 3],
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Gnss {
|
||||
peer: Option<IpAddr>,
|
||||
gga: Option<Recent<Gga>>,
|
||||
position: Option<Recent<Option<Point>>>,
|
||||
gsa: [Option<Recent<Gsa>>; 7],
|
||||
visibility: [[Option<Recent<u8>>; 16]; CONSTELLATIONS.len()],
|
||||
motion: Option<Recent<[Option<f64>; 2]>>,
|
||||
time: Option<Recent<String>>,
|
||||
date: Option<Recent<String>>,
|
||||
antenna: Option<Antenna>,
|
||||
}
|
||||
|
||||
impl Gnss {
|
||||
/// Accept only complete, checksummed sentences for the supported fields.
|
||||
pub fn observe(&mut self, bytes: &[u8], peer: Option<IpAddr>, now: u64) -> bool {
|
||||
let Some(body) = checked_body(bytes) else {
|
||||
return false;
|
||||
};
|
||||
let fields: Vec<_> = body.split(',').collect();
|
||||
let field = |i| fields.get(i).copied().unwrap_or("");
|
||||
let header = fields[0];
|
||||
let (talker, sentence) = header.split_at(2);
|
||||
let report = match sentence {
|
||||
"GGA" if fields.len() >= 9 => {
|
||||
let Ok(quality) = field(6).parse() else {
|
||||
return false;
|
||||
};
|
||||
let point = (1..=5)
|
||||
.contains(&quality)
|
||||
.then(|| position(field(2), field(3), field(4), field(5)))
|
||||
.flatten();
|
||||
let altitude_msl_m = if point.is_some() && field(10) == "M" {
|
||||
field(9)
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|v| (-1000.0..=100000.0).contains(v))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Report::Gga(
|
||||
Gga {
|
||||
point,
|
||||
quality,
|
||||
altitude_msl_m,
|
||||
satellites: field(7).parse().ok(),
|
||||
hdop: number(field(8), 999.0),
|
||||
},
|
||||
clock(field(1)),
|
||||
)
|
||||
}
|
||||
"GLL" if matches!(field(6), "A" | "V") => Report::Gll(
|
||||
(field(6) == "A" && gnss_mode(field(7)))
|
||||
.then(|| position(field(1), field(2), field(3), field(4)))
|
||||
.flatten(),
|
||||
clock(field(5)),
|
||||
),
|
||||
"GSA" => {
|
||||
let system = gsa_system(talker, field(18));
|
||||
let reading = match field(2) {
|
||||
"1" => None,
|
||||
"2" | "3" => Some(Gsa {
|
||||
dimension: if field(2) == "3" { 3 } else { 2 },
|
||||
dop: [
|
||||
number(field(15), 999.0),
|
||||
number(field(16), 999.0),
|
||||
number(field(17), 999.0),
|
||||
],
|
||||
}),
|
||||
_ => return false,
|
||||
};
|
||||
Report::Gsa(system, reading)
|
||||
}
|
||||
"GSV" => {
|
||||
let Some(count) = field(3).parse().ok() else {
|
||||
return false;
|
||||
};
|
||||
let Some(total) = field(1).parse::<u8>().ok().filter(|total| *total != 0) else {
|
||||
return false;
|
||||
};
|
||||
if !field(2)
|
||||
.parse::<u8>()
|
||||
.is_ok_and(|page| (1..=total).contains(&page))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let system = match talker {
|
||||
"GP" => 0,
|
||||
"GB" | "BD" => 1,
|
||||
"GL" => 2,
|
||||
"GA" => 3,
|
||||
"GQ" => 4,
|
||||
"GI" => 5,
|
||||
"GN" => 6,
|
||||
_ => return false,
|
||||
};
|
||||
let tail = fields.len() - 4;
|
||||
let signal = match tail % 4 {
|
||||
0 => 0,
|
||||
1 => {
|
||||
let value = field(fields.len() - 1);
|
||||
if value.is_empty() {
|
||||
0
|
||||
} else {
|
||||
let Ok(id) = u8::from_str_radix(value, 16) else {
|
||||
return false;
|
||||
};
|
||||
if id >= 16 {
|
||||
return false;
|
||||
}
|
||||
usize::from(id)
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
};
|
||||
Report::Visibility(system, signal, count)
|
||||
}
|
||||
"RMC" if matches!(field(2), "A" | "V") => {
|
||||
let valid = field(2) == "A" && gnss_mode(field(12));
|
||||
let point = valid
|
||||
.then(|| position(field(3), field(4), field(5), field(6)))
|
||||
.flatten();
|
||||
let motion = if valid {
|
||||
[
|
||||
number(field(7), 1000.0).map(|knots| knots * 1.852),
|
||||
number(field(8), 360.0),
|
||||
]
|
||||
} else {
|
||||
[None; 2]
|
||||
};
|
||||
Report::Rmc(point, motion, clock(field(1)), rmc_date(field(9)))
|
||||
}
|
||||
"VTG" if fields.len() >= 9 => Report::Motion(if gnss_mode(field(9)) {
|
||||
let speed = number(field(7), 1852.0)
|
||||
.or_else(|| number(field(5), 1000.0).map(|knots| knots * 1.852));
|
||||
[speed, number(field(1), 360.0)]
|
||||
} else {
|
||||
[None; 2]
|
||||
}),
|
||||
"ZDA" if fields.len() >= 5 => {
|
||||
let date = date(field(2), field(3), field(4));
|
||||
let time = clock(field(1));
|
||||
Report::Clock(time, date)
|
||||
}
|
||||
"TXT" => Report::Antenna(match field(4) {
|
||||
"ANTENNA OK" | "ANTSTATUS=OK" => Antenna::Ok,
|
||||
"ANTENNA OPEN" | "ANTSTATUS=OPEN" => Antenna::Open,
|
||||
"ANTENNA SHORT" | "ANTSTATUS=SHORT" => Antenna::Short,
|
||||
_ => return false,
|
||||
}),
|
||||
_ => return false,
|
||||
};
|
||||
|
||||
if self.peer != peer {
|
||||
*self = Self {
|
||||
peer,
|
||||
..Self::default()
|
||||
};
|
||||
}
|
||||
match report {
|
||||
Report::Gga(gga, time) => {
|
||||
self.gga = Some(Recent {
|
||||
value: gga,
|
||||
at_ms: now,
|
||||
});
|
||||
self.update_clock(time, None, now);
|
||||
}
|
||||
Report::Gll(point, time) => {
|
||||
self.position = Some(Recent {
|
||||
value: point,
|
||||
at_ms: now,
|
||||
});
|
||||
self.update_clock(time, None, now);
|
||||
}
|
||||
Report::Gsa(system, reading) => {
|
||||
self.gsa[system] = reading.map(|value| Recent { value, at_ms: now });
|
||||
}
|
||||
Report::Visibility(system, signal, count) => {
|
||||
let signals = &mut self.visibility[system];
|
||||
if signal == 0 {
|
||||
signals.fill(None);
|
||||
} else {
|
||||
signals[0] = None;
|
||||
}
|
||||
signals[signal] = Some(Recent {
|
||||
value: count,
|
||||
at_ms: now,
|
||||
});
|
||||
}
|
||||
Report::Rmc(point, motion, time, date) => {
|
||||
self.position = Some(Recent {
|
||||
value: point,
|
||||
at_ms: now,
|
||||
});
|
||||
self.motion = Some(Recent {
|
||||
value: motion,
|
||||
at_ms: now,
|
||||
});
|
||||
self.update_clock(time, date, now);
|
||||
}
|
||||
Report::Motion(value) => self.motion = Some(Recent { value, at_ms: now }),
|
||||
Report::Clock(time, date) => self.update_clock(time, date, now),
|
||||
Report::Antenna(antenna) => self.antenna = Some(antenna),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn update_clock(&mut self, time: Option<String>, date: Option<String>, now: u64) {
|
||||
if let Some(value) = time {
|
||||
self.time = Some(Recent { value, at_ms: now });
|
||||
}
|
||||
if let Some(value) = date {
|
||||
self.date = Some(Recent { value, at_ms: now });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self, peer: Option<IpAddr>, now: u64) -> Option<Snapshot> {
|
||||
if self.peer != peer {
|
||||
return None;
|
||||
}
|
||||
let gga = self.gga.as_ref().and_then(|reading| reading.fresh(now));
|
||||
let position = gga.map(|reading| reading.point).or_else(|| {
|
||||
self.position
|
||||
.as_ref()
|
||||
.and_then(|reading| reading.fresh(now))
|
||||
.copied()
|
||||
});
|
||||
let point = position.flatten();
|
||||
let gsa = point.and_then(|_| {
|
||||
self.gsa
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|reading| reading.fresh(now).is_some())
|
||||
.max_by_key(|reading| (reading.value.dimension, reading.at_ms))
|
||||
.map(|reading| &reading.value)
|
||||
});
|
||||
let motion = point.and_then(|_| self.motion.as_ref()?.fresh(now));
|
||||
let mut counts: Vec<_> = CONSTELLATIONS
|
||||
.iter()
|
||||
.zip(&self.visibility)
|
||||
.filter_map(|(name, signals)| {
|
||||
let count = signals
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter_map(|value| value.fresh(now))
|
||||
.max()?;
|
||||
Some(SatelliteCount {
|
||||
system: name,
|
||||
count: *count,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A combined GN tally covers the individual constellations already present.
|
||||
if counts.len() > 1 {
|
||||
counts.retain(|count| count.system != "GNSS");
|
||||
}
|
||||
let utc_time = self
|
||||
.time
|
||||
.as_ref()
|
||||
.and_then(|reading| reading.fresh(now))
|
||||
.cloned();
|
||||
let utc_date = self
|
||||
.date
|
||||
.as_ref()
|
||||
.and_then(|reading| reading.fresh(now))
|
||||
.cloned();
|
||||
if position.is_none()
|
||||
&& counts.is_empty()
|
||||
&& utc_time.is_none()
|
||||
&& utc_date.is_none()
|
||||
&& self.antenna.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Snapshot {
|
||||
fix_available: position.map(|fix| fix.is_some()),
|
||||
fix_dimension: gsa.map(|reading| reading.dimension),
|
||||
latitude: point.map(|point| point[0]),
|
||||
longitude: point.map(|point| point[1]),
|
||||
altitude_msl_m: gga.and_then(|reading| reading.altitude_msl_m),
|
||||
fix_quality: gga.map(|reading| reading.quality),
|
||||
satellites_used: gga.and_then(|reading| reading.satellites),
|
||||
satellites_visible: (!counts.is_empty())
|
||||
.then(|| counts.iter().map(|count| u16::from(count.count)).sum()),
|
||||
satellites_by_system: counts,
|
||||
hdop: point.and_then(|_| {
|
||||
gga.and_then(|reading| reading.hdop)
|
||||
.or(gsa.and_then(|reading| reading.dop[1]))
|
||||
}),
|
||||
pdop: gsa.and_then(|reading| reading.dop[0]),
|
||||
vdop: gsa.and_then(|reading| reading.dop[2]),
|
||||
speed_kmh: motion.and_then(|v| v[0]),
|
||||
course_deg: motion.and_then(|v| v[1]),
|
||||
utc_time,
|
||||
utc_date,
|
||||
antenna: self.antenna,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
enum Report {
|
||||
Gga(Gga, Option<String>),
|
||||
Gll(Option<Point>, Option<String>),
|
||||
Gsa(usize, Option<Gsa>),
|
||||
Visibility(usize, usize, u8),
|
||||
Rmc(
|
||||
Option<Point>,
|
||||
[Option<f64>; 2],
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
),
|
||||
Motion([Option<f64>; 2]),
|
||||
Clock(Option<String>, Option<String>),
|
||||
Antenna(Antenna),
|
||||
}
|
||||
|
||||
fn gsa_system(talker: &str, system_id: &str) -> usize {
|
||||
system_id
|
||||
.parse::<usize>()
|
||||
.ok()
|
||||
.filter(|id| (1..=6).contains(id))
|
||||
.unwrap_or(match talker {
|
||||
"GP" => 1,
|
||||
"GL" => 2,
|
||||
"GA" => 3,
|
||||
"GB" | "BD" => 4,
|
||||
"GQ" => 5,
|
||||
"GI" => 6,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn checked_body(bytes: &[u8]) -> Option<&str> {
|
||||
let bytes = bytes.trim_ascii();
|
||||
if bytes.len() > 256 || !bytes.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let line = std::str::from_utf8(bytes).ok()?.strip_prefix('$')?;
|
||||
let (body, checksum) = line.split_once('*')?;
|
||||
if checksum.len() != 2
|
||||
|| body.bytes().fold(0, |xor, b| xor ^ b) != u8::from_str_radix(checksum, 16).ok()?
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (header, _) = body.split_once(',')?;
|
||||
if header.len() != 5 || !header.bytes().all(|c| c.is_ascii_uppercase()) {
|
||||
return None;
|
||||
}
|
||||
Some(body)
|
||||
}
|
||||
|
||||
fn position(lat: &str, ns: &str, lng: &str, ew: &str) -> Option<Point> {
|
||||
fn degrees(value: &str, direction: &str, digits: usize, limit: f64) -> Option<f64> {
|
||||
let (degrees, minutes) = value.split_at_checked(digits)?;
|
||||
if !degrees.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let result = degrees.parse::<u16>().ok().map(f64::from)?
|
||||
+ number(minutes, 60.0).filter(|m| *m < 60.0)? / 60.0;
|
||||
if result > limit {
|
||||
return None;
|
||||
}
|
||||
match (digits, direction) {
|
||||
(2, "N") | (3, "E") => Some(result),
|
||||
(2, "S") | (3, "W") => Some(-result),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Some([degrees(lat, ns, 2, 90.0)?, degrees(lng, ew, 3, 180.0)?])
|
||||
}
|
||||
|
||||
fn number(input: &str, max: f64) -> Option<f64> {
|
||||
input
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|value| (0.0..=max).contains(value))
|
||||
}
|
||||
|
||||
fn gnss_mode(mode: &str) -> bool {
|
||||
matches!(mode, "" | "A" | "D" | "F" | "R" | "P")
|
||||
}
|
||||
|
||||
fn clock(raw: &str) -> Option<String> {
|
||||
let (whole, fraction) = raw.split_once('.').unwrap_or((raw, ""));
|
||||
if whole.len() != 6
|
||||
|| !whole
|
||||
.bytes()
|
||||
.chain(fraction.bytes())
|
||||
.all(|b| b.is_ascii_digit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (hour, minute, second) = (&whole[..2], &whole[2..4], &whole[4..]);
|
||||
if hour > "23" || minute > "59" || second > "60" {
|
||||
return None;
|
||||
}
|
||||
let fraction = if fraction.is_empty() { "" } else { &raw[6..] };
|
||||
Some(format!("{hour}:{minute}:{second}{fraction}"))
|
||||
}
|
||||
|
||||
fn rmc_date(raw: &str) -> Option<String> {
|
||||
if raw.len() != 6 || !raw.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let year: u16 = raw[4..].parse().ok()?;
|
||||
let year = if year >= 80 { 1900 + year } else { 2000 + year };
|
||||
date(&raw[..2], &raw[2..4], &year.to_string())
|
||||
}
|
||||
|
||||
fn date(day: &str, month: &str, year: &str) -> Option<String> {
|
||||
if year.len() != 4 || !year.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let (day, month, year): (u8, u8, u16) =
|
||||
(day.parse().ok()?, month.parse().ok()?, year.parse().ok()?);
|
||||
let limit = match month {
|
||||
2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
|
||||
29
|
||||
}
|
||||
2 => 28,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
||||
_ => return None,
|
||||
};
|
||||
(year > 0 && (1..=limit).contains(&day)).then(|| format!("{year:04}-{month:02}-{day:02}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn feed(gnss: &mut Gnss, body: &str, peer: Option<IpAddr>, now: u64) {
|
||||
let checksum = body.bytes().fold(0, |xor, b| xor ^ b);
|
||||
let packet = format!("${body}*{checksum:02X}\r\n");
|
||||
assert!(gnss.observe(packet.as_bytes(), peer, now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_sample_preserves_zero_satellites_and_no_fix() {
|
||||
let mut gnss = Gnss::default();
|
||||
for line in [
|
||||
"$GNGGA,,,,,,0,00,25.5,,,,,,*64",
|
||||
"$GNGLL,,,,,,V,M*79",
|
||||
"$GNGSA,A,1,,,,,,,,,,,,,25.5,25.5,25.5,1*01",
|
||||
"$GNGSA,A,1,,,,,,,,,,,,,25.5,25.5,25.5,4*04",
|
||||
"$GPGSV,1,1,00,0*65",
|
||||
"$BDGSV,1,1,00,0*74",
|
||||
"$GNRMC,,V,,,,,,,,,,M,V*34",
|
||||
"$GNVTG,,,,,,,,,M*2D",
|
||||
"$GNZDA,,,,,,*56",
|
||||
"$GPTXT,01,01,01,ANTENNA OK*35",
|
||||
] {
|
||||
assert!(gnss.observe(line.as_bytes(), None, 1000), "{line}");
|
||||
}
|
||||
let status = gnss.snapshot(None, 1000).unwrap();
|
||||
assert_eq!(status.fix_available, Some(false));
|
||||
assert_eq!(status.satellites_used, Some(0));
|
||||
assert_eq!(status.satellites_visible, Some(0));
|
||||
assert_eq!(status.satellites_by_system.len(), 2);
|
||||
assert_eq!(status.latitude, None);
|
||||
assert_eq!(status.longitude, None);
|
||||
assert_eq!(status.hdop, None);
|
||||
assert!(matches!(status.antenna, Some(Antenna::Ok)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_fix_is_bounded_and_lost_or_stale_coordinates_disappear() {
|
||||
let mut gnss = Gnss::default();
|
||||
let peer = Some("192.0.2.1".parse().unwrap());
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGSA,A,1,,,,,,,,,,,,,25.5,25.5,25.5,1",
|
||||
peer,
|
||||
999,
|
||||
);
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGGA,121314.50,3112.0000,S,12130.0000,E,1,08,0.9,5.4,M,2.5,M,,",
|
||||
peer,
|
||||
1000,
|
||||
);
|
||||
feed(&mut gnss, "GPGSV,1,1,08,1", peer, 1000);
|
||||
feed(&mut gnss, "GPGSV,1,1,05,2", peer, 1000);
|
||||
feed(&mut gnss, "BDGSV,1,1,03,0", peer, 1000);
|
||||
feed(&mut gnss, "GNZDA,121314.50,18,11,2026,00,00", peer, 1000);
|
||||
feed(&mut gnss, "GNVTG,123.4,T,,M,5.0,N,9.26,K,A", peer, 1000);
|
||||
let status = gnss.snapshot(peer, 1000).unwrap();
|
||||
assert_eq!(status.fix_available, Some(true));
|
||||
assert!((status.latitude.unwrap() + 31.2).abs() < 1e-8);
|
||||
assert_eq!(status.longitude, Some(121.5));
|
||||
assert_eq!(status.altitude_msl_m, Some(5.4));
|
||||
assert_eq!(status.satellites_used, Some(8));
|
||||
assert_eq!(status.satellites_visible, Some(11));
|
||||
assert_eq!(status.hdop, Some(0.9));
|
||||
assert_eq!(status.pdop, None);
|
||||
assert_eq!(status.speed_kmh, Some(9.26));
|
||||
assert_eq!(status.course_deg, Some(123.4));
|
||||
assert_eq!(status.utc_time.as_deref(), Some("12:13:14.50"));
|
||||
assert_eq!(status.utc_date.as_deref(), Some("2026-11-18"));
|
||||
assert!(gnss.snapshot(None, 1000).is_none());
|
||||
assert!(gnss.snapshot(peer, 1000 + FRESH_MS + 1).is_none());
|
||||
assert!(!gnss.observe(b"$GNGGA,,,,,,0,00,25.5,,,,,,*00", peer, 1001));
|
||||
assert_eq!(gnss.snapshot(peer, 1001).unwrap().fix_available, Some(true));
|
||||
feed(&mut gnss, "GNGGA,,,,,,0,00,25.5,,,,,,", peer, 1002);
|
||||
feed(&mut gnss, "GPGSV,1,1,00,0", peer, 1002);
|
||||
feed(&mut gnss, "BDGSV,1,1,00,0", peer, 1002);
|
||||
let lost = gnss.snapshot(peer, 1002).unwrap();
|
||||
assert_eq!(lost.fix_available, Some(false));
|
||||
assert_eq!(lost.latitude, None);
|
||||
assert_eq!(lost.longitude, None);
|
||||
assert_eq!(lost.speed_kmh, None);
|
||||
assert_eq!(lost.satellites_visible, Some(0));
|
||||
assert!(position("3160.0000", "S", "12130.0000", "E").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gsa_tracks_fix_dimension_per_constellation() {
|
||||
let mut gnss = Gnss::default();
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGGA,121314.50,3112.0000,N,12130.0000,E,1,08,0.9,5.4,M,2.5,M,,",
|
||||
None,
|
||||
1000,
|
||||
);
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGSA,A,3,03,10,,,,,,,,,,,1.4,0.9,1.2,1",
|
||||
None,
|
||||
1000,
|
||||
);
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGSA,A,2,04,22,,,,,,,,,,,2.0,1.5,1.3,4",
|
||||
None,
|
||||
1001,
|
||||
);
|
||||
let status = gnss.snapshot(None, 1001).unwrap();
|
||||
assert_eq!(status.fix_dimension, Some(3));
|
||||
assert_eq!(status.pdop, Some(1.4));
|
||||
feed(
|
||||
&mut gnss,
|
||||
"GNGSA,A,1,,,,,,,,,,,,,25.5,25.5,25.5,1",
|
||||
None,
|
||||
1002,
|
||||
);
|
||||
let status = gnss.snapshot(None, 1002).unwrap();
|
||||
assert_eq!(status.fix_dimension, Some(2));
|
||||
assert_eq!(status.pdop, Some(2.0));
|
||||
feed(&mut gnss, "GNGGA,,,,,,0,00,25.5,,,,,,", None, 1003);
|
||||
let status = gnss.snapshot(None, 1003).unwrap();
|
||||
assert_eq!(status.fix_dimension, None);
|
||||
assert_eq!(status.pdop, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
//! One listening socket per local TCP endpoint, with independent stream decoders.
|
||||
use super::{Config, Duration, Format, IpAddr, Receiver, SocketAddr};
|
||||
use super::{device, manager::Registry, nmea};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
io::{self, Cursor},
|
||||
sync::{Arc, Mutex, Weak},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::watch,
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
|
||||
const MAX_CLIENTS: usize = 64;
|
||||
const PROBE_LIMIT: usize = 65_536;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Binding {
|
||||
pub routes: Vec<Route>,
|
||||
pub discovery: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ListenerStatus {
|
||||
listening: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Route {
|
||||
receiver: Receiver,
|
||||
format: Format,
|
||||
source_ip: Option<IpAddr>,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
pub fn new(receiver: Receiver, config: &Config) -> Self {
|
||||
Self {
|
||||
receiver,
|
||||
format: config.format,
|
||||
source_ip: config.peer_ip.map(|address| address.to_canonical()),
|
||||
}
|
||||
}
|
||||
|
||||
fn same(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.receiver.monitor, &other.receiver.monitor)
|
||||
}
|
||||
|
||||
fn status(&self, state: &str, endpoint: SocketAddr, error: Option<&str>) {
|
||||
let mut monitor = self.receiver.monitor.lock().unwrap();
|
||||
monitor.status.state = state.into();
|
||||
monitor.status.endpoint = endpoint.to_string();
|
||||
monitor.status.last_error = error.map(str::to_owned);
|
||||
}
|
||||
}
|
||||
|
||||
fn choose<'a>(
|
||||
routes: &'a [Route],
|
||||
ip: IpAddr,
|
||||
active: &HashMap<tokio::task::Id, Route>,
|
||||
) -> Option<&'a Route> {
|
||||
// Apply explicit source filters before wildcard routes. Peers sharing an IP
|
||||
// use the least occupied matching receiver for the lifetime of the connection.
|
||||
routes
|
||||
.iter()
|
||||
.filter(|route| route.source_ip.is_none_or(|allowed| allowed == ip))
|
||||
.min_by_key(|route| {
|
||||
(
|
||||
route.source_ip.is_none(),
|
||||
active
|
||||
.values()
|
||||
.filter(|current| current.same(route))
|
||||
.count(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn receive(
|
||||
address: SocketAddr,
|
||||
mut routes: watch::Receiver<Binding>,
|
||||
registry: Option<Weak<Registry>>,
|
||||
status: Option<&Mutex<ListenerStatus>>,
|
||||
) -> io::Result<()> {
|
||||
let listener = TcpListener::bind(address).await?;
|
||||
let address = listener.local_addr()?;
|
||||
if let Some(status) = status {
|
||||
*status.lock().unwrap() = ListenerStatus {
|
||||
listening: true,
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
for route in &routes.borrow_and_update().routes {
|
||||
route.status("tcp-listening", address, None);
|
||||
}
|
||||
let mut clients = JoinSet::new();
|
||||
let mut active = HashMap::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
updated = routes.changed() => {
|
||||
if updated.is_err() { return Ok(()); }
|
||||
for route in &routes.borrow_and_update().routes {
|
||||
route.status("tcp-listening", address, None);
|
||||
}
|
||||
}
|
||||
completed = clients.join_next_with_id(), if !clients.is_empty() => {
|
||||
if let Some(completed) = completed {
|
||||
let id = completed.map_or_else(|error| error.id(), |(id, ())| id);
|
||||
active.remove(&id);
|
||||
}
|
||||
}
|
||||
incoming = listener.accept() => {
|
||||
let (mut socket, peer) = incoming?;
|
||||
if clients.len() >= MAX_CLIENTS { continue; }
|
||||
let ip = peer.ip().to_canonical();
|
||||
let binding = routes.borrow();
|
||||
let existing = choose(&binding.routes, ip, &active).cloned();
|
||||
let discovery = registry.as_ref().filter(|_| {
|
||||
existing.as_ref().is_none_or(|route| route.source_ip.is_none() && route.format == Format::RidDeviceJson)
|
||||
&& (binding.discovery || binding.routes.iter().any(|route| route.format == Format::RidDeviceJson))
|
||||
});
|
||||
drop(binding);
|
||||
if let Some(registry) = discovery.cloned() {
|
||||
let subscription = routes.clone();
|
||||
clients.spawn(async move {
|
||||
let Ok(Some(prefix)) = tokio::time::timeout(Duration::from_secs(8), probe(&mut socket)).await else { return; };
|
||||
let Some(registry) = registry.upgrade() else { return; };
|
||||
// A disconnect must not cancel a registry write between persisting and activating it.
|
||||
let write = tokio::spawn(async move { registry.discover(address, ip).await });
|
||||
if let Ok(Some(route)) = write.await {
|
||||
serve(Cursor::new(prefix).chain(socket), route, subscription, ip).await;
|
||||
}
|
||||
});
|
||||
} else if let Some(route) = existing {
|
||||
let handle = clients.spawn(serve(socket, route.clone(), routes.clone(), ip));
|
||||
active.insert(handle.id(), route);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
stream: impl AsyncRead + Unpin,
|
||||
route: Route,
|
||||
mut subscription: watch::Receiver<Binding>,
|
||||
ip: IpAddr,
|
||||
) {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = subscription.wait_for(|binding| !binding.routes.iter().any(|member| member.same(&route))) => {},
|
||||
_ = route.receiver.stream(stream, route.format, Some(Duration::from_secs(30)), Some(ip)) => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn recognized(line: &[u8]) -> bool {
|
||||
let line = line.trim_ascii();
|
||||
if line.starts_with(b"$") {
|
||||
return nmea::Gnss::default().observe(line, None, 0);
|
||||
}
|
||||
let mut sequence = 0;
|
||||
device::decode(line, 0, &mut sequence).is_ok_and(|frame| match frame.kind {
|
||||
device::FrameKind::Heartbeat => true,
|
||||
device::FrameKind::Data => frame.invalid_targets == 0 || !frame.observations.is_empty(),
|
||||
device::FrameKind::Ignored => false,
|
||||
})
|
||||
}
|
||||
|
||||
async fn probe(socket: &mut TcpStream) -> Option<Vec<u8>> {
|
||||
let mut prefix = Vec::new();
|
||||
let mut packet = [0; 4096];
|
||||
let mut checked = 0;
|
||||
while prefix.len() < PROBE_LIMIT {
|
||||
let available = packet.len().min(PROBE_LIMIT - prefix.len());
|
||||
let len = socket.read(&mut packet[..available]).await.ok()?;
|
||||
if len == 0 {
|
||||
return recognized(&prefix[checked..]).then_some(prefix);
|
||||
}
|
||||
prefix.extend_from_slice(&packet[..len]);
|
||||
while let Some(end) = prefix[checked..].iter().position(|&byte| byte == b'\n') {
|
||||
let end = checked + end;
|
||||
if recognized(&prefix[checked..end]) {
|
||||
return Some(prefix);
|
||||
}
|
||||
checked = end + 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct Listener {
|
||||
routes: watch::Sender<Binding>,
|
||||
task: JoinHandle<()>,
|
||||
status: Arc<Mutex<ListenerStatus>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Listeners(BTreeMap<SocketAddr, Listener>);
|
||||
|
||||
impl Listeners {
|
||||
pub fn discovery_status(&self, address: SocketAddr) -> (bool, Option<String>) {
|
||||
self.0.get(&address).map_or((false, None), |listener| {
|
||||
let status = listener.status.lock().unwrap();
|
||||
(status.listening, status.error.clone())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_route(&mut self, address: SocketAddr, route: Route) {
|
||||
if let Some(listener) = self.0.get(&address) {
|
||||
listener
|
||||
.routes
|
||||
.send_modify(|binding| binding.routes.push(route));
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn replace(
|
||||
&mut self,
|
||||
desired: BTreeMap<SocketAddr, Binding>,
|
||||
registry: Weak<Registry>,
|
||||
) {
|
||||
for (address, listener) in std::mem::take(&mut self.0) {
|
||||
if desired.contains_key(&address) {
|
||||
self.0.insert(address, listener);
|
||||
} else {
|
||||
listener.task.abort();
|
||||
let _ = listener.task.await;
|
||||
}
|
||||
}
|
||||
for (address, routes) in desired {
|
||||
if let Some(listener) = self.0.get(&address) {
|
||||
listener.routes.send_replace(routes);
|
||||
} else {
|
||||
let (routes, active) = watch::channel(routes);
|
||||
let registry = registry.clone();
|
||||
let status = Arc::new(Mutex::new(ListenerStatus::default()));
|
||||
let task_status = status.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
while active.has_changed().is_ok() {
|
||||
let Err(error) = receive(
|
||||
address,
|
||||
active.clone(),
|
||||
Some(registry.clone()),
|
||||
Some(&task_status),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let error = match error.kind() {
|
||||
io::ErrorKind::AddrNotAvailable => format!(
|
||||
"监听失败:{} 不是本机网卡地址,请修改监听 IP",
|
||||
address.ip()
|
||||
),
|
||||
io::ErrorKind::AddrInUse => {
|
||||
format!("监听失败:{address} 已被占用,请检查端口")
|
||||
}
|
||||
io::ErrorKind::PermissionDenied => {
|
||||
format!("监听失败:系统拒绝绑定 {address},请检查端口权限")
|
||||
}
|
||||
_ => format!("监听失败:{error}"),
|
||||
};
|
||||
for route in &active.borrow().routes {
|
||||
route.status("disconnected", address, Some(&error));
|
||||
}
|
||||
*task_status.lock().unwrap() = ListenerStatus {
|
||||
listening: false,
|
||||
error: Some(error),
|
||||
};
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
});
|
||||
self.0.insert(
|
||||
address,
|
||||
Listener {
|
||||
routes,
|
||||
task,
|
||||
status,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Observed COM16 UID JSON. Coordinate-system codes have no verified definition yet.
|
||||
use super::device::Decoded;
|
||||
use super::device::{Decoded, FrameKind};
|
||||
use rid_shared::{DeviceTelemetry, Observation};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -59,7 +59,7 @@ pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Dec
|
||||
telemetry: Some(telemetry),
|
||||
}],
|
||||
invalid_targets: 0,
|
||||
ignored: false,
|
||||
kind: FrameKind::Data,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::{
|
||||
target_bindings, target_lists,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::Connection;
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -25,6 +26,45 @@ impl Services {
|
||||
pub async fn close(&self) {
|
||||
self.database.close().await;
|
||||
}
|
||||
pub async fn flight_plans(&self) -> Result<Vec<crate::flight_plans::Plan>> {
|
||||
crate::flight_plans::list(&mut self.database.acquire().await?.db).await
|
||||
}
|
||||
pub async fn save_flight_plan(
|
||||
&self,
|
||||
id: &str,
|
||||
plan: crate::flight_plans::Plan,
|
||||
) -> Result<crate::flight_plans::Plan> {
|
||||
crate::flight_plans::save(&mut self.database.acquire().await?.db, id, plan).await
|
||||
}
|
||||
pub async fn remove_flight_plan(&self, id: &str, revision: u64) -> Result<()> {
|
||||
crate::flight_plans::remove(&mut self.database.acquire().await?.db, id, revision).await
|
||||
}
|
||||
pub async fn review_flight_plan(
|
||||
&self,
|
||||
id: &str,
|
||||
decision: crate::flight_plans::Decision,
|
||||
actor: &str,
|
||||
) -> Result<crate::flight_plans::Plan> {
|
||||
crate::flight_plans::review(&mut self.database.acquire().await?.db, id, decision, actor)
|
||||
.await
|
||||
}
|
||||
pub async fn flight_assessments(
|
||||
&self,
|
||||
observations: &[(rid_shared::Observation, u64)],
|
||||
) -> Result<Vec<crate::flight_plans::Assessment>> {
|
||||
let ids: Vec<_> = observations
|
||||
.iter()
|
||||
.map(|(o, _)| o.target_id.as_str())
|
||||
.collect();
|
||||
let mut store = self.database.acquire().await?;
|
||||
let mut tx = store.db.begin().await?;
|
||||
let policy = crate::flight_plans::Policy::load(&mut tx, &ids).await?;
|
||||
tx.commit().await?;
|
||||
Ok(observations
|
||||
.iter()
|
||||
.map(|(o, time)| policy.evaluate(o, *time))
|
||||
.collect())
|
||||
}
|
||||
pub async fn records(&self, q: &str, page: Option<&str>, size: Option<&str>) -> Result<Value> {
|
||||
let mut store = self.database.acquire().await?;
|
||||
if page.is_some() || size.is_some() {
|
||||
@@ -168,6 +208,12 @@ impl Services {
|
||||
pub async fn binding(&self, id: &str) -> Result<Value> {
|
||||
target_bindings::resolve(&mut self.database.acquire().await?, id).await
|
||||
}
|
||||
pub async fn registration_statuses(
|
||||
&self,
|
||||
ids: &[&str],
|
||||
) -> Result<Vec<target_bindings::RegistrationStatus>> {
|
||||
target_bindings::statuses(&mut self.database.acquire().await?.db, ids).await
|
||||
}
|
||||
pub async fn save_binding(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -195,6 +241,44 @@ impl Services {
|
||||
pub async fn events(&self, params: &HashMap<String, String>) -> Result<Value> {
|
||||
geofences::events(&mut self.database.acquire().await?.db, params).await
|
||||
}
|
||||
pub async fn center_events(
|
||||
&self,
|
||||
params: &HashMap<String, String>,
|
||||
actor: &str,
|
||||
) -> Result<Value> {
|
||||
geofences::center_events(&mut self.database.acquire().await?.db, params, Some(actor)).await
|
||||
}
|
||||
pub async fn dismiss_event(&self, id: i64, actor: &str) -> Result<()> {
|
||||
geofences::dismiss(&mut self.database.acquire().await?.db, id, actor).await
|
||||
}
|
||||
pub async fn acknowledge_event(&self, id: i64, actor: &str) -> Result<()> {
|
||||
geofences::acknowledge(&mut self.database.acquire().await?.db, id, actor).await
|
||||
}
|
||||
pub async fn event_counts(&self, from_ms: i64) -> Result<Value> {
|
||||
let mut store = self.database.acquire().await?;
|
||||
let (total, since): (i64, i64) = sqlx::query_as(
|
||||
"SELECT COUNT(*), COUNT(CASE WHEN occurred_at_ms>=? THEN 1 END) FROM monitoring_events",
|
||||
)
|
||||
.bind(from_ms)
|
||||
.fetch_one(&mut *store.db)
|
||||
.await?;
|
||||
Ok(json!({"total":total,"since":since}))
|
||||
}
|
||||
pub async fn event_rankings(&self, from_ms: i64, to_ms: i64) -> Result<Value> {
|
||||
if from_ms < 0 || from_ms > to_ms {
|
||||
return Err("请检查统计时间范围".into());
|
||||
}
|
||||
let mut store = self.database.acquire().await?;
|
||||
let rows = sqlx::query_as::<_, (String, i64)>(
|
||||
"SELECT event_type, COUNT(*) FROM monitoring_events WHERE occurred_at_ms BETWEEN ? AND ?
|
||||
GROUP BY event_type ORDER BY COUNT(*) DESC,event_type"
|
||||
).bind(from_ms).bind(to_ms).fetch_all(&mut *store.db).await?;
|
||||
let entries = rows
|
||||
.into_iter()
|
||||
.map(|(name, count)| json!({"name":name,"count":count}))
|
||||
.collect::<Vec<_>>();
|
||||
Ok(json!({"entries":entries}))
|
||||
}
|
||||
pub async fn monitor(
|
||||
&self,
|
||||
engine: Option<geofences::Engine>,
|
||||
|
||||
@@ -163,6 +163,7 @@ impl Store {
|
||||
CREATE TABLE IF NOT EXISTS registry_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);")
|
||||
.execute(&mut *self.db).await?;
|
||||
crate::target_bindings::init(&mut self.db).await?;
|
||||
crate::flight_plans::init(&mut self.db).await?;
|
||||
let mut tx = self.db.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let done: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM registry_meta WHERE key='legacy_import_done')",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Explicit RID-to-record associations; classification remains attached to the RID identity.
|
||||
use crate::{error::Result, store::Store};
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
|
||||
@@ -27,18 +27,77 @@ async fn bound(db: &mut SqliteConnection, target: &str) -> Result<Option<String>
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
struct RecordMatch {
|
||||
target_id: String,
|
||||
binding: Option<String>,
|
||||
serial: Option<String>,
|
||||
list_kind: Option<String>,
|
||||
}
|
||||
|
||||
async fn matches(db: &mut SqliteConnection, targets: &[&str]) -> Result<Vec<RecordMatch>> {
|
||||
if targets.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let ids = serde_json::to_string(targets).map_err(|error| error.to_string())?;
|
||||
let rows = sqlx::query_as::<_, (String, Option<String>, Option<String>, Option<String>)>(
|
||||
"SELECT target.value, binding.record_id, record.id, list.list_kind
|
||||
FROM json_each(?1) AS target
|
||||
LEFT JOIN target_record_bindings AS binding ON binding.target_id=target.value
|
||||
LEFT JOIN records AS record ON record.serial_no=target.value COLLATE BINARY
|
||||
AND binding.record_id IS NULL AND substr(target.value,1,4) NOT IN ('MAC-','SRC-')
|
||||
LEFT JOIN target_list_entries AS list ON list.target_id=target.value",
|
||||
)
|
||||
.bind(ids)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(target_id, binding, serial, list_kind)| RecordMatch {
|
||||
target_id,
|
||||
binding,
|
||||
serial,
|
||||
list_kind,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RegistrationStatus {
|
||||
pub target_id: String,
|
||||
pub registered: bool,
|
||||
pub record_id: Option<String>,
|
||||
pub list_kind: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn statuses(
|
||||
db: &mut SqliteConnection,
|
||||
targets: &[&str],
|
||||
) -> Result<Vec<RegistrationStatus>> {
|
||||
Ok(matches(db, targets)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|row| RegistrationStatus {
|
||||
target_id: row.target_id,
|
||||
registered: row.binding.is_some() || row.serial.is_some(),
|
||||
record_id: row.binding.or(row.serial),
|
||||
list_kind: row.list_kind,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn resolve(store: &mut Store, target: &str) -> Result<Value> {
|
||||
validate(target)?;
|
||||
let binding = bound(&mut store.db, target).await?;
|
||||
let automatic: Option<String> =
|
||||
if binding.is_none() && !target.starts_with("MAC-") && !target.starts_with("SRC-") {
|
||||
sqlx::query_scalar("SELECT id FROM records WHERE serial_no=?1 COLLATE BINARY")
|
||||
.bind(target)
|
||||
.fetch_optional(&mut *store.db)
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let matched = matches(&mut store.db, &[target])
|
||||
.await?
|
||||
.pop()
|
||||
.ok_or_else(|| crate::error::AppError::Internal("缺少目标登记匹配结果".into()))?;
|
||||
let RecordMatch {
|
||||
binding,
|
||||
serial: automatic,
|
||||
..
|
||||
} = matched;
|
||||
let record = if let Some(id) = binding.as_ref().or(automatic.as_ref()) {
|
||||
Some(crate::archive::public(store.get(id).await?))
|
||||
} else {
|
||||
|
||||
@@ -403,6 +403,76 @@ async fn http_status_codes_and_error_redaction() {
|
||||
assert_eq!(response.status(), 404);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_module_requires_login_and_is_the_only_frameable_page() {
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{Request, StatusCode, header},
|
||||
middleware,
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let services = crate::services::Services::open(
|
||||
root.path().to_owned(),
|
||||
&crate::config::SqliteConfig::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth = crate::auth::Auth::open(root.path()).await.unwrap();
|
||||
let app = crate::http::router(services)
|
||||
.merge(auth.router())
|
||||
.layer(middleware::from_fn_with_state(auth, crate::auth::protect));
|
||||
let module = "/workbench/module.html";
|
||||
let request = |path, cookie: &str| {
|
||||
Request::builder()
|
||||
.uri(path)
|
||||
.header(header::HOST, "127.0.0.1:8787")
|
||||
.header(header::COOKIE, cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
app.clone()
|
||||
.oneshot(request(module, ""))
|
||||
.await
|
||||
.unwrap()
|
||||
.status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
let setup = Request::post("/api/auth/setup")
|
||||
.header(header::HOST, "127.0.0.1:8787")
|
||||
.header(header::ORIGIN, "http://127.0.0.1:8787")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(
|
||||
r#"{"username":"module-test","password":"local-test-only"}"#,
|
||||
))
|
||||
.unwrap();
|
||||
let setup = app.clone().oneshot(setup).await.unwrap();
|
||||
assert_eq!(setup.status(), StatusCode::OK);
|
||||
let cookie = setup.headers()[header::SET_COOKIE]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap();
|
||||
|
||||
for (path, ancestor) in [
|
||||
(module, "'self'"),
|
||||
("/workbench/platform.html", "'none'"),
|
||||
("/?app=register", "'none'"),
|
||||
] {
|
||||
let response = app.clone().oneshot(request(path, cookie)).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert!(
|
||||
response.headers()[header::CONTENT_SECURITY_POLICY]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.contains(&format!("frame-ancestors {ancestor}"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn locked_backup_retains_delete_intent_until_retry() {
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Persistent settings and local model lookup used by the map workbench.
|
||||
use crate::{
|
||||
config::SqliteConfig,
|
||||
error::{AppError, Result},
|
||||
};
|
||||
use axum::{
|
||||
Extension, Json, Router,
|
||||
extract::{DefaultBodyLimit, Path, State},
|
||||
http::StatusCode,
|
||||
routing::{get, put},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{
|
||||
Row, SqlitePool,
|
||||
sqlite::{SqliteConnectOptions, SqlitePoolOptions},
|
||||
};
|
||||
use std::{path::Path as FsPath, time::Duration};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Workbench(SqlitePool);
|
||||
|
||||
impl Workbench {
|
||||
pub async fn open(root: &FsPath, config: &SqliteConfig) -> Result<Self> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(root.join("registry/data/workbench.sqlite"))
|
||||
.create_if_missing(true)
|
||||
.busy_timeout(Duration::from_millis(config.busy_timeout_ms));
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
sqlx::raw_sql(
|
||||
"CREATE TABLE IF NOT EXISTS platform_settings(
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), name TEXT NOT NULL,
|
||||
sound INTEGER NOT NULL, flash INTEGER NOT NULL, revision INTEGER NOT NULL
|
||||
);
|
||||
INSERT OR IGNORE INTO platform_settings(id,name,sound,flash,revision) VALUES(1,'RID侦测平台',1,1,0);
|
||||
CREATE TABLE IF NOT EXISTS platform_alarm_settings(
|
||||
id INTEGER PRIMARY KEY CHECK(id=1),
|
||||
flash_seconds INTEGER NOT NULL CHECK(flash_seconds BETWEEN 1 AND 60)
|
||||
);
|
||||
INSERT OR IGNORE INTO platform_alarm_settings VALUES(1,10);
|
||||
CREATE TABLE IF NOT EXISTS workbench_views(
|
||||
username TEXT PRIMARY KEY, camera TEXT,
|
||||
cleared_alarm_id INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS model_rules(
|
||||
id INTEGER PRIMARY KEY, field TEXT NOT NULL, pattern TEXT NOT NULL COLLATE NOCASE,
|
||||
vendor TEXT NOT NULL, model TEXT NOT NULL, note TEXT NOT NULL, enabled INTEGER NOT NULL,
|
||||
UNIQUE(field,pattern)
|
||||
);"
|
||||
).execute(&pool).await?;
|
||||
Ok(Self(pool))
|
||||
}
|
||||
|
||||
pub async fn close(&self) {
|
||||
self.0.close().await;
|
||||
}
|
||||
|
||||
pub fn router(&self) -> Router {
|
||||
Router::new()
|
||||
.route("/api/workbench/branding", get(branding))
|
||||
.route("/api/workbench/settings", get(settings).put(save_settings))
|
||||
.route("/api/workbench/view", get(view).put(save_view))
|
||||
.route("/api/workbench/models", get(models).post(create_model))
|
||||
.route(
|
||||
"/api/workbench/models/{id}",
|
||||
put(update_model).delete(delete_model),
|
||||
)
|
||||
.layer(DefaultBodyLimit::max(8192))
|
||||
.with_state(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct Camera {
|
||||
lat: f64,
|
||||
lng: f64,
|
||||
zoom: f64,
|
||||
pitch: f64,
|
||||
bearing: f64,
|
||||
mode3d: bool,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct View {
|
||||
camera: Option<Camera>,
|
||||
cleared_alarm_id: Option<i64>,
|
||||
}
|
||||
|
||||
async fn read_view(db: &SqlitePool, username: &str) -> Result<View> {
|
||||
let row = sqlx::query_as::<_, (Option<String>, i64)>(
|
||||
"SELECT camera,cleared_alarm_id FROM workbench_views WHERE username=?",
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
match row {
|
||||
Some((camera, cleared)) => Ok(View {
|
||||
camera: camera
|
||||
.map(|value| serde_json::from_str(&value))
|
||||
.transpose()
|
||||
.map_err(|error| AppError::Internal(error.to_string()))?,
|
||||
cleared_alarm_id: Some(cleared),
|
||||
}),
|
||||
None => Ok(View::default()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_view(db: &SqlitePool, username: &str, input: View) -> Result<View> {
|
||||
if input
|
||||
.cleared_alarm_id
|
||||
.is_some_and(|id| !(0..=9_007_199_254_740_991).contains(&id))
|
||||
{
|
||||
return Err("告警游标无效".into());
|
||||
}
|
||||
if let Some(camera) = &input.camera {
|
||||
if ![
|
||||
camera.lat,
|
||||
camera.lng,
|
||||
camera.zoom,
|
||||
camera.pitch,
|
||||
camera.bearing,
|
||||
]
|
||||
.iter()
|
||||
.all(|v| v.is_finite())
|
||||
|| !(-90.0..=90.0).contains(&camera.lat)
|
||||
|| !(-180.0..=180.0).contains(&camera.lng)
|
||||
|| !(0.0..=24.0).contains(&camera.zoom)
|
||||
|| !(0.0..=70.0).contains(&camera.pitch)
|
||||
|| !(-180.0..=180.0).contains(&camera.bearing)
|
||||
{
|
||||
return Err("地图视角参数无效".into());
|
||||
}
|
||||
}
|
||||
let camera = input
|
||||
.camera
|
||||
.map(|camera| serde_json::to_string(&camera))
|
||||
.transpose()
|
||||
.map_err(|error| AppError::Internal(error.to_string()))?;
|
||||
sqlx::query(
|
||||
"INSERT INTO workbench_views(username,camera,cleared_alarm_id) VALUES(?,?,?)
|
||||
ON CONFLICT(username) DO UPDATE SET camera=COALESCE(excluded.camera,workbench_views.camera),
|
||||
cleared_alarm_id=MAX(workbench_views.cleared_alarm_id,excluded.cleared_alarm_id)",
|
||||
)
|
||||
.bind(username)
|
||||
.bind(camera)
|
||||
.bind(input.cleared_alarm_id.unwrap_or(0))
|
||||
.execute(db)
|
||||
.await?;
|
||||
read_view(db, username).await
|
||||
}
|
||||
|
||||
async fn view(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
) -> Result<Json<View>> {
|
||||
Ok(Json(read_view(&db, &actor.0).await?))
|
||||
}
|
||||
|
||||
async fn save_view(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Extension(actor): Extension<crate::auth::Actor>,
|
||||
Json(input): Json<View>,
|
||||
) -> Result<Json<View>> {
|
||||
Ok(Json(write_view(&db, &actor.0, input).await?))
|
||||
}
|
||||
|
||||
async fn branding(State(Workbench(db)): State<Workbench>) -> Result<Json<Value>> {
|
||||
let name: String = sqlx::query_scalar("SELECT name FROM platform_settings WHERE id=1")
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "name": name })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct Settings {
|
||||
name: String,
|
||||
sound: bool,
|
||||
flash: bool,
|
||||
flash_seconds: Option<i64>,
|
||||
revision: i64,
|
||||
}
|
||||
|
||||
async fn settings(State(Workbench(db)): State<Workbench>) -> Result<Json<Settings>> {
|
||||
let (name, sound, flash, flash_seconds, revision) =
|
||||
sqlx::query_as::<_, (String, bool, bool, i64, i64)>(
|
||||
"SELECT name,sound,flash,flash_seconds,revision FROM platform_settings JOIN platform_alarm_settings USING(id) WHERE id=1",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
Ok(Json(Settings {
|
||||
name,
|
||||
sound,
|
||||
flash,
|
||||
flash_seconds: Some(flash_seconds),
|
||||
revision,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn save_settings(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Json(mut input): Json<Settings>,
|
||||
) -> Result<Json<Settings>> {
|
||||
input.name = field(input.name, 60, true)?;
|
||||
if input.revision < 0 || input.revision == i64::MAX {
|
||||
return Err("配置版本无效,请重新打开配置页面".into());
|
||||
}
|
||||
if input
|
||||
.flash_seconds
|
||||
.is_some_and(|seconds| !(1..=60).contains(&seconds))
|
||||
{
|
||||
return Err("闪屏时长须为 1–60 秒".into());
|
||||
}
|
||||
let mut transaction = db.begin().await?;
|
||||
let result = sqlx::query("UPDATE platform_settings SET name=?,sound=?,flash=?,revision=revision+1 WHERE id=1 AND revision=?")
|
||||
.bind(&input.name).bind(input.sound).bind(input.flash).bind(input.revision).execute(&mut *transaction).await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err("平台配置已在其他窗口修改,请重新打开配置页面".into());
|
||||
}
|
||||
input.flash_seconds = Some(sqlx::query_scalar("UPDATE platform_alarm_settings SET flash_seconds=COALESCE(?,flash_seconds) WHERE id=1 RETURNING flash_seconds")
|
||||
.bind(input.flash_seconds).fetch_one(&mut *transaction).await?);
|
||||
transaction.commit().await?;
|
||||
input.revision += 1;
|
||||
Ok(Json(input))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Rule {
|
||||
field: String,
|
||||
pattern: String,
|
||||
vendor: String,
|
||||
model: String,
|
||||
note: String,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
fn field(value: String, max: usize, required: bool) -> Result<String> {
|
||||
let value = value.trim();
|
||||
if (required && value.is_empty())
|
||||
|| value.chars().count() > max
|
||||
|| value.chars().any(char::is_control)
|
||||
{
|
||||
return Err("请检查必填字段、长度及控制字符".into());
|
||||
}
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
|
||||
async fn models(State(Workbench(db)): State<Workbench>) -> Result<Json<Value>> {
|
||||
let rows = sqlx::query("SELECT id,field,pattern,vendor,model,note,enabled FROM model_rules ORDER BY length(pattern) DESC, id")
|
||||
.fetch_all(&db).await?;
|
||||
let entries = rows
|
||||
.into_iter()
|
||||
.map(|row| -> Result<Value> {
|
||||
Ok(json!({
|
||||
"id":row.try_get::<i64,_>(0)?, "field":row.try_get::<String,_>(1)?,
|
||||
"pattern":row.try_get::<String,_>(2)?, "vendor":row.try_get::<String,_>(3)?,
|
||||
"model":row.try_get::<String,_>(4)?, "note":row.try_get::<String,_>(5)?,
|
||||
"enabled":row.try_get::<bool,_>(6)?
|
||||
}))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(Json(json!({"entries":entries})))
|
||||
}
|
||||
|
||||
async fn save_rule(db: &SqlitePool, id: Option<i64>, mut rule: Rule) -> Result<i64> {
|
||||
if !matches!(rule.field.as_str(), "serial" | "target" | "model") {
|
||||
return Err("请选择 SN 前缀、UAS ID 或上报机型作为匹配字段".into());
|
||||
}
|
||||
let pattern = field(rule.pattern, 80, true)?;
|
||||
rule.pattern = if rule.field == "serial" {
|
||||
if !pattern.bytes().all(|value| value.is_ascii_alphanumeric()) {
|
||||
return Err("SN 前缀只支持英文字母和数字".into());
|
||||
}
|
||||
pattern.to_ascii_uppercase()
|
||||
} else {
|
||||
pattern.to_lowercase()
|
||||
};
|
||||
rule.vendor = field(rule.vendor, 60, false)?;
|
||||
rule.model = field(rule.model, 80, true)?;
|
||||
rule.note = field(rule.note, 200, false)?;
|
||||
let command = match id {
|
||||
Some(_) => {
|
||||
"UPDATE model_rules SET field=?1,pattern=?2,vendor=?3,model=?4,note=?5,enabled=?6 WHERE id=?7 RETURNING id"
|
||||
}
|
||||
None => {
|
||||
"INSERT INTO model_rules(field,pattern,vendor,model,note,enabled) SELECT ?1,?2,?3,?4,?5,?6 WHERE (SELECT count(*) FROM model_rules) < 1000 RETURNING id"
|
||||
}
|
||||
};
|
||||
let mut query = sqlx::query_scalar(command)
|
||||
.bind(rule.field)
|
||||
.bind(rule.pattern)
|
||||
.bind(rule.vendor)
|
||||
.bind(rule.model)
|
||||
.bind(rule.note)
|
||||
.bind(rule.enabled);
|
||||
if let Some(id) = id {
|
||||
query = query.bind(id);
|
||||
}
|
||||
match query.fetch_optional(db).await {
|
||||
Ok(Some(id)) => Ok(id),
|
||||
Ok(None) if id.is_some() => Err(AppError::NotFound("型号规则不存在")),
|
||||
Ok(None) => Err("型号规则已达 1000 条".into()),
|
||||
Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
|
||||
Err("同一字段已存在该关键词".into())
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
async fn create_model(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Json(rule): Json<Rule>,
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(json!({"id":save_rule(&db, None, rule).await?})))
|
||||
}
|
||||
async fn update_model(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Path(id): Path<i64>,
|
||||
Json(rule): Json<Rule>,
|
||||
) -> Result<Json<Value>> {
|
||||
Ok(Json(json!({"id":save_rule(&db, Some(id), rule).await?})))
|
||||
}
|
||||
async fn delete_model(
|
||||
State(Workbench(db)): State<Workbench>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Result<StatusCode> {
|
||||
let result = sqlx::query("DELETE FROM model_rules WHERE id=?")
|
||||
.bind(id)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(AppError::NotFound("型号规则不存在"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn personal_view_survives_restart_and_independent_updates() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(root.path().join("registry/data")).unwrap();
|
||||
let config = SqliteConfig::default();
|
||||
let store = Workbench::open(root.path(), &config).await.unwrap();
|
||||
let camera = Camera {
|
||||
lat: 41.01,
|
||||
lng: 117.9,
|
||||
zoom: 16.5,
|
||||
pitch: 35.,
|
||||
bearing: 45.,
|
||||
mode3d: true,
|
||||
};
|
||||
write_view(
|
||||
&store.0,
|
||||
"alice",
|
||||
View {
|
||||
camera: Some(camera),
|
||||
cleared_alarm_id: Some(20),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
write_view(
|
||||
&store.0,
|
||||
"alice",
|
||||
View {
|
||||
camera: None,
|
||||
cleared_alarm_id: Some(19),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(read_view(&store.0, "bob").await.unwrap().camera.is_none());
|
||||
store.close().await;
|
||||
let reopened = Workbench::open(root.path(), &config).await.unwrap();
|
||||
let saved = read_view(&reopened.0, "alice").await.unwrap();
|
||||
assert_eq!(saved.cleared_alarm_id, Some(20));
|
||||
let camera = saved.camera.unwrap();
|
||||
assert_eq!(
|
||||
(camera.lat, camera.lng, camera.pitch, camera.bearing),
|
||||
(41.01, 117.9, 35., 45.)
|
||||
);
|
||||
let invalid = View {
|
||||
camera: Some(Camera { lat: 91., ..camera }),
|
||||
cleared_alarm_id: Some(30),
|
||||
};
|
||||
assert!(write_view(&reopened.0, "alice", invalid).await.is_err());
|
||||
assert_eq!(
|
||||
read_view(&reopened.0, "alice")
|
||||
.await
|
||||
.unwrap()
|
||||
.cleared_alarm_id,
|
||||
Some(20)
|
||||
);
|
||||
reopened.close().await;
|
||||
}
|
||||
}
|
||||