```
feat(realtime): 多源观测追踪与启动配置文件支持 - 协议版本升至 3,Target 新增 sources 字段保留各接收器独立观测 - Store 改为按接收器维护 SourceObservation,基于 received_at_ms 独立执行 TTL 过期,过期后自动 refresh 选取最新有效位置 - refresh() 按时间排序源观测,优先选取有坐标的最近记录 - rid-shared 新增 SourceObservation 结构体 - Observation 验证内联 target_id 规则,长度不超过 192 - DeviceTelemetry 扩展 raw_identity、raw_position、 coordinate_system、position_unverified、relative_height_m - 项目级 config.json 支持版本化配置与 sqlite.busy_timeout_ms, 优先级:环境变量 > config.json > 旧版 maps/config.json - web-worker 传递 sources 与 position_source 至前端 - 首页标题更新为"凌空智巡无人机监测系统" ```
This commit is contained in:
@@ -17,7 +17,11 @@ host/
|
||||
# Runtime map cache and user-supplied offline tiles
|
||||
/maps/
|
||||
/receiver-config.json
|
||||
/config.json
|
||||
/.build.lock
|
||||
|
||||
# 文档目录
|
||||
docs/
|
||||
|
||||
# Multi-receiver runtime configuration
|
||||
/receivers.json
|
||||
|
||||
Generated
+250
@@ -11,6 +11,12 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
@@ -74,6 +80,15 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atoi"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atomic-polyfill"
|
||||
version = "1.0.3"
|
||||
@@ -411,6 +426,21 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
|
||||
dependencies = [
|
||||
"crc-catalog",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc-catalog"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -426,6 +456,21 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-queue"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -485,6 +530,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dotenvy"
|
||||
version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "drain_filter_polyfill"
|
||||
version = "0.1.3"
|
||||
@@ -496,6 +547,9 @@ name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either_of"
|
||||
@@ -594,6 +648,17 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
@@ -643,6 +708,7 @@ dependencies = [
|
||||
"rust_xlsxwriter",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-serial",
|
||||
@@ -703,6 +769,17 @@ dependencies = [
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-intrusive"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"lock_api",
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.34"
|
||||
@@ -851,6 +928,8 @@ version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
dependencies = [
|
||||
"allocator-api2",
|
||||
"equivalent",
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
@@ -883,6 +962,18 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "html-escape"
|
||||
version = "0.2.15"
|
||||
@@ -1584,6 +1675,29 @@ version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
@@ -1846,6 +1960,15 @@ dependencies = [
|
||||
"rid-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
@@ -2363,6 +2486,110 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71"
|
||||
dependencies = [
|
||||
"sqlx-core",
|
||||
"sqlx-macros",
|
||||
"sqlx-sqlite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cfg-if",
|
||||
"crc",
|
||||
"crossbeam-queue",
|
||||
"either",
|
||||
"event-listener",
|
||||
"futures-core",
|
||||
"futures-intrusive",
|
||||
"futures-io",
|
||||
"futures-util",
|
||||
"hashbrown 0.16.1",
|
||||
"hashlink",
|
||||
"indexmap",
|
||||
"log",
|
||||
"memchr",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"sha2",
|
||||
"smallvec",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx-macros"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"sqlx-core",
|
||||
"sqlx-macros-core",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx-macros-core"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"dotenvy",
|
||||
"either",
|
||||
"heck",
|
||||
"hex",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx-core",
|
||||
"sqlx-sqlite",
|
||||
"syn 2.0.119",
|
||||
"tokio",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx-sqlite"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c"
|
||||
dependencies = [
|
||||
"atoi",
|
||||
"flume",
|
||||
"form_urlencoded",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-executor",
|
||||
"futures-intrusive",
|
||||
"futures-util",
|
||||
"libsqlite3-sys",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"sqlx-core",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -2588,6 +2815,17 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-stream"
|
||||
version = "0.1.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.29.0"
|
||||
@@ -2693,9 +2931,21 @@ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
|
||||
@@ -20,6 +20,7 @@ rid-shared = { path = "crates/rid-shared" }
|
||||
realtime-core = { path = "crates/realtime-core" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite-bundled"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
|
||||
@@ -64,6 +64,8 @@ FPV-RID 本地备案登记站,Rust + Axum + SQLite。对应 GitHub 仓库:`z
|
||||
|
||||
前端构建工具:Rust 1.99.1 + wasm32-unknown-unknown、Trunk 0.22.0、wasm-bindgen CLI 0.2.129;本机工具在 `D:/Rust_Contact/util/tools/`。其他机器可安装到 PATH,或通过 RID_TRUNK、RID_WASM_BINDGEN 指定工具绝对路径。前端生成资源不提交 Git,干净 checkout 先运行 cargo xtask web 再运行后端测试。
|
||||
|
||||
天地图与离线资源配置见 [地图资源说明](doc/realtime/platform/api/map-resources.md)。在线密钥通过 TIANDITU_TOKEN 配置在服务器环境中,不能提交到源码。
|
||||
项目启动配置使用数据目录下的 `config.json`,可从 `config.example.json` 复制并填写 `maps.tianditu_token`;填写后重启程序。文件包含密钥,已被 Git 忽略,切勿提交或分享。环境变量 `TIANDITU_TOKEN` 具有最高优先级,旧版 `maps/config.json` 仍兼容;优先级为环境变量、项目配置、旧版配置。地图偏好与接收器设置由界面管理并保存在各自的数据文件,不会被启动配置覆盖。天地图与离线资源配置见 [地图资源说明](doc/realtime/platform/api/map-resources.md)。
|
||||
|
||||
配置当前版本为 `1`;省略 `version` 兼容现有配置。`sqlite.busy_timeout_ms` 是 SQLite 遇锁时的等待时间,范围 1–60000 毫秒,默认 5000;数据库位置保持为数据目录下的 `registry/data/registry.sqlite`。未知字段、无效版本或超出范围会使启动失败,原文件保持不变;修改配置需要重新启动。Redis、MQTT 尚未实现,不能添加对应配置节。
|
||||
|
||||
USB / UDP / TCP 的配置、帧格式及实机边界见 [接收端说明](doc/realtime/platform/api/receiver-transports.md)。配置默认禁用,不自动打开串口;未知厂商格式先使用原始诊断。
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"version": 1,
|
||||
"maps": {
|
||||
"tianditu_token": ""
|
||||
},
|
||||
"sqlite": {
|
||||
"busy_timeout_ms": 5000
|
||||
}
|
||||
}
|
||||
+122
-45
@@ -1,12 +1,12 @@
|
||||
//! Bounded latest-state store, independent of SQLite and archive generation.
|
||||
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, Target};
|
||||
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, SourceObservation, Target};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
type ObservationListener = Box<dyn Fn(&Observation, u64) + Send + Sync>;
|
||||
|
||||
struct Track {
|
||||
target: Target,
|
||||
sources: HashMap<String, (u64, u64)>,
|
||||
sources: HashMap<String, SourceObservation>,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
@@ -19,6 +19,30 @@ pub struct Store {
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
fn refresh(track: &mut Track) {
|
||||
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())
|
||||
.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
|
||||
{
|
||||
track.target.position_generation += 1;
|
||||
}
|
||||
track.target.observation = selected.observation.clone();
|
||||
track.target.received_at_ms = sources.iter().map(|s| s.received_at_ms).max().unwrap_or(0);
|
||||
track.target.sources = sources;
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(capacity: usize, journal_capacity: usize, ttl_ms: u64, epoch: u64) -> Self {
|
||||
assert!(capacity > 0 && journal_capacity > 0 && ttl_ms > 0);
|
||||
@@ -49,62 +73,58 @@ impl Store {
|
||||
self.changes.push_back((self.metrics.sequence, id));
|
||||
}
|
||||
|
||||
/// Multiple receivers use arrival order; no unverified sensor-time fusion is implied.
|
||||
/// Select the latest still-valid position, retaining independent source observations.
|
||||
pub fn apply(&mut self, observation: Observation, now_ms: u64) -> bool {
|
||||
if !observation.validate() {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
let id = observation.target_id.clone();
|
||||
if let Some(track) = self.tracks.get_mut(&id) {
|
||||
if let Some(&(epoch, sequence)) = track.sources.get(&observation.receiver_id) {
|
||||
if observation.source_epoch < epoch
|
||||
|| (observation.source_epoch == epoch && observation.sequence <= sequence)
|
||||
if !self.tracks.contains_key(&id) {
|
||||
if self.tracks.len() >= self.metrics.capacity {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
self.tracks.insert(
|
||||
id.clone(),
|
||||
Track {
|
||||
target: Target {
|
||||
observation: observation.clone(),
|
||||
received_at_ms: now_ms,
|
||||
position_generation: 0,
|
||||
sources: vec![],
|
||||
},
|
||||
sources: HashMap::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let track = self.tracks.get_mut(&id).unwrap();
|
||||
if let Some(old) = track.sources.get(&observation.receiver_id) {
|
||||
let old = &old.observation;
|
||||
if observation.source_epoch < old.source_epoch
|
||||
|| (observation.source_epoch == old.source_epoch
|
||||
&& observation.sequence <= old.sequence)
|
||||
{
|
||||
self.metrics.stale += 1;
|
||||
return false;
|
||||
}
|
||||
} else if track.sources.len() >= 8 {
|
||||
} else if track.sources.len() >= 32 {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
track.sources.insert(
|
||||
observation.receiver_id.clone(),
|
||||
(observation.source_epoch, observation.sequence),
|
||||
);
|
||||
let position_generation = track.target.position_generation
|
||||
+ u64::from(
|
||||
track.target.observation.coordinates().is_some()
|
||||
!= observation.coordinates().is_some(),
|
||||
);
|
||||
track.target = Target {
|
||||
position_generation,
|
||||
observation,
|
||||
received_at_ms: now_ms,
|
||||
};
|
||||
} else {
|
||||
if self.tracks.len() >= self.metrics.capacity {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
let sources = HashMap::from([(
|
||||
observation.receiver_id.clone(),
|
||||
(observation.source_epoch, observation.sequence),
|
||||
)]);
|
||||
self.tracks.insert(
|
||||
id.clone(),
|
||||
Track {
|
||||
target: Target {
|
||||
position_generation: 0,
|
||||
SourceObservation {
|
||||
observation,
|
||||
received_at_ms: now_ms,
|
||||
},
|
||||
sources,
|
||||
},
|
||||
);
|
||||
}
|
||||
track
|
||||
.sources
|
||||
.retain(|_, s| now_ms.saturating_sub(s.received_at_ms) < self.ttl_ms);
|
||||
refresh(track);
|
||||
if let Some(observer) = &self.observer {
|
||||
observer(&self.tracks[&id].target.observation, now_ms);
|
||||
observer(&track.target.observation, now_ms);
|
||||
}
|
||||
self.metrics.accepted += 1;
|
||||
self.changed(id);
|
||||
@@ -112,17 +132,31 @@ impl Store {
|
||||
}
|
||||
|
||||
pub fn expire(&mut self, now_ms: u64) {
|
||||
let expired: Vec<String> = self
|
||||
.tracks
|
||||
.iter()
|
||||
.filter(|(_, t)| now_ms.saturating_sub(t.target.received_at_ms) >= self.ttl_ms)
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
for id in expired {
|
||||
let mut changed = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
for (id, track) in &mut self.tracks {
|
||||
let count = track.sources.len();
|
||||
track
|
||||
.sources
|
||||
.retain(|_, s| now_ms.saturating_sub(s.received_at_ms) < self.ttl_ms);
|
||||
if track.sources.is_empty() {
|
||||
removed.push(id.clone());
|
||||
} else if track.sources.len() != count {
|
||||
refresh(track);
|
||||
if let Some(observer) = &self.observer {
|
||||
observer(&track.target.observation, now_ms);
|
||||
}
|
||||
changed.push(id.clone());
|
||||
}
|
||||
}
|
||||
for id in removed {
|
||||
self.tracks.remove(&id);
|
||||
self.metrics.expired += 1;
|
||||
self.changed(id);
|
||||
}
|
||||
for id in changed {
|
||||
self.changed(id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(&self, since: Option<u64>, now_ms: u64) -> Frame {
|
||||
@@ -176,6 +210,49 @@ impl Store {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn independent_sources_select_valid_position_fallback_expire_and_break_trails() {
|
||||
let mut store = Store::new(10, 100, 30, 1);
|
||||
let mut a = sample("same", 1);
|
||||
a.receiver_id = "a".into();
|
||||
let mut b = a.clone();
|
||||
b.receiver_id = "b".into();
|
||||
b.longitude = Some(121.);
|
||||
assert!(store.apply(a.clone(), 0));
|
||||
assert!(store.apply(b.clone(), 5));
|
||||
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");
|
||||
let generation = frame.targets[0].position_generation;
|
||||
a.sequence = 2;
|
||||
a.longitude = None;
|
||||
a.latitude = None;
|
||||
assert!(store.apply(a.clone(), 10));
|
||||
assert_eq!(
|
||||
store.frame(None, 10).targets[0].observation.receiver_id,
|
||||
"b"
|
||||
);
|
||||
b.sequence = 2;
|
||||
b.longitude = None;
|
||||
b.latitude = None;
|
||||
assert!(store.apply(b, 11));
|
||||
assert!(
|
||||
store.frame(None, 11).targets[0]
|
||||
.observation
|
||||
.coordinates()
|
||||
.is_none()
|
||||
);
|
||||
a.sequence = 3;
|
||||
a.longitude = Some(120.);
|
||||
a.latitude = Some(30.);
|
||||
assert!(store.apply(a, 15));
|
||||
assert!(store.frame(None, 15).targets[0].position_generation > generation);
|
||||
store.expire(41);
|
||||
assert_eq!(store.frame(None, 41).targets[0].sources.len(), 1);
|
||||
store.expire(45);
|
||||
assert!(store.frame(None, 45).targets.is_empty());
|
||||
}
|
||||
fn sample(id: &str, sequence: u64) -> Observation {
|
||||
Observation {
|
||||
target_id: id.into(),
|
||||
|
||||
@@ -5,7 +5,7 @@ pub mod geofences;
|
||||
pub mod map_settings;
|
||||
pub mod target_lists;
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 2;
|
||||
pub const PROTOCOL_VERSION: u16 = 3;
|
||||
pub const MAX_BATCH: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
@@ -36,7 +36,7 @@ impl Observation {
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
identity(&self.target_id)
|
||||
target_lists::valid_target_id(&self.target_id)
|
||||
&& identity(&self.receiver_id)
|
||||
&& match (self.longitude, self.latitude) {
|
||||
(None, None) => true,
|
||||
@@ -57,8 +57,15 @@ impl Observation {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct SourceObservation {
|
||||
pub observation: Observation,
|
||||
pub received_at_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Target {
|
||||
pub sources: Vec<SourceObservation>,
|
||||
pub observation: Observation,
|
||||
pub received_at_ms: u64,
|
||||
/// Changes on every position availability transition, even between coalesced frames.
|
||||
@@ -90,6 +97,11 @@ pub struct Metrics {
|
||||
/// Fields reported by the device; height reference systems are never interchanged.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub struct DeviceTelemetry {
|
||||
pub raw_identity: Option<String>,
|
||||
pub raw_position: Option<[f64; 2]>,
|
||||
pub coordinate_system: Option<i64>,
|
||||
pub position_unverified: bool,
|
||||
pub relative_height_m: Option<f64>,
|
||||
pub serial: Option<String>,
|
||||
pub mac: Option<String>,
|
||||
pub model: Option<String>,
|
||||
|
||||
@@ -37,7 +37,7 @@ pub struct Mutation {
|
||||
|
||||
pub fn valid_target_id(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& (value.len() <= 64 || (value.starts_with("SRC-") && value.len() <= 192))
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
|
||||
@@ -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"></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></head><body></body></html>
|
||||
|
||||
@@ -10,10 +10,11 @@ let centered=false, workerWasmBytes=0, resizeObserver;
|
||||
let basemap="imagery",tileRevision=0,mapCreations=0;
|
||||
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
|
||||
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?v=${tileRevision}`:''}`;}
|
||||
let classification=new Map(),listFilter="all";
|
||||
let classification=new Map(),listFilter="all",sourceIds=null;
|
||||
function setSources(value){sourceIds=value?new Set(Array.from(value)):null;flush();}
|
||||
function targetKind(id){return classification.get(id)||"unknown";}
|
||||
function located(id,i=ids.indexOf(id)){return i>=0&&latest&&Number.isFinite(latest[i*4])&&Number.isFinite(latest[i*4+1]);}
|
||||
function targetVisible(id,i=ids.indexOf(id)){return located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
|
||||
function targetVisible(id,i=ids.indexOf(id)){return (!sourceIds||sourceIds.has(id))&&located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
|
||||
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
|
||||
let occlusion={top:0,right:0,bottom:0,left:0};
|
||||
function shader(gl, type, source) {
|
||||
@@ -145,4 +146,4 @@ function focusCoordinate(center,animate=true){
|
||||
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
|
||||
}
|
||||
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);}
|
||||
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";occlusion={top:0,right:0,bottom:0,left:0};}};
|
||||
window.ridMap={setSources,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.rx-page{max-width:1440px;margin:auto;padding:28px;color:var(--work-text,#dce7f4)}.rx-heading,.rx-toolbar,.rx-drawer-header{display:flex;align-items:center;justify-content:space-between;gap:18px}.rx-heading h1{margin:0;font-size:26px}.rx-heading p,.rx-footnote{color:var(--work-muted,#9eb3c8);line-height:1.7}.rx-toolbar{margin:24px 0;flex-wrap:wrap}.rx-toolbar label{display:flex;align-items:center;gap:12px}.rx-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:18px}.rx-card{border:1px solid var(--work-line,rgba(143,174,203,.24));background:var(--work-panel,rgba(20,39,58,.92));border-radius:14px;padding:22px;min-width:0}.rx-card h2{font-size:19px;margin:0 0 12px;overflow-wrap:anywhere}.rx-card p{overflow-wrap:anywhere}.rx-card .rx-badge{color:#75d8b2}.rx-card .rx-warn,.rx-error{color:#eeb56a}.rx-card .rx-metrics{display:flex;gap:32px;padding:18px 0;border-top:1px solid #7894b32b;margin-top:18px}.rx-metrics strong{display:block;font-size:25px}.rx-metrics span{font-size:12px;color:var(--work-muted,#9eb3c8)}.rx-card .rx-actions{margin-top:12px}.rx-page button,.rx-drawer button{padding:9px 15px;border:1px solid var(--work-line,#546d84);border-radius:8px;background:var(--work-panel,#21364a);color:inherit;cursor:pointer;font:inherit}.rx-page button.primary,.rx-drawer button.primary{background:#255f79;color:#f2faff}.rx-page button:focus-visible,.rx-drawer button:focus-visible,.rx-drawer input:focus-visible,.rx-drawer select:focus-visible{outline:2px solid #70cfe6;outline-offset:3px}.rx-page input,.rx-drawer input,.rx-drawer select{padding:10px 12px;border:1px solid var(--work-line,#53697d);border-radius:7px;background:var(--work-input,#102235);color:var(--work-text,#e4edf8);font:inherit;max-width:100%;min-width:0}.rx-drawer{position:fixed;inset:0 0 0 auto;margin:0;width:min(490px,100vw);height:100dvh;max-height:100dvh;max-width:100vw;border:0;border-left:1px solid #617992;padding:24px;background:var(--work-panel,#14283b);color:var(--work-text,#e4edf8);overflow:auto;box-shadow:-16px 0 60px #0005}.rx-drawer::backdrop{background:#06101d88}.rx-drawer h2{font-size:22px;margin:0}.rx-drawer label{display:flex;flex-direction:column;gap:7px;margin:18px 0}.rx-drawer label.rx-enable{flex-direction:row;align-items:center}.rx-tabs{display:flex;gap:8px;margin-top:24px}.rx-tabs [aria-pressed=true]{background:#255f79;color:#fff}.rx-note{border-left:3px solid #dbb16b;padding:12px;background:#a4772520;line-height:1.65}.rx-actions{display:flex;gap:10px;flex-wrap:wrap}.rx-drawer button:disabled,.rx-page button:disabled{opacity:.55;cursor:not-allowed}.rx-drawer dl{display:grid;grid-template-columns:1fr 1fr;gap:12px;overflow-wrap:anywhere}.rx-drawer dd{margin:0}.rx-drawer pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:#061420;max-height:360px;overflow:auto;color:#d8e7f3;font-size:12px}.rx-page [hidden],.rx-drawer [hidden]{display:none!important}#rx-message{line-height:1.6;color:#e6bb77}@media(max-width:650px){.rx-page{padding:16px}.rx-heading{align-items:flex-start;flex-direction:column}.rx-toolbar label{width:100%;flex-wrap:wrap}.rx-cards{grid-template-columns:1fr}.rx-drawer{padding:20px}}
|
||||
|
||||
.rx-drawer{backdrop-filter:blur(28px)}.theme-white .rx-card .rx-badge{color:#287957}.theme-white .rx-card .rx-warn,.theme-white .rx-error,.theme-white #rx-message{color:#8a5919}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 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',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'};
|
||||
function state(row) {
|
||||
const s=row.status;
|
||||
if(!row.config.enabled)return '未启用';
|
||||
if(s.state==='disconnected')return '连接失败 · 自动重试';
|
||||
if(s.state==='connecting')return '正在连接';
|
||||
if(!s.receivedBytes)return '已连接 · 等待数据';
|
||||
if(Date.now()-(s.lastDataMs||0)>10000)return '连接中 · 暂无新数据';
|
||||
if(row.config.format==='raw')return '接收中 · 原始诊断';
|
||||
if(s.rejectedFrames && !s.decodedFrames)return '收到数据 · 协议不匹配';
|
||||
if(!s.acceptedObservations)return '接收中 · 暂无有效目标';
|
||||
return '接收中 · 已解析目标';
|
||||
}
|
||||
async function api(url,method='GET',body) {
|
||||
const r=await fetch(url,{method,headers:body?{'Content-Type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});
|
||||
const v=await r.json().catch(()=>({}));if(!r.ok)throw new Error(v.error||`请求失败 (${r.status})`);return v;
|
||||
}
|
||||
function el(tag,text,className) {const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(className)e.className=className;return e;}
|
||||
function render(){
|
||||
const focused=document.activeElement?.dataset.rxFocus;
|
||||
const query=$('rx-search').value.trim().toLowerCase();
|
||||
const list=rows.filter(r=>`${r.name} ${r.id} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
|
||||
$('rx-summary').textContent=`${rows.length} 台接收机 · ${rows.filter(r=>r.config.enabled).length} 台已启用`;
|
||||
$('rx-cards').replaceChildren(...list.map(row=>{
|
||||
const c=el('article',undefined,'rx-card');c.append(el('h2',row.name),el('p',state(row),'rx-badge'));
|
||||
c.append(el('p',row.config.transport==='serial'?`${row.config.serialPort||'尚未选择串口'} · ${row.config.baudRate}`:`${row.config.transport.toUpperCase()} · ${row.config.bindIp}:${row.config.port}`));
|
||||
c.append(el('p',protocols[row.config.format]||row.config.format,'rx-footnote'));
|
||||
if(row.status.lastError)c.append(el('p',row.status.lastError,'rx-warn'));
|
||||
if(row.config.format==='uid-json')c.append(el('p','坐标系待核实 · 原始坐标在目标详情中查看','rx-warn'));
|
||||
const metrics=el('div',undefined,'rx-metrics');for(const [label,value] of [['接收字节',row.status.receivedBytes],['接受更新',row.status.acceptedObservations]]){const m=el('div');m.append(el('strong',Number(value).toLocaleString()),el('span',label));metrics.append(m);}c.append(metrics);
|
||||
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');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(actions);return c;
|
||||
}));$('rx-empty').hidden=!!list.length;
|
||||
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-protocol-note').textContent=f.elements.format.value==='uid-json'?'UID 报文中的坐标系代码尚未核实:显示原始坐标,不在地图落点、不参与围栏。':f.elements.format.value==='raw'?'原始诊断只接收字节,不生成无人机目标。':'协议必须与设备实际输出一致;未知报文不会猜测为位置。';}
|
||||
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?[['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无']]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
||||
function open(row){selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config=row?.config||defaults;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 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;}};
|
||||
refresh();setInterval(()=>{if(document.body.dataset.screen==='receivers')refresh();},1500);
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
|
||||
@@ -3,7 +3,6 @@ mod geofences;
|
||||
mod map_settings;
|
||||
mod realtime_layout;
|
||||
mod realtime_ui;
|
||||
mod receiver_ui;
|
||||
mod registry;
|
||||
mod target_binding;
|
||||
mod target_lists;
|
||||
@@ -23,6 +22,7 @@ fn main() {
|
||||
<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")/>
|
||||
<section id="workspace-content" class="workspace-pane">
|
||||
{if realtime { view! { <realtime_ui::Realtime lists=lists/> }.into_any() }
|
||||
else { view! { <Registry/> }.into_any() }}
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Layout {
|
||||
.filter(|v| v.is_finite() && (100.0..=2000.0).contains(v))
|
||||
.unwrap_or(default)
|
||||
};
|
||||
let receiver = boolean("receiver", false);
|
||||
let receiver = false;
|
||||
Self {
|
||||
list: RwSignal::new(boolean("list", true)),
|
||||
detail: RwSignal::new(boolean("detail", true)),
|
||||
|
||||
@@ -150,6 +150,7 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
});
|
||||
let query = RwSignal::new(String::new());
|
||||
let selected = RwSignal::new(String::new());
|
||||
let source_filter = RwSignal::new(String::new());
|
||||
let position = RwSignal::new(None::<[f64; 4]>);
|
||||
let details = RwSignal::new(HashMap::<String, Value>::new());
|
||||
let age = RwSignal::new(0u64);
|
||||
@@ -169,9 +170,35 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
let kinds = classification.get();
|
||||
ids.get()
|
||||
.into_iter()
|
||||
.filter(|id| id.to_lowercase().contains(&q) && filter.matches(kinds.get(id).copied()))
|
||||
.filter(|id| {
|
||||
id.to_lowercase().contains(&q)
|
||||
&& filter.matches(kinds.get(id).copied())
|
||||
&& (source_filter.get().is_empty()
|
||||
|| details.with(|d| {
|
||||
d.get(id)
|
||||
.and_then(|o| o["sources"].as_array())
|
||||
.is_some_and(|sources| {
|
||||
sources.iter().any(|s| {
|
||||
s["observation"]["receiver_id"].as_str()
|
||||
== Some(source_filter.get().as_str())
|
||||
})
|
||||
})
|
||||
}))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
Effect::new(move |_| {
|
||||
let ids = if source_filter.get().is_empty() {
|
||||
JsValue::NULL
|
||||
} else {
|
||||
let values = js_sys::Array::new();
|
||||
for id in filtered.get() {
|
||||
values.push(&id.into());
|
||||
}
|
||||
values.into()
|
||||
};
|
||||
let _ = map_call("setSources", &[ids]);
|
||||
});
|
||||
let visible_page = Memo::new(move |_| {
|
||||
page.get()
|
||||
.min(filtered.get().len().div_ceil(100).max(1) - 1)
|
||||
@@ -544,28 +571,23 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/status")
|
||||
.send()
|
||||
.await
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receivers").send().await
|
||||
&& let Ok(value) = response.json::<Value>().await
|
||||
{
|
||||
let state = match value["state"].as_str().unwrap_or("unknown") {
|
||||
"stopped" => "未启用",
|
||||
"connected" => "已连接",
|
||||
"listening" => "监听中",
|
||||
"connecting" => "连接中",
|
||||
"error" => "异常",
|
||||
other => other,
|
||||
};
|
||||
let entries = value["receivers"].as_array();
|
||||
let count = entries.map_or(0, Vec::len);
|
||||
let enabled = entries.map_or(0, |v| {
|
||||
v.iter().filter(|r| r["config"]["enabled"] == true).count()
|
||||
});
|
||||
receiver.set(format!(
|
||||
"{}接收器 {} · {}",
|
||||
"{}接收机 {} 台 · 已启用 {} 台",
|
||||
if synthetic {
|
||||
"隔离仿真输入 · "
|
||||
} else {
|
||||
""
|
||||
},
|
||||
state,
|
||||
value["endpoint"].as_str().unwrap_or("")
|
||||
count,
|
||||
enabled
|
||||
));
|
||||
}
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/maps/status")
|
||||
@@ -611,8 +633,8 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
<div class="live-panel-head"><h2>"目标目录"</h2><button id="rt-list-manager-from-directory" aria-controls="rt-list-manager" aria-expanded=move||lists.open.get().to_string() title="管理黑白名单" aria-label="管理黑白名单" on:click=move |_|lists.show()>"名单管理"</button><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">
|
||||
<span class="live-data-label rt-status">{move||status.get()}</span>
|
||||
<input class="live-search" aria-label="搜索实时目标" placeholder="搜索目标标识" prop:value=move||query.get() on:input=move|e|{query.set(event_target_value(&e));page.set(0);}/>
|
||||
<span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span><div class="rt-target-list-filters" role="group" aria-label="目标名单筛选">{[Filter::All,Filter::White,Filter::Black,Filter::Unknown].into_iter().map(move |filter|view!{<button type="button" disabled=move||!lists.ready.get() aria-pressed=move||(lists.filter.get()==filter).to_string() on:click=move |_|{lists.filter.set(filter);page.set(0);}>{filter.label()}" "{move||{if !lists.ready.get() && filter!=Filter::All {"—".to_owned()}else{let kinds=classification.get();ids.with(|targets|targets.iter().filter(|id|filter.matches(kinds.get(*id).copied())).count()).to_string()}}}</button>}).collect_view()}</div><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><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();let badge_id=id.clone();let description_id=id.clone();let location_id=id.clone();view!{<button class="rt-target" aria-label=id.clone() aria-description=move||if lists.ready.get(){super::target_lists::label(lists.kind(&description_id))}else{"名单未知"} aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span><span class="rt-target-id"><span class="rt-device-id">{id.clone()}</span><small class="rt-position-state">{move||if details.with(|d|d.get(&location_id).is_some_and(|o|o["longitude"].is_number()&&o["latitude"].is_number())){"已定位"}else{"未定位"}}</small></span><Badge lists=lists target=badge_id/></button>}}).collect_view()}</div>
|
||||
<label class="live-data-label">"接收来源 "<select aria-label="筛选接收来源" prop:value=move||source_filter.get() on:change=move|e|{source_filter.set(event_target_value(&e));page.set(0);}><option value="">"全部来源"</option>{move||{let mut sources=std::collections::BTreeSet::new();details.with(|d|{for o in d.values(){if let Some(items)=o["sources"].as_array(){for s in items {if let Some(id)=s["observation"]["receiver_id"].as_str(){sources.insert(id.to_owned());}}}}});sources.into_iter().map(|id|view!{<option value=id.clone()>{id.clone()}</option>}).collect_view()}}</select></label><span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span><div class="rt-target-list-filters" role="group" aria-label="目标名单筛选">{[Filter::All,Filter::White,Filter::Black,Filter::Unknown].into_iter().map(move |filter|view!{<button type="button" disabled=move||!lists.ready.get() aria-pressed=move||(lists.filter.get()==filter).to_string() on:click=move |_|{lists.filter.set(filter);page.set(0);}>{filter.label()}" "{move||{if !lists.ready.get() && filter!=Filter::All {"—".to_owned()}else{let kinds=classification.get();ids.with(|targets|targets.iter().filter(|id|filter.matches(kinds.get(*id).copied())).count()).to_string()}}}</button>}).collect_view()}</div><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><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();let badge_id=id.clone();let description_id=id.clone();let location_id=id.clone();view!{<button class="rt-target" aria-label=id.clone() aria-description=move||if lists.ready.get(){super::target_lists::label(lists.kind(&description_id))}else{"名单未知"} aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span><span class="rt-target-id"><span class="rt-device-id">{id.clone()}</span><small class="rt-position-state">{move||details.with(|d|position_label(d.get(&location_id)))}</small></span><Badge lists=lists target=badge_id/></button>}}).collect_view()}</div>
|
||||
<p class="live-empty" hidden=move||!filtered.get().is_empty()>{move||if ids.get().is_empty(){"暂无目标。请检查接收器和数据源。"}else{"没有匹配的目标。"}}</p>
|
||||
</div><nav class="pagination"><button disabled=move||{visible_page.get()==0} on:click=move |_|page.set(visible_page.get().saturating_sub(1))>"上一组"</button><span>{move||format!("{} / {}",visible_page.get()+1,filtered.get().len().div_ceil(100).max(1))}</span><button disabled=move||{(visible_page.get()+1)*100>=filtered.get().len()} on:click=move |_|page.set(visible_page.get()+1)>"下一组"</button></nav>
|
||||
</aside>
|
||||
@@ -621,7 +643,7 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
<div class="live-detail-body"><button class="live-back" hidden=move||!layout.compact.get() on:click=move |_|layout.mobile.set(1)>"‹ 返回目标目录"</button>
|
||||
<div class="live-target-heading">{move||if selected.get().is_empty(){"请选择目标".into()}else{selected.get()}}</div>
|
||||
<p class="live-data-label">{move||lookup.get()}</p>
|
||||
<p class="live-data-label" role="status">{move||if selected.get().is_empty(){""}else if position.get().is_some(){"已定位"}else{"已接收 · 未定位"}}</p>
|
||||
<p class="live-data-label" role="status">{move||if selected.get().is_empty(){""}else{details.with(|d|position_label(d.get(&selected.get())))}}</p>
|
||||
<super::target_binding::TargetBinding target=selected record=record lookup=lookup/>
|
||||
<div class="rt-detail-classification" hidden=move||selected.get().is_empty()>{move||view!{<Badge lists=lists target=selected.get()/>}}<p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==selected.get()).map(|entry|entry.note.clone()).unwrap_or_default())}</p><div class="rt-detail-list-actions"><button class="rt-white-action" disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.mark(selected.get_untracked(),ListKind::White)>"加入白名单"</button><button class="rt-black-action" disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.mark(selected.get_untracked(),ListKind::Black)>"加入黑名单"</button><button disabled=move||selected.get().is_empty()||!lists.ready.get()||lists.busy.get() on:click=move |_|lists.edit(selected.get_untracked())>"编辑名单备注"</button></div><p class="rt-list-inline-feedback" role="status" class:error=move||lists.failed.get()>{move||lists.message.get()}</p></div>
|
||||
|
||||
@@ -643,7 +665,7 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
</div>
|
||||
<div class="mc-dock-header"><div class="mc-dock-tabs" role="group" aria-label="底栏内容">
|
||||
<button class="mc-dock-tab" class:active=move||!layout.receiver.get() aria-pressed=move||(!layout.receiver.get()).to_string() on:click=move |_|layout.tab(false)>"目标快照与事件"</button>
|
||||
<button class="mc-dock-tab" class:active=move||layout.receiver.get() aria-pressed=move||layout.receiver.get().to_string() on:click=move |_|layout.tab(true)>"接收器与解码"</button>
|
||||
<button class="mc-dock-tab" on:click=move |_|crate::workspace::navigate("receivers")>"设备管理"</button>
|
||||
</div><div class="live-dock-actions"><span class="mc-dock-substatus">{move||receiver.get()}</span>
|
||||
<button aria-label="切换底栏高度" title="紧凑或展开底栏" on:click=move |_|{let max=layout.maximum.get_untracked();layout.set_height(if layout.height.get_untracked()>170.0{170.0}else{max});layout.commit_height();}>"↕"</button>
|
||||
<button aria-label="隐藏事件面板" on:click=move |_|{layout.dock.set(false);layout.save();super::realtime_layout::focus("rt-dock-restore");}>"⌄ 隐藏"</button>
|
||||
@@ -653,7 +675,6 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
<p class="live-data-label" hidden=move||!events.get().is_empty()>"暂无事件,等待实时通道消息。"</p>
|
||||
<ol class="live-events"><For each=move||events.get() key=|event|event.id children=move |event|{let alert=event.message.starts_with("黑名单命中:")||event.message.starts_with("围栏进入:");view!{<li data-alert=alert.to_string() id=format!("rt-event-{}",event.id) data-event-id=event.id><time>{event.time}</time><span>{event.message}</span></li>}}/></ol>
|
||||
</div>
|
||||
<div class="mc-dock-body live-receiver-body" hidden=move||!layout.receiver.get()><Show when=move||layout.mounted.get()><crate::receiver_ui::ReceiverControls expanded=true/></Show></div>
|
||||
</section>
|
||||
<button id="rt-dock-restore" class="live-dock-restore" hidden=move||layout.dock_visible() || (layout.compact.get() && layout.mobile.get()!=0) on:click=move |_|{layout.dock.set(true);layout.save();super::realtime_layout::focus("rt-dock");}>"⌃ 显示事件面板"</button>
|
||||
</div></main>
|
||||
@@ -661,13 +682,13 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
||||
}
|
||||
|
||||
fn device_detail_rows(observation: Option<&Value>) -> Vec<(&'static str, String)> {
|
||||
let Some(t) = observation
|
||||
let t = observation
|
||||
.and_then(|o| o.get("telemetry"))
|
||||
.filter(|t| t.is_object())
|
||||
else {
|
||||
return vec![];
|
||||
};
|
||||
.unwrap_or(&Value::Null);
|
||||
let fields = [
|
||||
("原始标识", "raw_identity", ""),
|
||||
("坐标系代码(未核实)", "coordinate_system", ""),
|
||||
("相对高度(原始)", "relative_height_m", " m"),
|
||||
("设备 SN", "serial", ""),
|
||||
("设备机型", "model", ""),
|
||||
("设备名称", "name", ""),
|
||||
@@ -705,5 +726,45 @@ fn device_detail_rows(observation: Option<&Value>) -> Vec<(&'static str, String)
|
||||
})
|
||||
.unwrap_or_else(|| "—".into());
|
||||
rows.push(("操作者坐标", pilot));
|
||||
if let Some(p) = t["raw_position"].as_array() {
|
||||
rows.push((
|
||||
"原始坐标(未用于地图)",
|
||||
p.iter()
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.map(|n| format!("{n:.7}"))
|
||||
.unwrap_or_else(|| "—".into())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
));
|
||||
}
|
||||
if let Some(o) = observation {
|
||||
rows.push((
|
||||
"定位来源",
|
||||
o["position_source"]
|
||||
.as_str()
|
||||
.unwrap_or("无有效定位")
|
||||
.to_owned(),
|
||||
));
|
||||
if let Some(sources) = o["sources"].as_array() {
|
||||
rows.push((
|
||||
"接收来源",
|
||||
sources
|
||||
.iter()
|
||||
.filter_map(|s| s["observation"]["receiver_id"].as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / "),
|
||||
));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn position_label(observation: Option<&Value>) -> &'static str {
|
||||
match observation {
|
||||
Some(o) if o["longitude"].is_number() && o["latitude"].is_number() => "已定位",
|
||||
Some(o) if o["telemetry"]["position_unverified"] == true => "已接收 · 定位待核实",
|
||||
_ => "已接收 · 未定位",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<div class="rx-page">
|
||||
<header class="rx-heading"><div><h1>设备管理</h1><p>管理接收机连接与解码。无人机目标和地图位于实时工作台默认界面。</p></div><button class="primary" id="rx-add">+ 添加接收机</button></header>
|
||||
<div class="rx-toolbar"><label>查找设备 <input id="rx-search" type="search" placeholder="名称、串口或接收机 ID"></label><span id="rx-summary" role="status">正在加载接收机…</span><button id="rx-refresh">刷新</button></div>
|
||||
<p id="rx-error" class="rx-error" role="alert" hidden></p><div id="rx-cards" class="rx-cards"></div><p id="rx-empty" hidden>没有匹配的接收机。</p>
|
||||
<p class="rx-footnote">切换菜单不停止后台接收。停用、修改连接或删除只影响当前接收机。</p>
|
||||
</div>
|
||||
<dialog id="rx-drawer" class="rx-drawer" aria-labelledby="rx-title">
|
||||
<header class="rx-drawer-header"><h2 id="rx-title">接收机</h2><button id="rx-close" type="button" aria-label="关闭设备详情">×</button></header>
|
||||
<div class="rx-tabs" role="group" aria-label="设备详情内容"><button id="rx-config-tab" type="button" aria-pressed="true">连接配置</button><button id="rx-diagnostic-tab" type="button" aria-pressed="false">接收诊断</button></div>
|
||||
<form id="rx-form"><label>设备名称<input name="name" required maxlength="40"></label><label class="rx-enable"><input type="checkbox" name="enabled">启用此接收机</label>
|
||||
<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>
|
||||
<p id="rx-protocol-note" class="rx-note"></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>
|
||||
<p id="rx-message" role="status"></p>
|
||||
</dialog>
|
||||
File diff suppressed because one or more lines are too long
@@ -328,7 +328,7 @@ fn show(view: &str, realtime: bool) {
|
||||
.and_then(|body| body.get_attribute("data-screen"));
|
||||
let view = match view {
|
||||
"register" | "archives" | "realtime" | "settings" | "display" | "maps" | "geofences"
|
||||
| "target-lists" => view,
|
||||
| "target-lists" | "receivers" => view,
|
||||
_ => "home",
|
||||
};
|
||||
if (view == "realtime" && !realtime) || (matches!(view, "register" | "archives") && realtime) {
|
||||
@@ -350,9 +350,10 @@ fn show(view: &str, realtime: bool) {
|
||||
"workspace-content",
|
||||
matches!(
|
||||
view,
|
||||
"home" | "settings" | "display" | "maps" | "geofences" | "target-lists"
|
||||
"home" | "settings" | "display" | "maps" | "geofences" | "target-lists" | "receivers"
|
||||
),
|
||||
);
|
||||
hidden("receivers-view", view != "receivers");
|
||||
hidden("target-lists-view", view != "target-lists");
|
||||
hidden("geofence-view", view != "geofences");
|
||||
if view == "geofences" {
|
||||
@@ -374,7 +375,7 @@ fn show(view: &str, realtime: bool) {
|
||||
let module = match view {
|
||||
"settings" | "display" | "maps" => "settings",
|
||||
"register" | "archives" => "register",
|
||||
"realtime" | "geofences" | "target-lists" => "realtime",
|
||||
"realtime" | "geofences" | "target-lists" | "receivers" => "realtime",
|
||||
_ => "home",
|
||||
};
|
||||
each("[data-module]", |entry| {
|
||||
@@ -449,6 +450,7 @@ fn show(view: &str, realtime: bool) {
|
||||
"maps" => "地图配置",
|
||||
"geofences" => "电子围栏",
|
||||
"target-lists" => "黑白名单管理",
|
||||
"receivers" => "设备管理",
|
||||
_ => "应用总览",
|
||||
},
|
||||
);
|
||||
@@ -464,7 +466,7 @@ fn show(view: &str, realtime: bool) {
|
||||
.map(|p| match p.as_str() {
|
||||
"display" | "maps" => "settings".to_owned(),
|
||||
"archives" => "register".to_owned(),
|
||||
"geofences" | "target-lists" => "realtime".to_owned(),
|
||||
"geofences" | "target-lists" | "receivers" => "realtime".to_owned(),
|
||||
_ => p,
|
||||
})
|
||||
.filter(|p| p != "home")
|
||||
@@ -622,7 +624,9 @@ pub fn init(realtime: bool) {
|
||||
.and_then(|w| w.location().search().ok())
|
||||
.unwrap_or_default();
|
||||
show(
|
||||
if search.contains("app=target-lists") {
|
||||
if realtime && search.contains("app=receivers") {
|
||||
"receivers"
|
||||
} else if search.contains("app=target-lists") {
|
||||
"target-lists"
|
||||
} else if realtime {
|
||||
"realtime"
|
||||
|
||||
@@ -117,7 +117,14 @@ pub fn connect(url: &str) -> Result<(), JsValue> {
|
||||
}
|
||||
for target in &frame.targets {
|
||||
let o = &target.observation;
|
||||
let detail = serde_json::to_string(o)
|
||||
let mut value = serde_json::to_value(o).unwrap_or_default();
|
||||
value["sources"] = serde_json::to_value(&target.sources).unwrap_or_default();
|
||||
value["position_source"] = if o.coordinates().is_some() {
|
||||
serde_json::json!(o.receiver_id)
|
||||
} else {
|
||||
serde_json::Value::Null
|
||||
};
|
||||
let detail = serde_json::to_string(&value)
|
||||
.ok()
|
||||
.and_then(|s| js_sys::JSON::parse(&s).ok())
|
||||
.unwrap_or(JsValue::NULL);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
## 本机密钥
|
||||
|
||||
在启动程序的环境中配置 `TIANDITU_TOKEN` 为自己的天地图服务端密钥,然后重启程序。无需将密钥发送到聊天中,也不要写进源码、Git 或网页。可以通过 Windows 用户环境变量配置,让下一次启动继承。
|
||||
将项目的 `config.example.json` 复制到数据目录,改名为 `config.json`,在 `maps.tianditu_token` 填写自己的天地图服务端密钥,然后重启程序。实际配置文件不纳入 Git;不要把密钥发送到聊天或网页中。也可以使用启动环境变量 `TIANDITU_TOKEN`,优先级高于项目配置;旧版 `maps/config.json` 仍可使用,优先级最低。配置文件格式或字段无效时程序会报错并保留原文件。
|
||||
|
||||
`GET /api/maps/status` 仅返回 keyConfigured,不返回密钥。上游 URL 和请求错误不写日志,以免其中包含 tk 参数。当前未取得有效密钥,因此天地图真实授权访问尚未实测;自动失败切换和恢复已通过本机受控上游测试。
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
- 点击「保存地图设置」后生效;实时目标地图下次创建时读取此默认位置和底图。打开设置不会重置正在运行的接收器。
|
||||
- 常用区域由用户框选或填写四侧坐标后命名保存,可再次选择;不是内置行政区划数据库。最多 30 个,不支持跨日期变更线的单个范围。
|
||||
|
||||
配置保存在 `--data-root/maps/preferences.json`,不与 `maps/config.json` 的天地图密钥混存。
|
||||
配置保存在 `--data-root/maps/preferences.json`,不与项目启动配置 `config.json` 的天地图密钥混存。
|
||||
采用版本冲突检查,其他窗口保存后旧版本返回 409;重新加载会丢弃当前草稿。
|
||||
损坏配置不自动覆盖,原文件保留等待修复。真实运行数据仍不提交 Git。
|
||||
|
||||
|
||||
@@ -8,13 +8,15 @@ Windows x64 发布包解压后,直接双击 `fpv-rid-registry.exe`,程序启
|
||||
|
||||
默认数据目录是 exe 所在目录,不是命令行当前目录。目录必须可写,不要放在 Program Files。数据库仍为 `registry/data/registry.sqlite`,自动档案仍在 `档案库/`。高级用法:`fpv-rid-registry.exe --data-root "D:\我的备案"`。
|
||||
|
||||
启动配置使用数据目录中的 `config.json`;可从发布包中的 `config.example.json` 复制并按需填写。`version` 当前为 1(旧配置省略时默认为 1);`sqlite.busy_timeout_ms` 控制数据库遇锁等待时间,默认 5000 毫秒,允许 1–60000。未配置文件时采用默认值,错误配置会阻止启动且不会被覆盖。配置变更需重启;实际文件可能包含密钥,不应分享。SQLite 数据库位置仍固定在数据目录内,以保持现有档案及备份规则。Redis 和 MQTT 尚未实现,不支持其配置字段。
|
||||
|
||||
同一时刻只运行一个登记站。默认启动时,如果同版本登记站已运行,再次双击 EXE 会重新打开页面并沿用已有服务,不会创建第二个服务。其他程序占用 8787、指定了 `--data-root` 或使用 `--no-browser` 时仍按端口冲突处理。Rust 版本另外锁定数据目录;旧版 Node 不认识这把锁,因此仍需人工关闭旧版。
|
||||
|
||||
地图框选下载需保留发布包内与主程序同目录的 `rid-map-downloader.exe`,不要只分发主 EXE。目标电脑无需安装 Go 或 Rust。程序优先使用有效的 `RID_MAP_DOWNLOADER` 路径;未设置或指向不存在的文件时,自动使用程序同目录的下载器。源码目录的 `启动Rust版.cmd` 会为本机 Release 版本设置统一工具目录中的下载器路径。
|
||||
|
||||
程序启动时自动创建数据目录中的 `maps/offline/` 文件夹,不需要手动建目录。下载时自动在其中按图层、缩放级别和瓦片坐标创建子目录;再次启动保留已有地图。默认数据目录为 EXE 所在目录;使用 `--data-root` 时保存在指定的数据目录内。
|
||||
|
||||
首次下载未缓存的区域需要联网,并在数据目录的 `maps/config.json` 中配置有效的 `tianditu_token`(或使用启动环境变量 `TIANDITU_TOKEN`)。发布包不包含业务数据或天地图密钥。下载结果保存在数据目录的 `maps/offline/`,下载完成后可离线使用相应区域、图层和层级;失败或取消的任务不代表完整离线覆盖。
|
||||
首次下载未缓存的区域需要联网,并在数据目录的 `config.json` 中配置有效的 `maps.tianditu_token`(也支持启动环境变量 `TIANDITU_TOKEN` 或旧版 `maps/config.json`)。发布包不包含业务数据或天地图密钥。下载结果保存在数据目录的 `maps/offline/`,下载完成后可离线使用相应区域、图层和层级;失败或取消的任务不代表完整离线覆盖。
|
||||
|
||||
## 编辑和照片
|
||||
|
||||
|
||||
+3
-2
@@ -6,7 +6,7 @@ $ridRepo = Split-Path $PSScriptRoot -Parent
|
||||
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', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
|
||||
$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')
|
||||
|
||||
function Assert-CleanDestination {
|
||||
if (Test-Path -LiteralPath $ridDestination) {
|
||||
@@ -20,7 +20,7 @@ function Assert-CleanDestination {
|
||||
}
|
||||
|
||||
function Get-RidSourceManifest {
|
||||
$ridInputs = @('Cargo.toml','Cargo.lock','rust-toolchain.toml','build.rs') | ForEach-Object { Get-Item -LiteralPath (Join-Path $ridRepo $_) }
|
||||
$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 }
|
||||
@($ridInputs | Sort-Object FullName | ForEach-Object { [ordered]@{path=$_.FullName.Substring($ridRepo.Length + 1).Replace('\','/');sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash} })
|
||||
}
|
||||
@@ -51,6 +51,7 @@ try {
|
||||
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')
|
||||
$ridLicenses = cargo tree --workspace --locked --prefix none --format '{p} {l}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Dependency inventory failed' }
|
||||
|
||||
@@ -34,7 +34,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','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') | 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() }
|
||||
|
||||
@@ -42,7 +42,7 @@ try{
|
||||
for(let i=0;i<bytes.length;i+=997)if(!tcp.write(bytes.subarray(i,i+997)))await new Promise(r=>tcp.once('drain',r));
|
||||
tcp.end();await poll(async()=>(await status()).decodedFrames===decoded);
|
||||
let s=await status();assert.equal(s.rejectedFrames,rejected);assert.equal(s.ignoredLines,ignored);assert.equal(s.acceptedObservations,accepted);
|
||||
let frame=await snapshot();assert.equal(frame.version,2);assert.equal(frame.targets.length,identities.size);assert.ok(frame.targets.every(t=>t.observation.longitude===null&&t.observation.latitude===null));
|
||||
let frame=await snapshot();assert.equal(frame.version,3);assert.equal(frame.targets.length,identities.size);assert.ok(frame.targets.every(t=>t.observation.longitude===null&&t.observation.latitude===null));
|
||||
const replay={decoded,rejected,ignored,accepted,targets:frame.targets.length,located:0};
|
||||
// Switch transports and verify release, mixed-entry isolation and position transitions.
|
||||
await save({...config,transport:'udp'});await poll(async()=>(await status()).state==='udp-listening');
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
//! Startup configuration. Mutable user preferences remain in their owning modules.
|
||||
use serde::Deserialize;
|
||||
use std::{io, path::Path};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct Config {
|
||||
version: u32,
|
||||
pub maps: MapConfig,
|
||||
pub sqlite: SqliteConfig,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
maps: MapConfig::default(),
|
||||
sqlite: SqliteConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct MapConfig {
|
||||
pub tianditu_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct SqliteConfig {
|
||||
pub busy_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for SqliteConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
busy_timeout_ms: 5_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn load(root: &Path) -> io::Result<Config> {
|
||||
let path = root.join("config.json");
|
||||
let metadata = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Config::default()),
|
||||
Err(error) => return Err(io::Error::new(error.kind(), "无法读取项目 config.json")),
|
||||
};
|
||||
if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 16384 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"项目 config.json 不是普通文件或超过 16 KiB;原文件已保留",
|
||||
));
|
||||
}
|
||||
let bytes = std::fs::read(path)
|
||||
.map_err(|error| io::Error::new(error.kind(), "无法读取项目 config.json"))?;
|
||||
if bytes.len() > 16384 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"项目 config.json 超过 16 KiB;原文件已保留",
|
||||
));
|
||||
}
|
||||
let config: Config = serde_json::from_slice(&bytes).map_err(|error| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"项目 config.json 格式或字段无效(行 {},列 {});原文件已保留",
|
||||
error.line(),
|
||||
error.column()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
if config.version != 1 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"项目 config.json 的 version 不受支持;当前支持版本 1",
|
||||
));
|
||||
}
|
||||
if !(1..=60_000).contains(&config.sqlite.busy_timeout_ms) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"项目 config.json 的 sqlite.busy_timeout_ms 必须在 1 到 60000 之间",
|
||||
));
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn startup_config_is_optional_validated_and_never_overwritten() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
assert!(load(root.path()).unwrap().maps.tianditu_token.is_none());
|
||||
assert_eq!(load(root.path()).unwrap().sqlite.busy_timeout_ms, 5_000);
|
||||
let path = root.path().join("config.json");
|
||||
std::fs::write(&path, br#"{"maps":{"tianditu_token":"secret"}}"#).unwrap();
|
||||
assert_eq!(
|
||||
load(root.path()).unwrap().maps.tianditu_token.as_deref(),
|
||||
Some("secret")
|
||||
);
|
||||
let invalid = br#"{"maps":{"tianditu_tokn":"secret"}}"#;
|
||||
std::fs::write(&path, invalid).unwrap();
|
||||
assert!(load(root.path()).is_err());
|
||||
assert_eq!(std::fs::read(path).unwrap(), invalid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_version_and_sqlite_settings_without_leaking_values() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join("config.json");
|
||||
std::fs::write(&path, br#"{"version":1,"sqlite":{"busy_timeout_ms":1200}}"#).unwrap();
|
||||
assert_eq!(load(root.path()).unwrap().sqlite.busy_timeout_ms, 1200);
|
||||
for data in [
|
||||
br#"{"version":2}"#.as_slice(),
|
||||
br#"{"sqlite":{"busy_timeout_ms":0}}"#,
|
||||
br#"{"sqlite":{"busy_timeout_ms":60001}}"#,
|
||||
] {
|
||||
std::fs::write(&path, data).unwrap();
|
||||
assert!(load(root.path()).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), data);
|
||||
}
|
||||
std::fs::write(
|
||||
&path,
|
||||
br#"{"maps":{"tianditu_token":"private-secret"},"unknown":true}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
!load(root.path())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("private-secret")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -363,6 +363,7 @@ mod tests {
|
||||
db,
|
||||
&[(o.clone(), time)],
|
||||
&[Target {
|
||||
sources: vec![],
|
||||
position_generation: 0,
|
||||
observation: o,
|
||||
received_at_ms: time,
|
||||
@@ -510,6 +511,7 @@ mod tests {
|
||||
(observation(121.0, 5), 1004),
|
||||
];
|
||||
let active = vec![Target {
|
||||
sources: vec![],
|
||||
position_generation: 0,
|
||||
observation: observation(121.0, 5),
|
||||
received_at_ms: 1004,
|
||||
@@ -524,6 +526,7 @@ mod tests {
|
||||
&mut db,
|
||||
&[],
|
||||
&[Target {
|
||||
sources: vec![],
|
||||
position_generation: 0,
|
||||
observation: observation(120.0, 6),
|
||||
received_at_ms: 1005
|
||||
@@ -565,6 +568,7 @@ mod tests {
|
||||
db.execute_batch("CREATE TRIGGER reject_event BEFORE INSERT ON monitoring_events BEGIN SELECT RAISE(ABORT,'test'); END;").unwrap();
|
||||
let o = observation(120.0, 1);
|
||||
let active = vec![Target {
|
||||
sources: vec![],
|
||||
position_generation: 0,
|
||||
observation: o.clone(),
|
||||
received_at_ms: 1000,
|
||||
|
||||
+64
-7
@@ -7,19 +7,82 @@ use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
extract::{DefaultBodyLimit, Request, State},
|
||||
http::{HeaderValue, StatusCode},
|
||||
http::{HeaderValue, Method, StatusCode},
|
||||
middleware::{self, Next},
|
||||
response::{IntoResponse, Response},
|
||||
routing::any,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn router(worker: Worker) -> Router {
|
||||
Router::new()
|
||||
.route("/api/records", any(records))
|
||||
.fallback(handle)
|
||||
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
|
||||
.layer(middleware::from_fn(headers))
|
||||
.with_state(worker)
|
||||
}
|
||||
// Keep the existing response contract while moving the registry endpoint to an
|
||||
// explicit Axum route. The database worker retains its serialized operations.
|
||||
async fn records(State(worker): State<Worker>, req: Request) -> Response {
|
||||
let method = req.method().clone();
|
||||
if req
|
||||
.headers()
|
||||
.get("origin")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|o| o != "http://127.0.0.1:8787" && o != "http://localhost:8787")
|
||||
{
|
||||
return json_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"error":"只允许从本地登记站访问"}),
|
||||
);
|
||||
}
|
||||
if method == Method::OPTIONS {
|
||||
return StatusCode::NO_CONTENT.into_response();
|
||||
}
|
||||
let params =
|
||||
match axum::extract::Query::<std::collections::HashMap<String, String>>::try_from_uri(
|
||||
req.uri(),
|
||||
) {
|
||||
Ok(q) => q.0,
|
||||
Err(_) => return error("查询参数无效".into()),
|
||||
};
|
||||
let body = if matches!(method, Method::POST | Method::PATCH | Method::PUT) {
|
||||
match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
|
||||
Ok(bytes) => match serde_json::from_slice::<Value>(&bytes) {
|
||||
Ok(value) => value,
|
||||
Err(_) => return error("提交内容不是有效 JSON".into()),
|
||||
},
|
||||
Err(_) => return error("提交内容过大,单张照片最多 5 MB".into()),
|
||||
}
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let result = worker.run(move |s| {
|
||||
if method == Method::GET {
|
||||
let q = params.get("q").map(|s| s.trim()).unwrap_or("");
|
||||
let value = if params.contains_key("page") || params.contains_key("pageSize") {
|
||||
let parse = |key: &str, default: usize| -> Result<usize> {
|
||||
params.get(key).map(|s| s.parse::<usize>().map_err(|_| "分页参数无效".into())).unwrap_or(Ok(default))
|
||||
};
|
||||
s.page(q, parse("page", 1)?, parse("pageSize", 20)?)?
|
||||
} else {
|
||||
json!({"records":s.list(q)?.into_iter().map(archive::public).collect::<Vec<_>>()})
|
||||
};
|
||||
return Ok(json_response(StatusCode::OK, value));
|
||||
}
|
||||
if method == Method::POST {
|
||||
let mut value = s.register(body)?;
|
||||
value["record"] = archive::public(value["record"].take());
|
||||
return Ok(json_response(StatusCode::OK, archive::finish(s, value)));
|
||||
}
|
||||
Ok(json_response(StatusCode::NOT_FOUND, json!({"error":"页面不存在"})))
|
||||
}).await;
|
||||
match result {
|
||||
Ok(response) => response,
|
||||
Err(e) => error(e),
|
||||
}
|
||||
}
|
||||
async fn headers(req: Request, next: Next) -> Response {
|
||||
let mut r = next.run(req).await;
|
||||
for (key, value) in [
|
||||
@@ -180,12 +243,6 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
return Ok(json_response(StatusCode::OK,serde_json::to_value(value).map_err(|e|AppError::Internal(e.to_string()))?));
|
||||
}
|
||||
if method=="GET"&&path=="/api/archive/status"{return Ok(json_response(StatusCode::OK,if s.pending()?.is_some(){json!({"archiveStatus":"pending","warning":"档案或备份待同步,请重试。"})}else{json!({"archiveStatus":"synced"})}));}
|
||||
if method=="GET"&&path=="/api/records"{
|
||||
let q=params.get("q").map(|s|s.trim()).unwrap_or("");
|
||||
let paged=params.contains_key("page")||params.contains_key("pageSize");
|
||||
let value=if paged{let parse=|key:&str,default:usize|->Result<usize>{params.get(key).map(|s|s.parse::<usize>().map_err(|_|"分页参数无效".into())).unwrap_or(Ok(default))};s.page(q,parse("page",1)?,parse("pageSize",20)?)?}else{json!({"records":s.list(q)?.into_iter().map(archive::public).collect::<Vec<_>>()})};return Ok(json_response(StatusCode::OK,value));
|
||||
}
|
||||
if method=="POST"&&path=="/api/records"{let mut v=s.register(body)?;v["record"]=archive::public(v["record"].take());return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
|
||||
if method=="POST"&&path=="/api/archive/retry"{archive::sync(s).map_err(|e|format!("内部错误:档案同步失败:{e}"))?;return Ok(json_response(StatusCode::OK,json!({"archiveStatus":"synced"})))}
|
||||
if method=="POST"&&(path=="/api/export/archive"||path=="/api/export/excel"){
|
||||
let excel=path.ends_with("excel");let records=selected(s,&body)?;let bytes=archive::export(s,records,excel).map_err(|e|format!("内部错误:导出失败:{e}"))?;
|
||||
|
||||
+4
-2
@@ -1,5 +1,6 @@
|
||||
mod appearance;
|
||||
mod archive;
|
||||
mod config;
|
||||
mod error;
|
||||
mod geofences;
|
||||
mod http;
|
||||
@@ -83,6 +84,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
if port == 0 {
|
||||
return Err("监听端口不能为零".into());
|
||||
}
|
||||
let config = config::load(&root)?;
|
||||
let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
@@ -106,7 +108,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| "该数据目录已被另一个 Rust 实例使用")?;
|
||||
map_settings::prepare_offline_directory(&root.join("maps"))?;
|
||||
let map_root = root.clone();
|
||||
let store = store::Store::open(root)?;
|
||||
let store = store::Store::open_with_config(root, &config.sqlite)?;
|
||||
let (tx, mut rx) = mpsc::channel::<Job>(64);
|
||||
let shutdown = tx.clone();
|
||||
let worker_thread = std::thread::spawn(move || {
|
||||
@@ -131,7 +133,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.merge(receivers)
|
||||
.merge(monitor)
|
||||
.merge(map_preferences)
|
||||
.merge(maps::router(map_root)?);
|
||||
.merge(maps::router(map_root, config.maps.tianditu_token)?);
|
||||
let browser_task = open_browser.then(|| tokio::spawn(launch::open_when_ready(port)));
|
||||
let served = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
|
||||
+26
-8
@@ -46,7 +46,11 @@ struct LayerStatus {
|
||||
error: Option<&'static str>,
|
||||
last_online_ms: u64,
|
||||
}
|
||||
fn load_key(root: &FsPath, environment: Option<String>) -> (Option<String>, Option<&'static str>) {
|
||||
fn load_key(
|
||||
root: &FsPath,
|
||||
environment: Option<String>,
|
||||
configured: Option<String>,
|
||||
) -> (Option<String>, Option<&'static str>) {
|
||||
let trim = |v: String| {
|
||||
let v = v.trim().to_owned();
|
||||
(!v.is_empty()).then_some(v)
|
||||
@@ -54,6 +58,9 @@ fn load_key(root: &FsPath, environment: Option<String>) -> (Option<String>, Opti
|
||||
if let Some(key) = environment.and_then(trim) {
|
||||
return (Some(key), None);
|
||||
}
|
||||
if let Some(key) = configured.and_then(trim) {
|
||||
return (Some(key), None);
|
||||
}
|
||||
let path = root.join("maps/config.json");
|
||||
if !path.exists() {
|
||||
return (None, None);
|
||||
@@ -105,8 +112,8 @@ impl Maps {
|
||||
.store(crate::realtime::now_ms() + 30000, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
pub fn router(root: PathBuf) -> Result<Router, reqwest::Error> {
|
||||
let (key, config_error) = load_key(&root, std::env::var("TIANDITU_TOKEN").ok());
|
||||
pub fn router(root: PathBuf, configured: Option<String>) -> Result<Router, reqwest::Error> {
|
||||
let (key, config_error) = load_key(&root, std::env::var("TIANDITU_TOKEN").ok(), configured);
|
||||
if config_error.is_some() {
|
||||
eprintln!("地图配置读取失败:请检查 maps/config.json,原文件已保留。");
|
||||
}
|
||||
@@ -684,22 +691,33 @@ mod tests {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, br#"{"tianditu_token":" local-test-token "}"#).unwrap();
|
||||
assert_eq!(
|
||||
load_key(temp.path(), None),
|
||||
load_key(temp.path(), None, None),
|
||||
(Some("local-test-token".into()), None)
|
||||
);
|
||||
assert_eq!(
|
||||
load_key(temp.path(), Some(" env-test-token ".into())),
|
||||
load_key(
|
||||
temp.path(),
|
||||
Some(" env-test-token ".into()),
|
||||
Some("central".into())
|
||||
),
|
||||
(Some("env-test-token".into()), None)
|
||||
);
|
||||
assert_eq!(
|
||||
load_key(temp.path(), Some(" ".into())),
|
||||
load_key(temp.path(), Some(" ".into()), None),
|
||||
(Some("local-test-token".into()), None)
|
||||
);
|
||||
assert_eq!(
|
||||
load_key(temp.path(), None, Some(" central-token ".into())),
|
||||
(Some("central-token".into()), None)
|
||||
);
|
||||
std::fs::write(&path, b"broken config").unwrap();
|
||||
assert_eq!(load_key(temp.path(), None), (None, Some("invalid-config")));
|
||||
assert_eq!(
|
||||
load_key(temp.path(), None, None),
|
||||
(None, Some("invalid-config"))
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"broken config");
|
||||
assert_eq!(
|
||||
load_key(temp.path(), Some("override".into())),
|
||||
load_key(temp.path(), Some("override".into()), None),
|
||||
(Some("override".into()), None)
|
||||
);
|
||||
}
|
||||
|
||||
+37
-73
@@ -1,5 +1,7 @@
|
||||
//! Receive-only transports. Unknown vendor formats remain raw bytes, never guessed positions.
|
||||
mod device;
|
||||
mod manager;
|
||||
mod uid;
|
||||
|
||||
use crate::realtime::{TargetStore, now_ms};
|
||||
use axum::{
|
||||
@@ -26,7 +28,7 @@ use tokio::{
|
||||
};
|
||||
use tokio_serial::SerialPortBuilderExt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum Transport {
|
||||
#[default]
|
||||
@@ -34,17 +36,18 @@ enum Transport {
|
||||
Udp,
|
||||
TcpListen,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum Format {
|
||||
#[default]
|
||||
Raw,
|
||||
JsonLines,
|
||||
RidDeviceJson,
|
||||
UidJson,
|
||||
Postcard,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct Config {
|
||||
enabled: bool,
|
||||
@@ -132,12 +135,11 @@ impl Default for Monitor {
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Receiver {
|
||||
root: PathBuf,
|
||||
id: String,
|
||||
config: Arc<Mutex<Config>>,
|
||||
monitor: Arc<Mutex<Monitor>>,
|
||||
targets: TargetStore,
|
||||
task: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
changes: Arc<tokio::sync::Mutex<()>>,
|
||||
}
|
||||
|
||||
fn local(headers: &HeaderMap) -> bool {
|
||||
@@ -152,37 +154,7 @@ fn local(headers: &HeaderMap) -> bool {
|
||||
}
|
||||
|
||||
pub(crate) async fn router(root: PathBuf, targets: TargetStore) -> Router {
|
||||
let receiver = Receiver {
|
||||
root,
|
||||
config: Arc::new(Mutex::new(Config::default())),
|
||||
monitor: Arc::new(Mutex::new(Monitor::default())),
|
||||
targets,
|
||||
task: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
changes: Arc::new(tokio::sync::Mutex::new(())),
|
||||
};
|
||||
let path = receiver.root.join("receiver-config.json");
|
||||
if path.exists() {
|
||||
match std::fs::metadata(&path)
|
||||
.ok()
|
||||
.filter(|m| m.len() <= 8192)
|
||||
.and_then(|_| std::fs::read(&path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<Config>(&bytes).ok())
|
||||
.filter(|c| c.validate().is_ok())
|
||||
{
|
||||
Some(config) => receiver.start(config).await,
|
||||
None => {
|
||||
receiver.monitor.lock().unwrap().status.last_error =
|
||||
Some("接收配置无效;原文件已保留,请通过接收设置重新配置".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
Router::new()
|
||||
.route("/api/receiver/status", get(status))
|
||||
.route("/api/receiver/config", get(config).post(save))
|
||||
.route("/api/receiver/ports", get(ports))
|
||||
.route("/api/receiver/capture", get(capture))
|
||||
.layer(axum::extract::DefaultBodyLimit::max(4096))
|
||||
.with_state(receiver)
|
||||
manager::router(root, targets).await
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
@@ -231,9 +203,13 @@ impl Receiver {
|
||||
fn decode(&self, format: Format, bytes: &[u8]) {
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
let result: Result<Vec<Observation>, ()> = match format {
|
||||
Format::RidDeviceJson => {
|
||||
Format::RidDeviceJson | Format::UidJson => {
|
||||
let epoch = monitor.source_epoch;
|
||||
match device::decode(bytes, epoch, &mut monitor.sequence) {
|
||||
match if format == Format::UidJson {
|
||||
uid::decode(bytes, epoch, &mut monitor.sequence)
|
||||
} else {
|
||||
device::decode(bytes, epoch, &mut monitor.sequence)
|
||||
} {
|
||||
Ok(decoded) => {
|
||||
monitor.status.invalid_targets += decoded.invalid_targets;
|
||||
if decoded.ignored {
|
||||
@@ -277,7 +253,18 @@ impl Receiver {
|
||||
let accepted = {
|
||||
let mut store = self.targets.lock().unwrap();
|
||||
let mut accepted = 0;
|
||||
for observation in batch {
|
||||
for mut observation in batch {
|
||||
observation.receiver_id = self.id.clone();
|
||||
if !matches!(format, Format::RidDeviceJson) {
|
||||
let identity = observation.target_id.clone();
|
||||
observation.target_id =
|
||||
format!("SRC-{}-{}-{}", self.id.len(), self.id, identity);
|
||||
if !matches!(format, Format::UidJson) {
|
||||
monitor.sequence = monitor.sequence.saturating_add(1);
|
||||
observation.source_epoch = monitor.source_epoch;
|
||||
observation.sequence = monitor.sequence;
|
||||
}
|
||||
}
|
||||
accepted += usize::from(store.apply(observation, now));
|
||||
}
|
||||
accepted
|
||||
@@ -314,7 +301,12 @@ impl Receiver {
|
||||
if matches!(format, Format::Raw) {
|
||||
continue;
|
||||
}
|
||||
if discarding_json && matches!(format, Format::JsonLines | Format::RidDeviceJson) {
|
||||
if discarding_json
|
||||
&& matches!(
|
||||
format,
|
||||
Format::JsonLines | Format::RidDeviceJson | Format::UidJson
|
||||
)
|
||||
{
|
||||
if let Some(end) = chunk[..n].iter().position(|b| *b == b'\n') {
|
||||
discarding_json = false;
|
||||
buffer.extend_from_slice(&chunk[end + 1..n]);
|
||||
@@ -325,7 +317,7 @@ impl Receiver {
|
||||
buffer.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
match format {
|
||||
Format::JsonLines | Format::RidDeviceJson => {
|
||||
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]);
|
||||
@@ -457,44 +449,16 @@ async fn ports(headers: HeaderMap) -> Response {
|
||||
.unwrap_or_default();
|
||||
Json(json!({"ports":names})).into_response()
|
||||
}
|
||||
async fn save(
|
||||
State(receiver): State<Receiver>,
|
||||
headers: HeaderMap,
|
||||
Json(mut config): Json<Config>,
|
||||
) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
config.serial_port = config.serial_port.trim().to_uppercase();
|
||||
if let Err(error) = config.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(json!({"error":error}))).into_response();
|
||||
}
|
||||
let _change = receiver.changes.lock().await;
|
||||
let bytes = serde_json::to_vec_pretty(&config).unwrap();
|
||||
let path = receiver.root.join("receiver-config.json");
|
||||
let saved = tokio::task::spawn_blocking(move || crate::archive::atomic(&path, bytes)).await;
|
||||
if !matches!(saved, Ok(Ok(()))) {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error":"接收配置保存失败"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
receiver.start(config.clone()).await;
|
||||
Json(json!({"saved":true,"config":config})).into_response()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn receiver() -> Receiver {
|
||||
Receiver {
|
||||
root: std::env::temp_dir(),
|
||||
id: "default".into(),
|
||||
config: Arc::new(Mutex::new(Config::default())),
|
||||
monitor: Arc::new(Mutex::new(Monitor::default())),
|
||||
targets: crate::realtime::new_store(),
|
||||
task: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
changes: Arc::new(tokio::sync::Mutex::new(())),
|
||||
}
|
||||
}
|
||||
fn observation() -> Observation {
|
||||
@@ -688,10 +652,10 @@ mod tests {
|
||||
app.clone().oneshot(request(&body)).await.unwrap().status(),
|
||||
200
|
||||
);
|
||||
let saved: Config = serde_json::from_slice(
|
||||
&std::fs::read(temp.path().join("receiver-config.json")).unwrap(),
|
||||
)
|
||||
let entries: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(temp.path().join("receivers.json")).unwrap())
|
||||
.unwrap();
|
||||
let saved: Config = serde_json::from_value(entries[0]["config"].clone()).unwrap();
|
||||
assert!(saved.enabled);
|
||||
assert_eq!(saved.port, port);
|
||||
let mut listening = false;
|
||||
|
||||
@@ -104,6 +104,7 @@ pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Dec
|
||||
height_agl_m: number(v, "Height_AGL", -1000., 100000.),
|
||||
pilot_position: coordinates(v, "pilot_lon", "pilot_lat"),
|
||||
utc_raw: text(v, "utc"),
|
||||
..DeviceTelemetry::default()
|
||||
}),
|
||||
};
|
||||
if o.validate() {
|
||||
|
||||
@@ -0,0 +1,530 @@
|
||||
//! Persistent receiver registry; transports remain owned by independent Receiver tasks.
|
||||
use super::*;
|
||||
use axum::extract::Path;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Entry {
|
||||
id: String,
|
||||
name: String,
|
||||
config: Config,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Manager {
|
||||
root: PathBuf,
|
||||
targets: TargetStore,
|
||||
entries: Arc<tokio::sync::Mutex<BTreeMap<String, (Entry, Receiver)>>>,
|
||||
error: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
fn receiver(id: &str, targets: TargetStore) -> Receiver {
|
||||
Receiver {
|
||||
id: id.into(),
|
||||
config: Arc::new(Mutex::new(Config::default())),
|
||||
monitor: Arc::new(Mutex::new(Monitor::default())),
|
||||
targets,
|
||||
task: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
fn conflicts(a: &Config, b: &Config) -> bool {
|
||||
if !a.enabled || !b.enabled {
|
||||
return false;
|
||||
}
|
||||
match (a.transport, b.transport) {
|
||||
(Transport::Serial, Transport::Serial) => {
|
||||
a.serial_port.eq_ignore_ascii_case(&b.serial_port)
|
||||
}
|
||||
(Transport::Udp, Transport::Udp) | (Transport::TcpListen, Transport::TcpListen) => {
|
||||
a.port == b.port
|
||||
&& match (a.bind_ip.parse::<IpAddr>(), b.bind_ip.parse::<IpAddr>()) {
|
||||
(Ok(a), Ok(b)) => a == b || a.is_unspecified() || b.is_unspecified(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn validate(entries: &[Entry]) -> Result<(), &'static str> {
|
||||
if entries.is_empty() || entries.len() > 32 {
|
||||
return Err("接收机数量应为 1–32 台");
|
||||
}
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
if entry.id.is_empty()
|
||||
|| entry.id.len() > 40
|
||||
|| !entry
|
||||
.id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
{
|
||||
return Err("接收机 ID 无效");
|
||||
}
|
||||
if entry.name.trim().is_empty() || entry.name.len() > 120 {
|
||||
return Err("请填写有效设备名称(最多 120 字节)");
|
||||
}
|
||||
entry.config.validate()?;
|
||||
if entries[..index]
|
||||
.iter()
|
||||
.any(|e| e.id == entry.id || conflicts(&e.config, &entry.config))
|
||||
{
|
||||
return Err("接收机 ID 重复或启用的串口 / 监听端点冲突");
|
||||
}
|
||||
}
|
||||
if !entries.iter().any(|e| e.id == "default") {
|
||||
return Err("默认接收机必须保留,可将其停用");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn error(code: StatusCode, message: impl ToString) -> Response {
|
||||
(code, Json(json!({"error":message.to_string()}))).into_response()
|
||||
}
|
||||
pub(super) async fn router(root: PathBuf, targets: TargetStore) -> Router {
|
||||
let manager = Manager {
|
||||
root,
|
||||
targets,
|
||||
entries: Default::default(),
|
||||
error: Default::default(),
|
||||
};
|
||||
let path = manager.root.join("receivers.json");
|
||||
let loaded: Result<Vec<Entry>, String> = (|| {
|
||||
if path.exists() {
|
||||
if std::fs::metadata(&path).map_err(|e| e.to_string())?.len() > 131072 {
|
||||
return Err("接收机配置超过大小限制".into());
|
||||
}
|
||||
serde_json::from_slice(&std::fs::read(&path).map_err(|e| e.to_string())?)
|
||||
.map_err(|e| e.to_string())
|
||||
} else {
|
||||
let old = manager.root.join("receiver-config.json");
|
||||
let config = if old.exists() {
|
||||
if std::fs::metadata(&old).map_err(|e| e.to_string())?.len() > 8192 {
|
||||
return Err("旧接收配置过大".into());
|
||||
}
|
||||
serde_json::from_slice(&std::fs::read(old).map_err(|e| e.to_string())?)
|
||||
.map_err(|e| e.to_string())?
|
||||
} else {
|
||||
Config::default()
|
||||
};
|
||||
Ok(vec![Entry {
|
||||
id: "default".into(),
|
||||
name: "接收机 01".into(),
|
||||
config,
|
||||
}])
|
||||
}
|
||||
})();
|
||||
match loaded.and_then(|entries| validate(&entries).map(|()| entries).map_err(str::to_owned)) {
|
||||
Ok(entries) => {
|
||||
let persisted = if path.exists() {
|
||||
Ok(())
|
||||
} else {
|
||||
let bytes =
|
||||
serde_json::to_vec_pretty(&entries).expect("receiver config serializes");
|
||||
crate::archive::atomic(&path, bytes).map_err(|e| e.to_string())
|
||||
};
|
||||
if let Err(e) = persisted {
|
||||
*manager.error.lock().unwrap() = Some(e);
|
||||
}
|
||||
let mut registry = manager.entries.lock().await;
|
||||
for entry in entries {
|
||||
let instance = receiver(&entry.id, manager.targets.clone());
|
||||
instance.start(entry.config.clone()).await;
|
||||
registry.insert(entry.id.clone(), (entry, instance));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
*manager.error.lock().unwrap() =
|
||||
Some(format!("配置无效,原文件已保留,未启动接收:{e}"));
|
||||
}
|
||||
}
|
||||
Router::new()
|
||||
.route("/api/receivers", get(list).post(create))
|
||||
.route(
|
||||
"/api/receivers/{id}",
|
||||
get(detail).put(update).delete(remove),
|
||||
)
|
||||
.route("/api/receivers/{id}/status", get(receiver_status))
|
||||
.route("/api/receivers/{id}/capture", get(receiver_capture))
|
||||
.route("/api/receiver/status", get(legacy_status))
|
||||
.route("/api/receiver/config", get(legacy_config).post(legacy_save))
|
||||
.route("/api/receiver/capture", get(legacy_capture))
|
||||
.route("/api/receiver/ports", get(ports))
|
||||
.layer(axum::extract::DefaultBodyLimit::max(8192))
|
||||
.with_state(manager)
|
||||
}
|
||||
async fn list(State(m): State<Manager>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let entries = m.entries.lock().await;
|
||||
let rows: Vec<_> = entries.values().map(|(entry, receiver)| json!({"id":entry.id,"name":entry.name,"config":entry.config,"status":receiver.monitor.lock().unwrap().status})).collect();
|
||||
Json(json!({"receivers":rows,"error":*m.error.lock().unwrap()})).into_response()
|
||||
}
|
||||
async fn detail(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let entries = m.entries.lock().await;
|
||||
match entries.get(&id) {
|
||||
Some((e, _)) => Json(e).into_response(),
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
async fn persist(m: &Manager, entries: Vec<Entry>) -> Result<(), Box<Response>> {
|
||||
validate(&entries).map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, e)))?;
|
||||
let bytes = serde_json::to_vec_pretty(&entries)
|
||||
.map_err(|e| Box::new(error(StatusCode::INTERNAL_SERVER_ERROR, e)))?;
|
||||
let path = m.root.join("receivers.json");
|
||||
tokio::task::spawn_blocking(move || crate::archive::atomic(&path, bytes))
|
||||
.await
|
||||
.map_err(|e| Box::new(error(StatusCode::INTERNAL_SERVER_ERROR, e)))?
|
||||
.map_err(|e| Box::new(error(StatusCode::INTERNAL_SERVER_ERROR, e)))?;
|
||||
*m.error.lock().unwrap() = None;
|
||||
Ok(())
|
||||
}
|
||||
async fn write(m: Manager, mut entry: Entry, creating: bool) -> Response {
|
||||
entry.name = entry.name.trim().to_owned();
|
||||
entry.config.serial_port = entry.config.serial_port.trim().to_ascii_uppercase();
|
||||
entry.config.bind_ip = entry.config.bind_ip.trim().to_owned();
|
||||
let mut entries = m.entries.lock().await;
|
||||
if entries.is_empty() {
|
||||
return error(
|
||||
StatusCode::CONFLICT,
|
||||
"请先修复磁盘上的无效配置,避免覆盖原文件",
|
||||
);
|
||||
}
|
||||
if creating == entries.contains_key(&entry.id) {
|
||||
return error(StatusCode::CONFLICT, "接收机不存在或 ID 已存在");
|
||||
}
|
||||
let mut next: Vec<_> = entries
|
||||
.values()
|
||||
.filter(|(e, _)| e.id != entry.id)
|
||||
.map(|(e, _)| e.clone())
|
||||
.collect();
|
||||
next.push(entry.clone());
|
||||
if let Err(response) = persist(&m, next).await {
|
||||
return *response;
|
||||
}
|
||||
let instance = entries
|
||||
.get(&entry.id)
|
||||
.map(|(_, r)| r.clone())
|
||||
.unwrap_or_else(|| receiver(&entry.id, m.targets.clone()));
|
||||
let changed = *instance.config.lock().unwrap() != entry.config;
|
||||
if changed {
|
||||
instance.start(entry.config.clone()).await;
|
||||
}
|
||||
entries.insert(entry.id.clone(), (entry.clone(), instance));
|
||||
Json(json!({"saved":true,"receiver":entry})).into_response()
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Input {
|
||||
name: String,
|
||||
config: Config,
|
||||
}
|
||||
async fn create(
|
||||
State(m): State<Manager>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Input>,
|
||||
) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
write(
|
||||
m,
|
||||
Entry {
|
||||
id: format!("rx-{:016x}", rand::random::<u64>()),
|
||||
name: input.name,
|
||||
config: input.config,
|
||||
},
|
||||
true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn update(
|
||||
State(m): State<Manager>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Json(input): Json<Input>,
|
||||
) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
write(
|
||||
m,
|
||||
Entry {
|
||||
id,
|
||||
name: input.name,
|
||||
config: input.config,
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn remove(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if id == "default" {
|
||||
return error(StatusCode::BAD_REQUEST, "默认接收机不可删除,可以停用");
|
||||
}
|
||||
let mut entries = m.entries.lock().await;
|
||||
if !entries.contains_key(&id) {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
let next = entries
|
||||
.values()
|
||||
.filter(|(e, _)| e.id != id)
|
||||
.map(|(e, _)| e.clone())
|
||||
.collect();
|
||||
if let Err(response) = persist(&m, next).await {
|
||||
return *response;
|
||||
}
|
||||
if let Some((mut e, r)) = entries.remove(&id) {
|
||||
e.config.enabled = false;
|
||||
r.start(e.config).await;
|
||||
}
|
||||
Json(json!({"deleted":true})).into_response()
|
||||
}
|
||||
async fn receiver_status(
|
||||
State(m): State<Manager>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let receiver = m.entries.lock().await.get(&id).map(|(_, r)| r.clone());
|
||||
match receiver {
|
||||
Some(r) => status(State(r), headers).await,
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
async fn receiver_capture(
|
||||
State(m): State<Manager>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let receiver = m.entries.lock().await.get(&id).map(|(_, r)| r.clone());
|
||||
match receiver {
|
||||
Some(r) => capture(State(r), headers).await,
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
async fn legacy_status(state: State<Manager>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if state.entries.lock().await.is_empty() {
|
||||
return Json(json!({"state":"stopped","lastError":*state.error.lock().unwrap()}))
|
||||
.into_response();
|
||||
}
|
||||
receiver_status(state, Path("default".into()), headers).await
|
||||
}
|
||||
async fn legacy_capture(state: State<Manager>, headers: HeaderMap) -> Response {
|
||||
receiver_capture(state, Path("default".into()), headers).await
|
||||
}
|
||||
async fn legacy_config(State(m): State<Manager>, headers: HeaderMap) -> Response {
|
||||
let receiver = m
|
||||
.entries
|
||||
.lock()
|
||||
.await
|
||||
.get("default")
|
||||
.map(|(_, r)| r.clone());
|
||||
match receiver {
|
||||
Some(r) => config(State(r), headers).await,
|
||||
None => StatusCode::SERVICE_UNAVAILABLE.into_response(),
|
||||
}
|
||||
}
|
||||
async fn legacy_save(
|
||||
State(m): State<Manager>,
|
||||
headers: HeaderMap,
|
||||
Json(config): Json<Config>,
|
||||
) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let name = m
|
||||
.entries
|
||||
.lock()
|
||||
.await
|
||||
.get("default")
|
||||
.map(|(e, _)| e.name.clone())
|
||||
.unwrap_or_else(|| "接收机 01".into());
|
||||
write(
|
||||
m,
|
||||
Entry {
|
||||
id: "default".into(),
|
||||
name,
|
||||
config,
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::Request,
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
async fn call(
|
||||
app: &Router,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: serde_json::Value,
|
||||
) -> (StatusCode, serde_json::Value) {
|
||||
let r = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let code = r.status();
|
||||
let bytes = to_bytes(r.into_body(), 131072).await.unwrap();
|
||||
(code, serde_json::from_slice(&bytes).unwrap_or_default())
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn migration_independent_updates_and_failed_save_preserve_configuration() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let old = br#"{"enabled":false,"serialPort":"COM16","baudRate":115200,"format":"raw"}"#;
|
||||
std::fs::write(root.path().join("receiver-config.json"), old).unwrap();
|
||||
let app = router(root.path().into(), crate::realtime::new_store()).await;
|
||||
let (_, list) = call(&app, "GET", "/api/receivers", json!(null)).await;
|
||||
assert_eq!(list["receivers"][0]["config"]["serialPort"], "COM16");
|
||||
assert_eq!(
|
||||
std::fs::read(root.path().join("receiver-config.json")).unwrap(),
|
||||
old
|
||||
);
|
||||
let input = json!({"name":"Second","config":{"enabled":false,"serialPort":"COM18","format":"uid-json"}});
|
||||
let (code, created) = call(&app, "POST", "/api/receivers", input.clone()).await;
|
||||
assert_eq!(code, 200);
|
||||
let id = created["receiver"]["id"].as_str().unwrap();
|
||||
let restarted = router(root.path().into(), crate::realtime::new_store()).await;
|
||||
let (_, list) = call(&restarted, "GET", "/api/receivers", json!(null)).await;
|
||||
assert_eq!(list["receivers"].as_array().unwrap().len(), 2);
|
||||
std::fs::create_dir(root.path().join("receivers.tmp")).unwrap();
|
||||
let mut edit = input;
|
||||
edit["name"] = json!("Must not persist");
|
||||
assert_eq!(
|
||||
call(&app, "PUT", &format!("/api/receivers/{id}"), edit)
|
||||
.await
|
||||
.0,
|
||||
500
|
||||
);
|
||||
let (_, detail) = call(&app, "GET", &format!("/api/receivers/{id}"), json!(null)).await;
|
||||
assert_eq!(detail["name"], "Second");
|
||||
assert_eq!(
|
||||
call(&app, "DELETE", "/api/receivers/default", json!(null))
|
||||
.await
|
||||
.0,
|
||||
400
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn enabled_endpoint_conflicts_are_rejected_without_blocking_tcp_and_udp_pairs() {
|
||||
let mut a = Config {
|
||||
enabled: true,
|
||||
serial_port: "COM16".into(),
|
||||
..Config::default()
|
||||
};
|
||||
let mut b = a.clone();
|
||||
assert!(conflicts(&a, &b));
|
||||
b.enabled = false;
|
||||
assert!(!conflicts(&a, &b));
|
||||
a.transport = Transport::Udp;
|
||||
a.bind_ip = "0.0.0.0".into();
|
||||
b = a.clone();
|
||||
b.bind_ip = "127.0.0.1".into();
|
||||
assert!(conflicts(&a, &b));
|
||||
b.transport = Transport::TcpListen;
|
||||
assert!(!conflicts(&a, &b));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn parallel_receivers_keep_running_when_one_is_stopped() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let targets = crate::realtime::new_store();
|
||||
let app = router(root.path().into(), targets.clone()).await;
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = socket.local_addr().unwrap().port();
|
||||
drop(socket);
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let port2 = socket.local_addr().unwrap().port();
|
||||
drop(socket);
|
||||
let config = json!({"enabled":true,"transport":"udp","format":"uid-json","bindIp":"127.0.0.1","port":port});
|
||||
assert_eq!(
|
||||
call(&app, "POST", "/api/receiver/config", config.clone())
|
||||
.await
|
||||
.0,
|
||||
200
|
||||
);
|
||||
let duplicate = json!({"name":"Duplicate","config":config});
|
||||
assert_eq!(call(&app, "POST", "/api/receivers", duplicate).await.0, 400);
|
||||
let mut second = json!({"name":"Second","config":{"enabled":true,"transport":"udp","format":"uid-json","bindIp":"127.0.0.1","port":port2}});
|
||||
let (_, created) = call(&app, "POST", "/api/receivers", second.clone()).await;
|
||||
let id = created["receiver"]["id"].as_str().unwrap();
|
||||
let sender = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let bytes=br#"{"uid":"SAME-UNKNOWN-ID","ua_longitude":120,"ua_latitude":30,"coordinate_system":0}"#;
|
||||
for _ in 0..100 {
|
||||
sender.send_to(bytes, ("127.0.0.1", port)).await.unwrap();
|
||||
sender.send_to(bytes, ("127.0.0.1", port2)).await.unwrap();
|
||||
if targets.lock().unwrap().metrics().active_targets == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let frame = targets.lock().unwrap().frame(None, now_ms());
|
||||
assert_eq!(frame.targets.len(), 2);
|
||||
assert!(
|
||||
frame
|
||||
.targets
|
||||
.iter()
|
||||
.all(|t| t.observation.coordinates().is_none())
|
||||
);
|
||||
let mut disabled = config;
|
||||
disabled["enabled"] = json!(false);
|
||||
assert_eq!(
|
||||
call(&app, "POST", "/api/receiver/config", disabled).await.0,
|
||||
200
|
||||
);
|
||||
let (_, before) = call(
|
||||
&app,
|
||||
"GET",
|
||||
&format!("/api/receivers/{id}/status"),
|
||||
json!(null),
|
||||
)
|
||||
.await;
|
||||
for _ in 0..100 {
|
||||
sender.send_to(bytes, ("127.0.0.1", port2)).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
let (_, after) = call(
|
||||
&app,
|
||||
"GET",
|
||||
&format!("/api/receivers/{id}/status"),
|
||||
json!(null),
|
||||
)
|
||||
.await;
|
||||
if after["receivedBytes"].as_u64() > before["receivedBytes"].as_u64() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (_, after) = call(
|
||||
&app,
|
||||
"GET",
|
||||
&format!("/api/receivers/{id}/status"),
|
||||
json!(null),
|
||||
)
|
||||
.await;
|
||||
assert!(after["receivedBytes"].as_u64() > before["receivedBytes"].as_u64());
|
||||
second["config"]["enabled"] = json!(false);
|
||||
assert_eq!(
|
||||
call(&app, "PUT", &format!("/api/receivers/{id}"), second)
|
||||
.await
|
||||
.0,
|
||||
200
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Observed COM16 UID JSON. Coordinate-system codes have no verified definition yet.
|
||||
use super::device::Decoded;
|
||||
use rid_shared::{DeviceTelemetry, Observation};
|
||||
use serde_json::Value;
|
||||
|
||||
fn number(v: &Value, key: &str, min: f64, max: f64) -> Option<f64> {
|
||||
v.get(key)?
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && (min..=max).contains(n))
|
||||
}
|
||||
pub(super) fn decode(bytes: &[u8], epoch: u64, sequence: &mut u64) -> Result<Decoded, ()> {
|
||||
let v: Value = serde_json::from_slice(bytes.trim_ascii()).map_err(|_| ())?;
|
||||
let id = v
|
||||
.get("uid")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 64
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
})
|
||||
.ok_or(())?;
|
||||
if !v.is_object() || (v.get("ua_longitude").is_none() && v.get("ua_latitude").is_none()) {
|
||||
return Err(());
|
||||
}
|
||||
*sequence = sequence.checked_add(1).ok_or(())?;
|
||||
let raw_position = number(&v, "ua_longitude", -180., 180.)
|
||||
.zip(number(&v, "ua_latitude", -90., 90.))
|
||||
.map(|(lon, lat)| [lon, lat]);
|
||||
let telemetry = DeviceTelemetry {
|
||||
raw_identity: Some(id.into()),
|
||||
raw_position,
|
||||
coordinate_system: v.get("coordinate_system").and_then(Value::as_i64),
|
||||
position_unverified: true,
|
||||
speed_mps: number(&v, "ground_speed", 0., 1000.),
|
||||
vertical_speed_mps: number(&v, "vertical_speed", -1000., 1000.),
|
||||
relative_height_m: number(&v, "relative_height", -1000., 100000.),
|
||||
geometric_altitude_m: number(&v, "geodetic_altitude", -1000., 100000.)
|
||||
.filter(|v| *v != -1000.),
|
||||
pressure_altitude_m: number(&v, "barometric_altitude", -1000., 100000.)
|
||||
.filter(|v| *v != -1000.),
|
||||
utc_raw: v
|
||||
.get("timestamp")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|v| v.to_string()),
|
||||
..DeviceTelemetry::default()
|
||||
};
|
||||
Ok(Decoded {
|
||||
observations: vec![Observation {
|
||||
target_id: id.into(),
|
||||
receiver_id: "UID-DEVICE".into(),
|
||||
source_epoch: epoch,
|
||||
sequence: *sequence,
|
||||
longitude: None,
|
||||
latitude: None,
|
||||
altitude_m: None,
|
||||
heading_deg: number(&v, "track_angle", 0., 360.).map(|v| (v % 360.) as f32),
|
||||
telemetry: Some(telemetry),
|
||||
}],
|
||||
invalid_targets: 0,
|
||||
ignored: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn uid_keeps_unverified_position_out_of_map_and_preserves_height_reference() {
|
||||
let mut seq = 0;
|
||||
let d=decode(br#"{"uid":"DEMO-UID-01","ua_longitude":120.1,"ua_latitude":30.2,"coordinate_system":0,"relative_height":21,"track_angle":360}"#,1,&mut seq).unwrap();
|
||||
let o = &d.observations[0];
|
||||
assert!(o.validate());
|
||||
assert_eq!(o.coordinates(), None);
|
||||
assert_eq!(o.heading_deg, Some(0.));
|
||||
let t = o.telemetry.as_ref().unwrap();
|
||||
assert_eq!(t.raw_position, Some([120.1, 30.2]));
|
||||
assert_eq!(t.relative_height_m, Some(21.));
|
||||
assert_eq!(t.height_agl_m, None);
|
||||
assert!(t.position_unverified);
|
||||
for bad in [
|
||||
br#"{"uid":""}"#.as_slice(),
|
||||
br#"{"uid":"A B","ua_latitude":0}"#,
|
||||
b"{broken",
|
||||
] {
|
||||
assert!(decode(bad, 1, &mut seq).is_err());
|
||||
}
|
||||
let d = decode(
|
||||
br#"{"uid":"TEST","ua_longitude":200,"ua_latitude":30}"#,
|
||||
1,
|
||||
&mut seq,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
d.observations[0].telemetry.as_ref().unwrap().raw_position,
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -129,10 +129,14 @@ fn apply_photos(db: &Connection, id: &str, photos: [Option<Photo>; 2]) -> Result
|
||||
Ok(())
|
||||
}
|
||||
impl Store {
|
||||
#[cfg(test)]
|
||||
pub fn open(root: PathBuf) -> Result<Self> {
|
||||
Self::open_with_config(root, &crate::config::SqliteConfig::default())
|
||||
}
|
||||
pub fn open_with_config(root: PathBuf, config: &crate::config::SqliteConfig) -> Result<Self> {
|
||||
std::fs::create_dir_all(root.join("registry/data"))?;
|
||||
let mut db = Connection::open(root.join("registry/data/registry.sqlite"))?;
|
||||
db.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
db.busy_timeout(std::time::Duration::from_millis(config.busy_timeout_ms))?;
|
||||
crate::target_lists::init(&mut db)?;
|
||||
crate::geofences::init(&db)?;
|
||||
db.execute_batch(
|
||||
|
||||
@@ -32,7 +32,8 @@ fn bound(db: &Connection, target: &str) -> Result<Option<String>> {
|
||||
pub fn resolve(store: &Store, target: &str) -> Result<Value> {
|
||||
validate(target)?;
|
||||
let binding = bound(&store.db, target)?;
|
||||
let automatic: Option<String> = if binding.is_none() && !target.starts_with("MAC-") {
|
||||
let automatic: Option<String> =
|
||||
if binding.is_none() && !target.starts_with("MAC-") && !target.starts_with("SRC-") {
|
||||
store
|
||||
.db
|
||||
.query_row(
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
use crate::{archive, store::Store};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn sqlite_uses_configured_timeout_and_existing_database_location() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
tmp.path().join("config.json"),
|
||||
br#"{"sqlite":{"busy_timeout_ms":1234}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let config = crate::config::load(tmp.path()).unwrap();
|
||||
let store = Store::open_with_config(tmp.path().to_owned(), &config.sqlite).unwrap();
|
||||
let timeout: i64 = store
|
||||
.db
|
||||
.query_row("PRAGMA busy_timeout", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(timeout, 1234);
|
||||
assert!(tmp.path().join("registry/data/registry.sqlite").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_registration_code_is_generated_and_retained_for_same_serial() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user