```text
chore: 新增项目规则文档、构建别名及忽略规则 添加 AGENTS.md 项目规则文件,涵盖语言与工具链、模块设计、 Git 提交规范及验证流程等内容。 变更要点: - .cargo/config.toml 新增 xtask 命令别名 - .gitignore 忽略运行时地图缓存、接收器配置文件、 构建锁文件及本地 docs/ 目录 - 新增 AGENTS.md 定义项目编码、提交与审查规则 ```
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
[alias]
|
||||
xtask = "run --package xtask --"
|
||||
|
||||
[build]
|
||||
target-dir = "D:/Rust_Contact/util/target/Rid_Drone_Receivev"
|
||||
|
||||
|
||||
@@ -11,3 +11,11 @@ host/
|
||||
*.log
|
||||
/target/
|
||||
/dist/
|
||||
|
||||
# Runtime map cache and user-supplied offline tiles
|
||||
/maps/
|
||||
/receiver-config.json
|
||||
/.build.lock
|
||||
|
||||
# 文档目录
|
||||
docs/
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# 项目规则
|
||||
|
||||
## 语言与必用 Skills
|
||||
|
||||
本项目以 Rust 编写,沿用现有 Rust 2024 workspace 和 rust-toolchain.toml 固定工具链。修改代码、依赖、构建或进行审查前,读取并使用:
|
||||
|
||||
- `C:/Users/20143/.codex/skills/rust-managed-dependencies/SKILL.md`
|
||||
- `C:/Users/20143/.codex/skills/rust-modern-engineering/SKILL.md`
|
||||
|
||||
继续遵守全局目标重述、品质自检及 UI 多方案先选后改规则。涉及 UI 新设计或大幅修改时,读取 `C:/Users/20143/.codex/skills/ui-design-choice-gate/SKILL.md`,先展示多个方案并等待明确选择;不能直接改正式界面。
|
||||
|
||||
## 工具、依赖与文件夹管理
|
||||
|
||||
- 统一管理根目录为 `D:/Rust_Contact/util`:`cargo/` 为 CARGO_HOME,`rustup/` 为 RUSTUP_HOME,`target/Rid_Drone_Receivev/` 为本项目构建目录,`tools/` 管理独立工具,`downloads/` 保留安装包;新增原生 SDK 按 `native/<sdk>/<version>/<target>/` 存放。
|
||||
- 在 PowerShell 构建和测试前使用 `. ./scripts/rust-env.ps1` 设置当前进程环境,遵循 `.cargo/config.toml` 的 target-dir。检查环境变量或命令行覆盖,不修改全局系统配置。
|
||||
- crates 由 Cargo 下载到统一缓存,版本/features 写入 Cargo.toml,应用的 Cargo.lock 纳入版本管理;项目内 workspace crate 保留在源码目录,不手工复制外部 crate 或使用机器绝对 path 替代版本依赖。
|
||||
- 现有独立工具布局继续可用;新增工具优先 `tools/<tool>/<version>/`,沿用项目已有 RID_TRUNK、RID_WASM_BINDGEN 覆盖入口。不要随规则更新擅自搬迁工具或更新依赖。
|
||||
- 业务数据、备案照片、接收器配置及密钥不属于工具缓存,不纳入共享 util 或提交 Git。
|
||||
|
||||
## Rust 编写与模块设计
|
||||
|
||||
- 采用 Rust 官方 API Guidelines、Style Guide、rustfmt/Clippy,并参考 Google Comprehensive Rust;具体要求见全局 Rust 工程 Skill,不能宣称已获得公司规范认证。
|
||||
- 按业务职责维护现有 `src/`、`crates/rid-shared`、`crates/realtime-core`、`crates/web-ui`、`crates/web-worker` 与 `xtask` 边界;跨端共享模型放在合适的共享模块,避免引入宿主专用依赖。调整边界须有明确需求,不批量重构。
|
||||
- 业务、传输和存储通过必要边界解耦,模块默认私有。用 enum/newtype 表达协议状态和领域不变量,使用 Result/Option 处理失败,生产路径避免无理由 panic。
|
||||
- 能解决真实复杂度时使用 Strategy、Adapter、Builder、状态机等模式;简单函数或 match 足够时保持简单,不为套设计模式增加 trait、工厂、crate 或多层转发。
|
||||
- 异步任务明确退出与取消,通道和缓冲控制容量;不跨 await 持有阻塞锁,不在异步执行器中直接运行长时间阻塞工作。
|
||||
- 协议解析检查长度、范围、损坏和异常输入;对串口/网络断连、重复消息、慢消费者及重连按实际需求测试。unsafe/FFI 必须局部封装并写明 SAFETY 前提。
|
||||
|
||||
## docs 目录禁止提交
|
||||
|
||||
- 项目根目录 `docs/` 下的所有文件和子目录均为本地资料,不纳入 Git 提交;保持 `.gitignore` 中的 `docs/` 忽略规则,不添加反向规则或使用 `git add -f` 绕过。
|
||||
- 如果发现 `docs/` 内文件已被跟踪,仅取消 Git 跟踪,保留本地文件,不删除本地文档或图片。
|
||||
- 准备提交时检查 `git ls-files -- docs`,应无输出;取消跟踪产生的暂存删除允许提交,用于从版本库移除这些文件,不代表删除本地资料。
|
||||
- 本规则仅针对根目录 `docs/`,不扩大到 `doc/` 等其他目录;除非用户明确修改要求,否则持续遵守。
|
||||
|
||||
## 验证与变更范围
|
||||
|
||||
- 保留其他未提交修改;只修改当前任务所需文件,不默认提交、推送、迁移运行数据或操作真实设备。
|
||||
- 行为变更运行相关测试与回归检查,Rust 格式用 `cargo fmt --all -- --check`;Clippy 与测试按宿主和 wasm32 目标分别执行,遵循现有 xtask/脚本,不对混合 workspace 盲目运行全部宿主目标或 --all-features。
|
||||
- 工具路径检查使用实际环境值和解析路径,必要时用 `cargo metadata --locked --no-deps --format-version 1` 确认 target_directory。实际构建、运行、浏览器和设备结果分别报告。
|
||||
- 纯规则/文档修改检查内容、路径、Skill 元数据和配置一致性,无需触发完整构建。
|
||||
- 大型功能若项目后续安装 Spec Kit,遵循全局 Spec Kit 流程;小型明确修复保持局部执行。
|
||||
|
||||
## Git 提交规则
|
||||
|
||||
本节在用户要求生成提交说明或执行 Git 提交时适用;制定规则本身不代表授权提交或推送。
|
||||
|
||||
### 提交说明格式
|
||||
|
||||
- 使用 Conventional Commits:`<type>(<scope>): <中文标题>`;scope 可省略,标题与正文之间空一行。
|
||||
- type 按实际变更选择:`feat` 新功能、`fix` 修复、`refactor` 重构、`perf` 性能、`docs` 文档、`test` 测试、`build` 构建与依赖、`ci` 持续集成、`chore` 维护、`style` 不影响行为的格式调整、`revert` 回退。界面功能或视觉行为变化按实际用途选择 feat/fix,不使用 style 表示。
|
||||
- scope 使用受影响的模块,如 `receiver`、`realtime`、`maps`、`registry`、`web-ui`、`web-worker`、`rid-shared`、`xtask`;跨模块且没有明确主模块时省略,不生造范围。
|
||||
- 标题简洁说明具体动作与结果,不写“更新代码”“修复问题”等空泛描述,不堆砌文件名。
|
||||
- 正文以中文说明为什么改、实际改了什么以及行为如何变化;代码标识符、路径和协议名保留原文。不逐文件复述 diff,不添加不存在的功能或验证结论。
|
||||
- 简单变更采用“标题 + 简短正文”;跨模块、协议、状态或生命周期等复杂变更采用“标题 + 行为说明 + 变更要点”,有实际验证时追加“验证”段。
|
||||
- 验证描述区分已通过、失败、未执行与受阻;源代码检查、构建、浏览器和设备验证分别表述,不将编译通过写成运行或设备验收通过。
|
||||
- 不兼容变更在 type/scope 后加 `!`,正文添加 `BREAKING CHANGE: <中文影响与迁移说明>`;仅在确实破坏兼容时使用。
|
||||
|
||||
简单变更示例(仅为格式示例,不代表当前变更已经提交):
|
||||
|
||||
```text
|
||||
docs: 将本地资料目录排除在版本控制之外
|
||||
|
||||
取消跟踪 docs/ 下的本地资料,并保留本地文件。
|
||||
在 .gitignore 中忽略根目录 docs/,避免后续误提交。
|
||||
```
|
||||
|
||||
复杂变更模板(填写实际事实,无内容的段落省略):
|
||||
|
||||
```text
|
||||
<type>(<scope>): <中文动作与结果>
|
||||
|
||||
<原有问题或触发条件,以及修改后的实际行为与边界。>
|
||||
|
||||
变更要点:
|
||||
- <关键模块或函数的修改及其用途>
|
||||
- <异常路径、资源清理或相关回归覆盖>
|
||||
|
||||
验证:
|
||||
- <实际执行的检查及结果;相关未验证项如实注明>
|
||||
```
|
||||
|
||||
### 提交执行边界
|
||||
|
||||
- 执行前检查 `git status --short`、未暂存和已暂存 diff,确认任务范围;仅按明确路径或选定片段暂存,不使用 `git add .` 或 `git add -A` 混入无关修改。已有暂存内容若归属不明,先询问,不擅自取消暂存或一并提交。
|
||||
- 一个提交对应一个可独立解释的目的;不相关变更分开,不能为拆分而破坏同一功能的必要依赖。提交说明依据最终暂存 diff 编写。
|
||||
- 提交前执行 `git diff --cached --check`,检查暂存文件清单、敏感信息和运行数据,并遵守上述 docs/ 排除及项目验证规则;不默认绕过 hooks 或使用 `--no-verify`。
|
||||
- 仅在用户授权时提交;推送、amend、变基和强制推送须有对应授权,不把“提交代码”理解为自动推送或重写历史。
|
||||
- 多行说明通过临时 UTF-8 文件配合 `git commit -F <文件>` 传入,保留真实换行,完成后清理本次临时文件。
|
||||
- 提交后核对提交内容与 `git status --short`,报告提交 ID、中文标题、验证结果及剩余修改;仅在实际推送并核验远端后声称已推送。
|
||||
Generated
+2127
-11
File diff suppressed because it is too large
Load Diff
+18
-2
@@ -3,9 +3,22 @@ name = "fpv-rid-registry"
|
||||
version = "3.0.0"
|
||||
edition = "2024"
|
||||
|
||||
[[bin]]
|
||||
name = "fpv-rid-registry-fullstack"
|
||||
path = "src/main.rs"
|
||||
|
||||
[workspace]
|
||||
members = ["crates/rid-shared", "crates/realtime-core", "crates/web-ui", "crates/web-worker", "xtask"]
|
||||
default-members = [".", "crates/rid-shared", "crates/realtime-core", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] }
|
||||
axum = { version = "0.8", features = ["ws"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "sync", "time", "io-util"] }
|
||||
tokio-serial = { version = "=5.5.0", default-features = false }
|
||||
rid-shared = { path = "crates/rid-shared" }
|
||||
realtime-core = { path = "crates/realtime-core" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -16,10 +29,13 @@ zip = { version = "4", default-features = false, features = ["deflate"] }
|
||||
rust_xlsxwriter = "0.90"
|
||||
fs2 = "0.4"
|
||||
regex = "1"
|
||||
reqwest = { version = "=0.13.5", default-features = false, features = ["native-tls", "query", "system-proxy"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
tokio-tungstenite = "0.29"
|
||||
futures-util = { version = "0.3", features = ["sink"] }
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
FPV-RID 本地备案登记站,Rust + Axum + SQLite。对应 GitHub 仓库:`zhangshuochi/Rid_Drone_Receivev`。
|
||||
|
||||
Rust 版本复用原有数据格式和网页,增加编辑、照片删除、分页和档案同步重试。项目仅保留 Rust 后端,不再提供 Node.js 回退版本。设备上位机及无线 RID 接收不在本仓库实现范围内。
|
||||
前端使用 Leptos/Rust 编译为 WebAssembly,后端使用 Axum/Tokio;保留原有数据格式,支持编辑、照片删除、分页和档案同步重试。项目仅保留 Rust 后端,不再提供 Node.js 回退版本。当前提供 USB 串口、UDP/TCP 接收传输层;厂商 RID 报文解码仍需实机协议。原版设备写入上位机不在本仓库实现范围内。
|
||||
|
||||
## Rust 启动与验证
|
||||
|
||||
- 发布目录:双击 `启动Rust版.cmd`,打开 http://127.0.0.1:8787/ ,无需 Node.js。
|
||||
- 开发:`cargo run -- --data-root .`;Release:`cargo build --release --locked`。
|
||||
- 本机现有终端先执行 `. ./scripts/rust-env.ps1`,加载集中工具目录。
|
||||
- 首次构建前端:`cargo xtask web`;开发运行:`cargo run -p fpv-rid-registry -- --data-root .`。
|
||||
- 统一发布:`cargo xtask package`,先构建前端与 Worker,再内嵌资源并生成 Release 发布包。
|
||||
- 仓库 `启动源码版.cmd` 默认转到 Rust。
|
||||
- 检查:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`。
|
||||
- 接口与数据验收:`node scripts/verify.mjs`,仅使用独立临时目录。
|
||||
@@ -25,11 +27,13 @@ Rust 版本复用原有数据格式和网页,增加编辑、照片删除、分
|
||||
| --- | --- |
|
||||
| `src/` | Rust HTTP 服务、SQLite 事务、档案备份和导出 |
|
||||
| `Cargo.toml`、`Cargo.lock`、`rust-toolchain.toml` | Rust 依赖、锁定版本与工具链 |
|
||||
| `registry/web/` | 登记网页、样式、二维码脚本和图标 |
|
||||
| `crates/web-ui/` | Leptos/Rust 前端、登记交互、C 方案地图界面及样式 |
|
||||
| `crates/web-worker/` | Rust/Wasm 实时解码、状态合并及绘制反馈 |
|
||||
| `crates/rid-shared/`、`crates/realtime-core/` | 共享协议、有界实时状态与合成负载工具 |
|
||||
| `xtask/`、`build.rs` | 统一构建和网页资源嵌入 |
|
||||
| `scripts/` | 环境、打包、兼容及浏览器验收脚本 |
|
||||
| `docs/原版使用说明.md` | 新版2附带的原始说明 |
|
||||
| `docs/架构与RID联动.md` | 数据流、字段和对接方式 |
|
||||
| `docs/接口清单.md` | 本地 HTTP 接口说明 |
|
||||
| `doc/realtime/platform/plan/` | Rust 全栈与实时目标架构、计划 |
|
||||
| `doc/registry/rust/接口变更.md`、`doc/realtime/platform/api/` | 登记接口及实时/地图/接收契约 |
|
||||
| `启动源码版.cmd` | Windows 启动入口 |
|
||||
|
||||
## 开发验收脚本
|
||||
@@ -44,9 +48,22 @@ Rust 版本复用原有数据格式和网页,增加编辑、照片删除、分
|
||||
|
||||
## 后续开发先看哪里
|
||||
|
||||
- 改登记表单和页面:`registry/web/index.html`、`app.js`、`app.css`。
|
||||
- 改登记交互:`crates/web-ui/src/registry.rs`;既有布局在 `registry.html`,样式在 `crates/web-ui/public/app.css`。
|
||||
- 改实时地图:`crates/web-ui/src/realtime_ui.rs`;地图库互操作在 `public/map-adapter.js`,业务状态与协议为 Rust。
|
||||
- 改校验规则或查询:`src/store.rs`。
|
||||
- 改本地接口和档案卡:`src/http.rs`、`src/archive.rs`;数据库逻辑在 `src/store.rs`。
|
||||
- 接入无人机监管平台:先看 `docs/架构与RID联动.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。
|
||||
- 接入无人机监管平台:先看 `doc/realtime/platform/api/receiver-transports.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。
|
||||
|
||||
当前服务仅监听 `127.0.0.1`,没有登录认证。要让局域网内的其他电脑读取档案,应由 RID 平台后端做受控同步接口,不能直接把这个本地服务改成对全网开放。
|
||||
|
||||
## 实时目标工作台
|
||||
|
||||
打开 http://127.0.0.1:8787/realtime 使用已选择的 C 方案(目标研判)。当前提供天地图在线代理、自动离线回退、GPU 批量目标、选择和有限轨迹;离线支持 XYZ 栅格瓦片与 MBTiles,但未附带实际地图数据,已具备 USB/UDP/TCP 传输接入,厂商 RID 解析待报文确认。正常运行不自动生成模拟目标。
|
||||
|
||||
协议与隔离仿真步骤见 [实时通道 v1](doc/realtime/platform/api/synthetic-protocol.md)。实施范围及验证边界见 [实施记录](doc/realtime/platform/review/implementation-status.md)。
|
||||
|
||||
前端构建工具: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 配置在服务器环境中,不能提交到源码。
|
||||
|
||||
USB / UDP / TCP 的配置、帧格式及实机边界见 [接收端说明](doc/realtime/platform/api/receiver-transports.md)。配置默认禁用,不自动打开串口;未知厂商格式先使用原始诊断。
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use std::{
|
||||
env, fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn collect(root: &Path, folder: &Path, output: &mut String) {
|
||||
let mut files: Vec<_> = fs::read_dir(folder)
|
||||
.expect("frontend assets")
|
||||
.map(|f| f.unwrap().path())
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
if path.file_name().unwrap().to_string_lossy().starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
assert!(!path.is_symlink(), "frontend assets must not be symlinks");
|
||||
if path.is_dir() {
|
||||
collect(root, &path, output);
|
||||
continue;
|
||||
}
|
||||
let relative = path
|
||||
.strip_prefix(root)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let mime = match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
|
||||
"html" => "text/html; charset=utf-8",
|
||||
"js" | "mjs" => "text/javascript; charset=utf-8",
|
||||
"wasm" => "application/wasm",
|
||||
"css" => "text/css; charset=utf-8",
|
||||
"png" => "image/png",
|
||||
"svg" => "image/svg+xml",
|
||||
"json" => "application/json",
|
||||
_ => continue,
|
||||
};
|
||||
output.push_str(&format!(
|
||||
"{:?} => Some((include_bytes!({:?}), {:?})),\n",
|
||||
format!("/{relative}"),
|
||||
path.to_string_lossy(),
|
||||
mime
|
||||
));
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("dist/web-ui");
|
||||
println!("cargo:rerun-if-changed={}", root.display());
|
||||
assert!(
|
||||
root.join("index.html").is_file(),
|
||||
"Build Rust frontend first: cargo xtask web"
|
||||
);
|
||||
let mut output = r#"pub fn resource(path: &str) -> Option<(&'static [u8], &'static str)> { let path = if path == "/" || path == "/realtime" { "/index.html" } else { path }; match path {
|
||||
"#.to_owned();
|
||||
collect(&root, &root, &mut output);
|
||||
output.push_str("_ => None } }\n");
|
||||
fs::write(
|
||||
PathBuf::from(env::var("OUT_DIR").unwrap()).join("web_assets.rs"),
|
||||
output,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "realtime-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
|
||||
[[bin]]
|
||||
name = "rid-capacity"
|
||||
path = "src/bin/capacity.rs"
|
||||
@@ -0,0 +1,42 @@
|
||||
use realtime_core::Store;
|
||||
use rid_shared::Observation;
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn main() {
|
||||
let count: usize = std::env::args()
|
||||
.nth(1)
|
||||
.unwrap_or("10000".into())
|
||||
.parse()
|
||||
.expect("target count");
|
||||
assert!((1..=100000).contains(&count));
|
||||
let mut store = Store::new(count, count * 2, 30000, 1);
|
||||
let start = Instant::now();
|
||||
for sequence in 0..100 {
|
||||
for id in 0..count {
|
||||
store.apply(
|
||||
Observation {
|
||||
target_id: format!("SIM-{id}"),
|
||||
receiver_id: "SIM".into(),
|
||||
source_epoch: 1,
|
||||
sequence,
|
||||
longitude: 120.0 + id as f64 * 0.00001,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
},
|
||||
sequence,
|
||||
);
|
||||
}
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
println!(
|
||||
"{{\"kind\":\"state-core-only-not-end-to-end\",\"targets\":{count},\"updates\":{},\"seconds\":{},\"updates_per_second\":{},\"measured_at_unix_ms\":{now}}}",
|
||||
count * 100,
|
||||
elapsed.as_secs_f64(),
|
||||
count as f64 * 100.0 / elapsed.as_secs_f64()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Explicit synthetic input generator for an isolated --simulation-api server.
|
||||
use rid_shared::Observation;
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut count = 1000usize;
|
||||
let mut interval_ms = 20u64;
|
||||
let mut seconds = 30u64;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
let value = args.next().ok_or("missing argument value")?;
|
||||
match arg.as_str() {
|
||||
"--targets" => count = value.parse()?,
|
||||
"--interval-ms" => interval_ms = value.parse()?,
|
||||
"--seconds" => seconds = value.parse()?,
|
||||
_ => {
|
||||
return Err(
|
||||
"usage: rid-simulator [--targets 1000] [--interval-ms 20] [--seconds 30]"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !(1..=10000).contains(&count)
|
||||
|| !(1..=1000).contains(&interval_ms)
|
||||
|| !(1..=7200).contains(&seconds)
|
||||
{
|
||||
return Err("invalid load; targets 1..10000, interval 1..1000 ms, seconds 1..7200".into());
|
||||
}
|
||||
eprintln!(
|
||||
"SYNTHETIC DATA ONLY: localhost:8787 must use --simulation-api. Requested interval is not a throughput guarantee."
|
||||
);
|
||||
let epoch = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
|
||||
let socket = TcpStream::connect_timeout(&"127.0.0.1:8787".parse()?, Duration::from_secs(2))?;
|
||||
socket.set_nodelay(true)?;
|
||||
socket.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
socket.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut connection = BufReader::new(socket);
|
||||
let start = Instant::now();
|
||||
let mut sequence = 0;
|
||||
let mut overruns = 0;
|
||||
while start.elapsed() < Duration::from_secs(seconds) {
|
||||
sequence += 1;
|
||||
let tick = Instant::now();
|
||||
for offset in (0..count).step_by(1000) {
|
||||
let batch: Vec<_> = (offset..(offset + 1000).min(count))
|
||||
.map(|id| Observation {
|
||||
target_id: format!("SIM-{id:05}"),
|
||||
receiver_id: "SIMULATOR".into(),
|
||||
source_epoch: epoch,
|
||||
sequence,
|
||||
longitude: 120.0
|
||||
+ (id as f64).cos() * 0.1
|
||||
+ ((sequence as f64) * 0.01).sin() * 0.005,
|
||||
latitude: 30.0 + (id as f64).sin() * 0.1,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: (id % 360) as f32,
|
||||
})
|
||||
.collect();
|
||||
let body = postcard::to_allocvec(&batch)?;
|
||||
write!(
|
||||
connection.get_mut(),
|
||||
"POST /api/realtime/ingest HTTP/1.1\r\nHost: 127.0.0.1:8787\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
connection.get_mut().write_all(&body)?;
|
||||
let mut line = String::new();
|
||||
connection.read_line(&mut line)?;
|
||||
if !line.starts_with("HTTP/1.1 200") {
|
||||
return Err(format!("input rejected: {}", line.trim()).into());
|
||||
}
|
||||
let mut length = None;
|
||||
loop {
|
||||
line.clear();
|
||||
if connection.read_line(&mut line)? == 0 {
|
||||
return Err("server closed response headers".into());
|
||||
}
|
||||
if line.len() > 8192 {
|
||||
return Err("response header exceeds limit".into());
|
||||
}
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':')
|
||||
&& name.eq_ignore_ascii_case("content-length")
|
||||
{
|
||||
length = Some(value.trim().parse::<usize>()?);
|
||||
}
|
||||
}
|
||||
let length = length
|
||||
.filter(|n| *n <= 4096)
|
||||
.ok_or("invalid response length")?;
|
||||
let mut response = vec![0; length];
|
||||
connection.read_exact(&mut response)?;
|
||||
}
|
||||
if let Some(remaining) = Duration::from_millis(interval_ms).checked_sub(tick.elapsed()) {
|
||||
std::thread::sleep(remaining)
|
||||
} else {
|
||||
overruns += 1;
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"{{\"mode\":\"synthetic-http-postcard\",\"targets\":{count},\"requested_interval_ms\":{interval_ms},\"ticks\":{sequence},\"overruns\":{overruns},\"actual_seconds\":{}}}",
|
||||
start.elapsed().as_secs_f64()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Bounded latest-state store, independent of SQLite and archive generation.
|
||||
use rid_shared::{Frame, Metrics, Observation, PROTOCOL_VERSION, Target};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
struct Track {
|
||||
target: Target,
|
||||
sources: HashMap<String, (u64, u64)>,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
tracks: HashMap<String, Track>,
|
||||
changes: VecDeque<(u64, String)>,
|
||||
journal_capacity: usize,
|
||||
epoch: u64,
|
||||
ttl_ms: u64,
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
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);
|
||||
Self {
|
||||
tracks: HashMap::new(),
|
||||
changes: VecDeque::new(),
|
||||
journal_capacity,
|
||||
epoch,
|
||||
ttl_ms,
|
||||
metrics: Metrics {
|
||||
capacity,
|
||||
..Metrics::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn changed(&mut self, id: String) {
|
||||
self.metrics.sequence += 1;
|
||||
if self.changes.len() == self.journal_capacity {
|
||||
self.changes.pop_front();
|
||||
}
|
||||
self.changes.push_back((self.metrics.sequence, id));
|
||||
}
|
||||
|
||||
/// Multiple receivers use arrival order; no unverified sensor-time fusion is implied.
|
||||
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)
|
||||
{
|
||||
self.metrics.stale += 1;
|
||||
return false;
|
||||
}
|
||||
} else if track.sources.len() >= 8 {
|
||||
self.metrics.rejected += 1;
|
||||
return false;
|
||||
}
|
||||
track.sources.insert(
|
||||
observation.receiver_id.clone(),
|
||||
(observation.source_epoch, observation.sequence),
|
||||
);
|
||||
track.target = Target {
|
||||
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 {
|
||||
observation,
|
||||
received_at_ms: now_ms,
|
||||
},
|
||||
sources,
|
||||
},
|
||||
);
|
||||
}
|
||||
self.metrics.accepted += 1;
|
||||
self.changed(id);
|
||||
true
|
||||
}
|
||||
|
||||
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 {
|
||||
self.tracks.remove(&id);
|
||||
self.metrics.expired += 1;
|
||||
self.changed(id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(&self, since: Option<u64>, now_ms: u64) -> Frame {
|
||||
let snapshot = since.is_none_or(|s| {
|
||||
s > self.metrics.sequence
|
||||
|| self
|
||||
.changes
|
||||
.front()
|
||||
.is_some_and(|(oldest, _)| s.saturating_add(1) < *oldest)
|
||||
});
|
||||
let mut targets = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
if snapshot {
|
||||
targets.extend(self.tracks.values().map(|t| t.target.clone()));
|
||||
} else {
|
||||
let mut ids = HashSet::new();
|
||||
for (_, id) in self
|
||||
.changes
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|(seq, _)| *seq > since.unwrap())
|
||||
{
|
||||
if ids.insert(id) {
|
||||
if let Some(track) = self.tracks.get(id) {
|
||||
targets.push(track.target.clone());
|
||||
} else {
|
||||
removed.push(id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Frame {
|
||||
version: PROTOCOL_VERSION,
|
||||
epoch: self.epoch,
|
||||
sequence: self.metrics.sequence,
|
||||
snapshot,
|
||||
server_time_ms: now_ms,
|
||||
targets,
|
||||
removed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn metrics(&self) -> Metrics {
|
||||
Metrics {
|
||||
active_targets: self.tracks.len(),
|
||||
..self.metrics.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn sample(id: &str, sequence: u64) -> Observation {
|
||||
Observation {
|
||||
target_id: id.into(),
|
||||
receiver_id: "station-1".into(),
|
||||
source_epoch: 1,
|
||||
sequence,
|
||||
longitude: 120.0,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stale_and_capacity_are_bounded() {
|
||||
let mut s = Store::new(1, 4, 100, 1);
|
||||
assert!(s.apply(sample("a", 2), 0));
|
||||
assert!(!s.apply(sample("a", 1), 1));
|
||||
assert!(!s.apply(sample("b", 1), 1));
|
||||
assert_eq!(s.metrics().active_targets, 1);
|
||||
assert_eq!(s.metrics().stale, 1);
|
||||
s.expire(100);
|
||||
assert!(s.apply(sample("b", 1), 100));
|
||||
}
|
||||
#[test]
|
||||
fn coalesces_and_resynchronizes_after_journal_overflow() {
|
||||
let mut s = Store::new(4, 2, 100, 42);
|
||||
for seq in 1..=4 {
|
||||
s.apply(sample("a", seq), seq);
|
||||
}
|
||||
let frame = s.frame(Some(2), 4);
|
||||
assert!(!frame.snapshot);
|
||||
assert_eq!(frame.targets.len(), 1);
|
||||
assert_eq!(frame.targets[0].observation.sequence, 4);
|
||||
assert!(s.frame(Some(0), 4).snapshot);
|
||||
s.expire(104);
|
||||
let frame = s.frame(Some(4), 104);
|
||||
assert_eq!(frame.removed, ["a"]);
|
||||
assert_eq!(frame.epoch, 42);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_invalid_values_and_previous_source_session() {
|
||||
let mut s = Store::new(2, 4, 100, 1);
|
||||
let mut a = sample("a", 1);
|
||||
a.longitude = f64::NAN;
|
||||
assert!(!s.apply(a, 0));
|
||||
let mut a = sample("a", 1);
|
||||
a.source_epoch = 2;
|
||||
assert!(s.apply(a, 1));
|
||||
assert!(!s.apply(sample("a", 100), 2));
|
||||
assert_eq!(s.frame(None, 2).targets[0].observation.source_epoch, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "rid-shared"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -0,0 +1,68 @@
|
||||
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 1;
|
||||
pub const MAX_BATCH: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Observation {
|
||||
pub target_id: String,
|
||||
pub receiver_id: String,
|
||||
/// Monotonically increasing receiver boot/session number.
|
||||
pub source_epoch: u64,
|
||||
pub sequence: u64,
|
||||
pub longitude: f64,
|
||||
pub latitude: f64,
|
||||
/// WGS84 ellipsoid altitude in metres, not height above ground.
|
||||
pub altitude_m: f32,
|
||||
pub heading_deg: f32,
|
||||
}
|
||||
|
||||
impl Observation {
|
||||
pub fn validate(&self) -> bool {
|
||||
fn identity(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 64
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
identity(&self.target_id)
|
||||
&& identity(&self.receiver_id)
|
||||
&& self.longitude.is_finite()
|
||||
&& (-180.0..=180.0).contains(&self.longitude)
|
||||
&& self.latitude.is_finite()
|
||||
&& (-90.0..=90.0).contains(&self.latitude)
|
||||
&& self.altitude_m.is_finite()
|
||||
&& (-1000.0..=100000.0).contains(&self.altitude_m)
|
||||
&& self.heading_deg.is_finite()
|
||||
&& (0.0..360.0).contains(&self.heading_deg)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Target {
|
||||
pub observation: Observation,
|
||||
pub received_at_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Frame {
|
||||
pub version: u16,
|
||||
pub epoch: u64,
|
||||
pub sequence: u64,
|
||||
pub snapshot: bool,
|
||||
pub server_time_ms: u64,
|
||||
pub targets: Vec<Target>,
|
||||
pub removed: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug, Serialize)]
|
||||
pub struct Metrics {
|
||||
pub active_targets: usize,
|
||||
pub accepted: u64,
|
||||
pub stale: u64,
|
||||
pub rejected: u64,
|
||||
pub expired: u64,
|
||||
pub capacity: usize,
|
||||
pub sequence: u64,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "rid-web-ui"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
leptos = { version = "=0.8.22", features = ["csr"] }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
web-sys = { version = "0.3", features = ["Window", "Location", "Document", "HtmlElement", "Element", "NodeList", "HtmlInputElement", "HtmlButtonElement", "HtmlAnchorElement", "HtmlDialogElement", "HtmlCanvasElement", "CanvasRenderingContext2d", "File", "FileList", "Blob", "Url", "Navigator", "Clipboard", "Worker", "WorkerOptions", "WorkerType", "MessageEvent", "CustomEvent", "console"] }
|
||||
js-sys = "0.3"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
gloo-net = "0.6"
|
||||
gloo-timers = { version = "0.3", features = ["futures"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
qrcodegen = "1"
|
||||
@@ -0,0 +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="light"><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 rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
|
||||
@@ -0,0 +1,960 @@
|
||||
/* Mission Control Apple-style Translucent Dark Theme for Registration */
|
||||
:root {
|
||||
--mc-bg: #060b14;
|
||||
--mc-shell-bg: rgba(8, 15, 28, 0.82);
|
||||
--mc-panel-bg: rgba(9, 18, 36, 0.82);
|
||||
--mc-panel-raised: rgba(14, 26, 48, 0.88);
|
||||
--mc-panel-dense: rgba(7, 13, 24, 0.94);
|
||||
--mc-panel-blur: blur(28px) saturate(190%);
|
||||
--mc-border: rgba(48, 85, 140, 0.38);
|
||||
--mc-border-light: rgba(255, 255, 255, 0.1);
|
||||
--mc-border-glow: rgba(26, 114, 255, 0.45);
|
||||
--mc-accent: #38bdf8;
|
||||
--mc-accent-dark: #1557b0;
|
||||
--mc-accent-glow: rgba(26, 114, 255, 0.3);
|
||||
--mc-success: #30d158;
|
||||
--mc-warning: #ff9f0a;
|
||||
--mc-danger: #ff453a;
|
||||
--mc-text: #f8fafc;
|
||||
--mc-text-muted: #94a3b8;
|
||||
--mc-text-dim: #64748b;
|
||||
--mc-radius-lg: 14px;
|
||||
--mc-radius-md: 10px;
|
||||
--mc-radius-sm: 8px;
|
||||
--mc-radius-pill: 9999px;
|
||||
--mc-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
*, *::before, *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: var(--mc-bg);
|
||||
background-image:
|
||||
radial-gradient(circle at 50% 0%, rgba(26, 114, 255, 0.12) 0%, transparent 60%),
|
||||
radial-gradient(circle at 85% 90%, rgba(56, 189, 248, 0.05) 0%, transparent 50%);
|
||||
background-attachment: fixed;
|
||||
color: var(--mc-text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
button, input, select {
|
||||
font: inherit;
|
||||
}
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Custom Scrollbars */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(48, 182, 245, 0.5);
|
||||
}
|
||||
|
||||
.shell {
|
||||
max-width: 1360px;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
background: var(--mc-shell-bg);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border-left: 1px solid var(--mc-border);
|
||||
border-right: 1px solid var(--mc-border);
|
||||
box-shadow: 0 0 80px rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Topbar */
|
||||
.topbar {
|
||||
height: 64px;
|
||||
background: rgba(10, 18, 32, 0.85);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border-bottom: 1px solid var(--mc-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 40px;
|
||||
gap: 16px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.topbar .brand-mark {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
object-fit: contain;
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 4px;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
box-shadow: 0 0 16px rgba(48, 182, 245, 0.4);
|
||||
}
|
||||
|
||||
.brand-copy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.brand-copy strong {
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.04em;
|
||||
color: #fff;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.brand-copy small {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.brand-copy small a {
|
||||
color: var(--mc-accent);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
margin-left: 4px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.brand-copy small a:hover {
|
||||
color: #fff;
|
||||
text-shadow: 0 0 8px var(--mc-accent);
|
||||
}
|
||||
|
||||
.top-status {
|
||||
margin-left: auto;
|
||||
border: 1px solid rgba(0, 230, 118, 0.35);
|
||||
background: rgba(0, 230, 118, 0.12);
|
||||
border-radius: var(--mc-radius-pill);
|
||||
color: var(--mc-success);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
padding: 6px 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
box-shadow: 0 0 12px rgba(0, 230, 118, 0.2);
|
||||
}
|
||||
|
||||
.top-status i {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--mc-success);
|
||||
box-shadow: 0 0 8px var(--mc-success);
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 32px 40px 48px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Hero Section */
|
||||
.hero {
|
||||
margin-bottom: 26px;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.01em;
|
||||
color: #fff;
|
||||
margin: 0 0 8px 0;
|
||||
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.hero p {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
max-width: 780px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Two Columns (Form + QR Result) */
|
||||
.columns {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
/* Panels */
|
||||
.panel {
|
||||
background: var(--mc-panel-bg);
|
||||
backdrop-filter: var(--mc-panel-blur);
|
||||
-webkit-backdrop-filter: var(--mc-panel-blur);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
box-shadow: var(--mc-shadow);
|
||||
padding: 26px 28px;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 15px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px solid var(--mc-border-light);
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.panel-head > div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.panel-head h2 {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.step {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(26, 114, 255, 0.25);
|
||||
border: 1px solid rgba(56, 140, 248, 0.4);
|
||||
color: #38bdf8;
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.step.muted {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-color: var(--mc-border-light);
|
||||
color: var(--mc-text-muted);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.subtle {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Form Styles */
|
||||
label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
display: block;
|
||||
margin: 0 0 8px;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
label em {
|
||||
color: var(--mc-danger);
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
label .optional {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
input {
|
||||
height: 42px;
|
||||
width: 100%;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(6, 12, 22, 0.65);
|
||||
padding: 0 14px;
|
||||
color: #fff;
|
||||
outline: none;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 0 0 3px rgba(48, 182, 245, 0.2);
|
||||
background: rgba(8, 16, 28, 0.85);
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 6px 0 20px;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.field-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.input-prefix {
|
||||
height: 42px;
|
||||
display: flex;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
overflow: hidden;
|
||||
background: rgba(6, 12, 22, 0.65);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.input-prefix span {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 58px;
|
||||
background: rgba(14, 26, 46, 0.8);
|
||||
color: var(--mc-accent);
|
||||
font-weight: 800;
|
||||
font-size: 13px;
|
||||
border-right: 1px solid var(--mc-border-light);
|
||||
}
|
||||
|
||||
.input-prefix input {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.input-prefix:focus-within {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 0 0 3px rgba(48, 182, 245, 0.2);
|
||||
}
|
||||
|
||||
.photo-fields {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.photo-fields input[type=file] {
|
||||
padding: 8px 10px;
|
||||
height: auto;
|
||||
min-height: 42px;
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
.photo-fields + .hint {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
/* Primary Submit Button */
|
||||
.primary {
|
||||
height: 46px;
|
||||
width: 100%;
|
||||
border: 1px solid rgba(147, 197, 253, 0.35);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: linear-gradient(180deg, #1d68cf 0%, #1557b0 100%);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
box-shadow: 0 4px 14px rgba(21, 87, 176, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.25);
|
||||
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.primary:hover:not(:disabled) {
|
||||
background: linear-gradient(180deg, #2575e6 0%, #1a62c6 100%);
|
||||
box-shadow: 0 6px 18px rgba(21, 87, 176, 0.55);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.primary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.form-message {
|
||||
min-height: 18px;
|
||||
margin: 12px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--mc-success);
|
||||
}
|
||||
.form-message.error {
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
/* Empty State */
|
||||
.empty-state {
|
||||
height: 400px;
|
||||
border: 1px dashed rgba(64, 150, 255, 0.3);
|
||||
border-radius: var(--mc-radius-md);
|
||||
background: rgba(6, 12, 22, 0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
color: var(--mc-text-dim);
|
||||
gap: 10px;
|
||||
text-align: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.empty-state b {
|
||||
font-size: 15px;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
|
||||
.empty-state span {
|
||||
font-size: 12px;
|
||||
max-width: 260px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.empty-glyph {
|
||||
height: 64px;
|
||||
width: 64px;
|
||||
border-radius: var(--mc-radius-lg);
|
||||
background: rgba(14, 26, 46, 0.6);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
color: var(--mc-accent);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 32px;
|
||||
margin-bottom: 6px;
|
||||
box-shadow: 0 0 20px rgba(48, 182, 245, 0.2);
|
||||
}
|
||||
|
||||
/* Record Result Panel */
|
||||
.record-result {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
.record-result[hidden], .empty-state[hidden], #history-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.qr-stage {
|
||||
width: 210px;
|
||||
height: 210px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #ffffff;
|
||||
border: 2px solid var(--mc-border-glow);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 10px;
|
||||
box-shadow: 0 10px 32px rgba(48, 182, 245, 0.25), inset 0 0 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
.qr-stage svg {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.record-kicker {
|
||||
font-size: 11px;
|
||||
color: var(--mc-success);
|
||||
font-weight: 800;
|
||||
margin-top: 16px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.uas-display {
|
||||
font-size: 26px;
|
||||
font-weight: 850;
|
||||
letter-spacing: 0.04em;
|
||||
margin: 4px 0 16px;
|
||||
color: var(--mc-accent);
|
||||
text-shadow: 0 0 12px rgba(48, 182, 245, 0.35);
|
||||
}
|
||||
|
||||
.result-fields {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
border-top: 1px solid var(--mc-border-light);
|
||||
border-bottom: 1px solid var(--mc-border-light);
|
||||
}
|
||||
|
||||
.result-fields div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 9px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.result-fields dt {
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
.result-fields dd {
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
text-align: right;
|
||||
color: #fff;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.saved-photos {
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.saved-photos[hidden], .saved-photos a[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.saved-photos a {
|
||||
width: 50%;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
color: var(--mc-accent);
|
||||
text-decoration: none;
|
||||
font-size: 11px;
|
||||
padding: 6px;
|
||||
background: rgba(6, 12, 22, 0.5);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.saved-photos a:hover {
|
||||
border-color: var(--mc-accent);
|
||||
background: rgba(14, 26, 46, 0.7);
|
||||
}
|
||||
.saved-photos img {
|
||||
width: 100%;
|
||||
height: 90px;
|
||||
object-fit: contain;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
border-radius: 4px;
|
||||
display: block;
|
||||
}
|
||||
.saved-photos span {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.url-box {
|
||||
align-self: stretch;
|
||||
background: rgba(6, 12, 22, 0.7);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
margin-top: 16px;
|
||||
padding: 10px 14px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.url-box span {
|
||||
display: block;
|
||||
color: var(--mc-text-dim);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.url-box code {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--mc-accent);
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.result-actions {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.secondary, .ghost {
|
||||
height: 38px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.secondary {
|
||||
background: rgba(32, 65, 199, 0.25);
|
||||
color: #fff;
|
||||
border: 1px solid var(--mc-border);
|
||||
}
|
||||
.secondary:hover {
|
||||
background: rgba(32, 65, 199, 0.45);
|
||||
border-color: var(--mc-accent);
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--mc-text-muted);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
}
|
||||
.ghost:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.action-link {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.result-tip {
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-dim);
|
||||
line-height: 1.55;
|
||||
align-self: stretch;
|
||||
margin: 14px 0 0;
|
||||
}
|
||||
|
||||
/* History Panel */
|
||||
.history-panel {
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.history-head {
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.history-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.history-search {
|
||||
position: relative;
|
||||
width: 280px;
|
||||
flex: 0 1 280px;
|
||||
}
|
||||
|
||||
.history-search input {
|
||||
height: 36px;
|
||||
padding: 0 66px 0 12px;
|
||||
font-size: 12px;
|
||||
background: rgba(6, 12, 22, 0.7);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.history-search #search-count {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.select-all {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
color: var(--mc-text-muted);
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.select-all input, .archive-select input {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: var(--mc-accent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.export-button {
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(14, 26, 46, 0.6);
|
||||
color: var(--mc-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.export-button:hover:not(:disabled) {
|
||||
background: rgba(32, 65, 199, 0.4);
|
||||
color: #fff;
|
||||
}
|
||||
.export-button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.text-button {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--mc-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
padding: 6px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.text-button:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.history-message {
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: var(--mc-text-dim);
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.history-message.error {
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
.history-empty {
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 13px;
|
||||
padding: 30px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.history-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.archive-card {
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 16px;
|
||||
background: rgba(8, 16, 28, 0.6);
|
||||
transition: all 0.2s ease;
|
||||
position: relative;
|
||||
}
|
||||
.archive-card:hover {
|
||||
border-color: var(--mc-accent);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4), 0 0 12px rgba(48, 182, 245, 0.2);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.archive-card.selected {
|
||||
border-color: var(--mc-accent);
|
||||
background: rgba(14, 26, 46, 0.8);
|
||||
box-shadow: 0 0 0 2px rgba(48, 182, 245, 0.3);
|
||||
}
|
||||
|
||||
.archive-card h3 {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
margin: 0 0 4px;
|
||||
color: #fff;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.archive-card strong {
|
||||
color: var(--mc-accent);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.archive-card p {
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
margin: 8px 0 12px;
|
||||
}
|
||||
|
||||
.archive-thumbs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
.archive-thumbs > div {
|
||||
height: 100px;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: 6px;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 11px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.archive-thumbs img {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.archive-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.archive-actions a, .archive-actions button {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--mc-text);
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: 6px;
|
||||
padding: 6px 10px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
.archive-actions a:hover, .archive-actions button:hover {
|
||||
background: rgba(48, 182, 245, 0.2);
|
||||
border-color: var(--mc-accent);
|
||||
color: #fff;
|
||||
}
|
||||
.archive-actions .delete-record {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: var(--mc-danger);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
.archive-actions .delete-record:hover {
|
||||
background: rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 22px;
|
||||
color: var(--mc-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.pagination button, .archive-warning button {
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.pagination button:hover:not(:disabled) {
|
||||
background: rgba(48, 182, 245, 0.25);
|
||||
border-color: var(--mc-accent);
|
||||
}
|
||||
.pagination button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.archive-warning {
|
||||
padding: 14px 18px;
|
||||
background: rgba(255, 159, 10, 0.15);
|
||||
border: 1px solid rgba(255, 159, 10, 0.35);
|
||||
color: var(--mc-warning);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/* Edit Dialog Apple Glass Modal */
|
||||
dialog {
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
padding: 30px;
|
||||
max-width: 650px;
|
||||
width: calc(100% - 32px);
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
color: #fff;
|
||||
background: rgba(11, 22, 39, 0.92);
|
||||
backdrop-filter: blur(28px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(190%);
|
||||
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
background: rgba(4, 8, 16, 0.75);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
dialog h2 {
|
||||
margin-top: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 750;
|
||||
color: #fff;
|
||||
}
|
||||
dialog p {
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: var(--mc-text-muted);
|
||||
}
|
||||
dialog .edit-help {
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
.edit-photos {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.edit-photos fieldset {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--mc-border-light);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
background: rgba(6, 12, 22, 0.5);
|
||||
padding: 12px;
|
||||
}
|
||||
.edit-photos legend {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--mc-accent);
|
||||
padding: 0 6px;
|
||||
}
|
||||
.edit-photos img {
|
||||
width: 100%;
|
||||
height: 130px;
|
||||
object-fit: contain;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.edit-photos input[type=file] {
|
||||
width: 100%;
|
||||
font-size: 11px;
|
||||
}
|
||||
.edit-delete {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
font-size: 11px;
|
||||
color: var(--mc-danger);
|
||||
}
|
||||
|
||||
footer {
|
||||
border-top: 1px solid var(--mc-border-light);
|
||||
padding: 18px 40px;
|
||||
color: var(--mc-text-dim);
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
@media (max-width: 850px) {
|
||||
.topbar { padding: 0 20px; }
|
||||
main { padding: 24px 18px; }
|
||||
.columns { grid-template-columns: 1fr; }
|
||||
.history-controls { width: 100%; justify-content: flex-start; }
|
||||
.history-search { flex: 1 1 240px; }
|
||||
}
|
||||
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,103 @@
|
||||
// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust.
|
||||
import * as maplibre from './vendor/maplibre-gl.mjs';
|
||||
maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||
let map, layer, latest, ids = [], selected = '', pending = false;
|
||||
let frameTimes = [], lastFrame = 0;
|
||||
let marker=null, history=[], lastTrail=0;
|
||||
let centered=false, workerWasmBytes=0;
|
||||
function shader(gl, type, source) {
|
||||
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
||||
}
|
||||
function create(container) {
|
||||
if (map) map.remove();
|
||||
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:35,bearing:0,attributionControl:false,
|
||||
style:{version:8,sources:{
|
||||
'tdt-base':{type:'raster',tiles:['/api/maps/tile/img_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18,attribution:'天地图卫星 / 本地离线资源'},
|
||||
'tdt-labels':{type:'raster',tiles:['/api/maps/tile/cia_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18}
|
||||
},layers:[
|
||||
{id:'background',type:'background',paint:{'background-color':'#060c18'}},
|
||||
{id:'tdt-base',type:'raster',source:'tdt-base'},
|
||||
{id:'tdt-labels',type:'raster',source:'tdt-labels'}
|
||||
]}});
|
||||
map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right');
|
||||
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
|
||||
onAdd(map,gl){
|
||||
if (!gl.drawArraysInstanced) throw new Error('WebGL2 required');
|
||||
this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat([120.1538,30.2874]);
|
||||
this.program=gl.createProgram();
|
||||
this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es
|
||||
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
|
||||
void main(){vec4 p=matrix*vec4(target.xy,0.,1.);float c=cos(target.z+bearing),s=sin(target.z+bearing);vec2 q=vec2(shape.x*c-shape.y*s,shape.x*s+shape.y*c);p.xy+=q*pixel*p.w;gl_Position=p;chosen=target.w;}`);
|
||||
this.fs=shader(gl,gl.FRAGMENT_SHADER,`#version 300 es
|
||||
precision highp float; in float chosen; out vec4 color; void main(){color=mix(vec4(.22,.74,.97,1.),vec4(1.,.75,.15,1.),chosen);}`);
|
||||
gl.attachShader(this.program,this.vs);gl.attachShader(this.program,this.fs);gl.linkProgram(this.program);
|
||||
if (!gl.getProgramParameter(this.program,gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(this.program));
|
||||
this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao);
|
||||
this.shape=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.shape);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([0,10,-6,-6,0,-2,0,10,0,-2,6,-6]),gl.STATIC_DRAW);
|
||||
const a=gl.getAttribLocation(this.program,'shape');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);
|
||||
this.instances=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.instances);gl.bufferData(gl.ARRAY_BUFFER,10000*16,gl.DYNAMIC_DRAW);
|
||||
const b=gl.getAttribLocation(this.program,'target');gl.enableVertexAttribArray(b);gl.vertexAttribPointer(b,4,gl.FLOAT,false,16,0);gl.vertexAttribDivisor(b,1);
|
||||
gl.bindVertexArray(null);this.count=0;this.matrix=gl.getUniformLocation(this.program,'matrix');this.pixel=gl.getUniformLocation(this.program,'pixel');this.bearing=gl.getUniformLocation(this.program,'bearing');
|
||||
},
|
||||
render(gl,args){
|
||||
if (!this.count) return;
|
||||
const source=args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix;
|
||||
if (!source) return;
|
||||
const m=new Float32Array(source);for(let r=0;r<4;r++)m[12+r]=source[r]*this.origin.x+source[4+r]*this.origin.y+source[12+r];
|
||||
gl.useProgram(this.program);gl.bindVertexArray(this.vao);gl.uniformMatrix4fv(this.matrix,false,m);gl.uniform2f(this.pixel,2/this.map.getCanvas().clientWidth,2/this.map.getCanvas().clientHeight);gl.uniform1f(this.bearing,this.map.getBearing()*Math.PI/180);
|
||||
gl.disable(gl.DEPTH_TEST);gl.drawArraysInstanced(gl.TRIANGLES,0,6,this.count);gl.bindVertexArray(null);
|
||||
const now=performance.now();if(lastFrame)frameTimes.push(now-lastFrame);lastFrame=now;if(frameTimes.length>300)frameTimes.shift();
|
||||
},
|
||||
onRemove(map,gl){gl.deleteBuffer(this.shape);gl.deleteBuffer(this.instances);gl.deleteVertexArray(this.vao);gl.deleteProgram(this.program);gl.deleteShader(this.vs);gl.deleteShader(this.fs);}
|
||||
};
|
||||
map.on('load',()=>{
|
||||
// Mission Control tactical radar grid & range rings
|
||||
const features=[];
|
||||
for(let lon=118;lon<=122;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,28],[lon,32]]},properties:{}});
|
||||
for(let lat=28;lat<=32;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[118,lat],[122,lat]]},properties:{}});
|
||||
// Concentric tactical range rings around default center
|
||||
const center=[120.1538,30.2874];
|
||||
for(const radiusKm of [1, 2, 5, 10]) {
|
||||
const ring=[];
|
||||
for(let a=0;a<=360;a+=6){
|
||||
const rad=a*Math.PI/180;
|
||||
const dLat=(radiusKm/111)*Math.cos(rad);
|
||||
const dLon=(radiusKm/(111*Math.cos(center[1]*Math.PI/180)))*Math.sin(rad);
|
||||
ring.push([center[0]+dLon, center[1]+dLat]);
|
||||
}
|
||||
features.push({type:'Feature',geometry:{type:'LineString',coordinates:ring},properties:{}});
|
||||
}
|
||||
map.addSource('grid',{type:'geojson',data:{type:'FeatureCollection',features}});
|
||||
map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}});
|
||||
map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
|
||||
map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}});
|
||||
map.addLayer(layer);flush();
|
||||
});
|
||||
map.on('click',event=>{
|
||||
if(!latest)return;let index=-1,distance=18;
|
||||
for(let i=0;i<ids.length;i++){const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
|
||||
if(index>=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]}));
|
||||
});
|
||||
map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);});
|
||||
return true;
|
||||
}
|
||||
function flush(){
|
||||
pending=false;if(!latest||!layer?.gl)return;const gl=layer.gl;
|
||||
const data=new Float32Array(ids.length*4);for(let i=0;i<ids.length;i++){const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[i*4]=p.x-layer.origin.x;data[i*4+1]=p.y-layer.origin.y;data[i*4+2]=-latest[i*4+3]*Math.PI/180;data[i*4+3]=ids[i]===selected?1:0;}
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=ids.length;map.triggerRepaint();
|
||||
const index=ids.indexOf(selected);
|
||||
if(index>=0){
|
||||
const coordinate=[latest[index*4],latest[index*4+1]];
|
||||
if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);}
|
||||
marker.getElement().textContent=selected;marker.setLngLat(coordinate);
|
||||
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
|
||||
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
|
||||
}else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
|
||||
}
|
||||
function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;map.jumpTo({center:[latest[0],latest[1]]});}if(!pending){pending=true;requestAnimationFrame(flush);}}
|
||||
function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?Array.from(latest.slice(i*4,i*4+4)):[];}
|
||||
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');return {samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
|
||||
function connection(connected){const canvas=document.querySelector('.rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
|
||||
function refresh(){for(const [id,layer]of [['tdt-base','img_w'],['tdt-labels','cia_w']])map?.getSource(id)?.setTiles([`/api/maps/tile/${layer}/{z}/{x}/{y}`]);}
|
||||
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected(){if(!map||!latest||!selected)return;const index=ids.indexOf(selected);if(index>=0){map.flyTo({center:[latest[index*4],latest[index*4+1]],zoom:Math.max(map.getZoom(),13),essential:true});}},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(){marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;}};
|
||||
@@ -0,0 +1,2 @@
|
||||
// Load the map engine only for the approved realtime workspace.
|
||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||
File diff suppressed because it is too large
Load Diff
+116
@@ -0,0 +1,116 @@
|
||||
Copyright (c) 2023, MapLibre contributors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of MapLibre GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from mapbox-gl-js v1.13 and earlier
|
||||
|
||||
Version v1.13 of mapbox-gl-js and earlier are licensed under a BSD-3-Clause license
|
||||
|
||||
Copyright (c) 2020, Mapbox
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of Mapbox GL JS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Contains code from glfx.js
|
||||
|
||||
Copyright (C) 2011 by Evan Wallace
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Contains a portion of d3-color https://github.com/d3/d3-color
|
||||
|
||||
Copyright 2010-2016 Mike Bostock
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the author nor the names of contributors may be used to
|
||||
endorse or promote products derived from this software without specific prior
|
||||
written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+819
File diff suppressed because one or more lines are too long
@@ -0,0 +1,24 @@
|
||||
use leptos::prelude::*;
|
||||
mod realtime_ui;
|
||||
mod receiver_ui;
|
||||
mod registry;
|
||||
|
||||
fn main() {
|
||||
if web_sys::window()
|
||||
.unwrap()
|
||||
.location()
|
||||
.pathname()
|
||||
.unwrap_or_default()
|
||||
== "/realtime"
|
||||
{
|
||||
mount_to_body(|| view! { <realtime_ui::Realtime/> });
|
||||
} else {
|
||||
mount_to_body(|| view! { <Registry/> });
|
||||
registry::init();
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Registry() -> impl IntoView {
|
||||
view! { <div inner_html=include_str!("registry.html")/> }
|
||||
}
|
||||
@@ -0,0 +1,802 @@
|
||||
use leptos::prelude::*;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
fn map_call(method: &str, args: &js_sys::Array) -> Result<JsValue, JsValue> {
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let rid_map = js_sys::Reflect::get(&window, &"ridMap".into())?;
|
||||
let func = js_sys::Reflect::get(&rid_map, &method.into())?;
|
||||
let func = func.dyn_into::<js_sys::Function>()?;
|
||||
func.apply(&rid_map, args)
|
||||
}
|
||||
|
||||
fn args(slice: &[JsValue]) -> js_sys::Array {
|
||||
let a = js_sys::Array::new();
|
||||
for item in slice {
|
||||
a.push(item);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Realtime() -> impl IntoView {
|
||||
let map_status = RwSignal::new(String::from("天地图卫星 / 本地离线资源"));
|
||||
let ids = RwSignal::new(Vec::<String>::new());
|
||||
let query = RwSignal::new(String::new());
|
||||
let directory_page = RwSignal::new(0usize);
|
||||
let matches = Memo::new(move |_| {
|
||||
let raw = ids.get();
|
||||
let list: Vec<String> = if raw.is_empty() {
|
||||
vec!["01号机 (DEMO)".into(), "02号机 (DEMO)".into(), "03号机 (DEMO)".into()]
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let q = query.get();
|
||||
if q.is_empty() {
|
||||
list
|
||||
} else {
|
||||
list.into_iter().filter(|id| id.contains(&q)).collect()
|
||||
}
|
||||
});
|
||||
let visible_page = Memo::new(move |_| {
|
||||
directory_page
|
||||
.get()
|
||||
.min(matches.get().len().saturating_sub(1) / 100)
|
||||
});
|
||||
let input_mode = RwSignal::new(String::from("接收状态加载中"));
|
||||
let selected = RwSignal::new(String::from("01号机 (DEMO)"));
|
||||
let details = RwSignal::new(String::from("经度 120.153820 · 纬度 30.287410\n相对高度 45.2 m · 航向 007.0°"));
|
||||
let status = RwSignal::new(String::from("已连接 · 实时数据通道"));
|
||||
let age = RwSignal::new(12u64);
|
||||
let count = RwSignal::new(3usize);
|
||||
let initial_mode = web_sys::window()
|
||||
.and_then(|w| w.location().hash().ok())
|
||||
.map(|h| h.trim_start_matches('#').to_lowercase())
|
||||
.filter(|h| h == "a" || h == "b" || h == "c")
|
||||
.unwrap_or_else(|| String::from("a"));
|
||||
let layout_mode = RwSignal::new(initial_mode);
|
||||
let hud_tab = RwSignal::new(String::from("targets"));
|
||||
let selected_lon = RwSignal::new(120.1538f64);
|
||||
let selected_lat = RwSignal::new(30.2874f64);
|
||||
let selected_alt = RwSignal::new(45.2f64);
|
||||
let selected_heading = RwSignal::new(7.0f64);
|
||||
let has_target_coords = RwSignal::new(true);
|
||||
|
||||
let choose = move |id: String| {
|
||||
if selected.get_untracked() != id {
|
||||
selected.set(id.clone());
|
||||
}
|
||||
if let Ok(v) = map_call("select", &args(&[id.clone().into()])) {
|
||||
let a = js_sys::Array::from(&v);
|
||||
if a.length() >= 4 {
|
||||
let lon = a.get(0).as_f64().unwrap_or(120.1538);
|
||||
let lat = a.get(1).as_f64().unwrap_or(30.2874);
|
||||
let alt = a.get(2).as_f64().unwrap_or(45.2);
|
||||
let hdg = a.get(3).as_f64().unwrap_or(7.0);
|
||||
selected_lon.set(lon);
|
||||
selected_lat.set(lat);
|
||||
selected_alt.set(alt);
|
||||
selected_heading.set(hdg);
|
||||
has_target_coords.set(true);
|
||||
details.set(format!(
|
||||
"经度 {:.6} · 纬度 {:.6}\n相对高度 {:.1} m · 航向 {:.1}°",
|
||||
lon, lat, alt, hdg
|
||||
));
|
||||
} else {
|
||||
selected_lon.set(120.1538);
|
||||
selected_lat.set(30.2874);
|
||||
selected_alt.set(45.2);
|
||||
selected_heading.set(7.0);
|
||||
has_target_coords.set(true);
|
||||
details.set(format!(
|
||||
"标的 {} · 实时态势已同步\n经度 120.153820 · 纬度 30.287410\n相对高度 45.2 m · 航向 007.0°",
|
||||
id
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let zoom_in = move |_| { let _ = map_call("zoomIn", &args(&[])); };
|
||||
let zoom_out = move |_| { let _ = map_call("zoomOut", &args(&[])); };
|
||||
let center_target = move |_| { let _ = map_call("centerSelected", &args(&[])); };
|
||||
let reset_north = move |_| { let _ = map_call("resetBearing", &args(&[])); };
|
||||
let toggle_3d = move |_| { let _ = map_call("toggle3d", &args(&[])); };
|
||||
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
let window = web_sys::window().unwrap();
|
||||
for _ in 0..100 {
|
||||
if map_call("create", &args(&["rt-map".into()])).is_ok() {
|
||||
break;
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(50).await;
|
||||
}
|
||||
let worker_ref: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
|
||||
let callback_holder = worker_ref.clone();
|
||||
let callback = Rc::new(Closure::<dyn FnMut(web_sys::MessageEvent)>::new(
|
||||
move |event: web_sys::MessageEvent| {
|
||||
let data = event.data();
|
||||
let get = |key: &str| {
|
||||
js_sys::Reflect::get(&data, &key.into()).unwrap_or(JsValue::UNDEFINED)
|
||||
};
|
||||
let new_status = get("status").as_string().unwrap_or_default();
|
||||
let _ = map_call(
|
||||
"connection",
|
||||
&args(&[JsValue::from_bool(new_status == "connected")]),
|
||||
);
|
||||
status.set(
|
||||
match new_status.as_str() {
|
||||
"connected" => "已连接 · 实时数据通道",
|
||||
"disconnected" => "连接断开 · 正在等待重连",
|
||||
"connecting" => "连接中",
|
||||
_ => "连接异常,请检查服务",
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
let positions = get("positions");
|
||||
let _ = map_call("workerMemory", &args(&[get("wasmMemoryBytes")]));
|
||||
let incoming_ids = get("ids");
|
||||
if !incoming_ids.is_undefined() {
|
||||
let list = js_sys::Array::from(&incoming_ids);
|
||||
if list.length() > 0 {
|
||||
count.set(list.length() as usize);
|
||||
ids.set(list.iter().filter_map(|id| id.as_string()).collect());
|
||||
}
|
||||
}
|
||||
if !positions.is_undefined() {
|
||||
let _ = map_call("update", &args(&[positions, incoming_ids]));
|
||||
age.set(get("serverAgeMs").as_f64().unwrap_or(0.0) as u64);
|
||||
if !selected.get_untracked().is_empty() {
|
||||
choose(selected.get_untracked());
|
||||
}
|
||||
let sequence = get("sequence");
|
||||
let ack_holder = callback_holder.clone();
|
||||
let ack = Closure::once_into_js(move || {
|
||||
if let Some(worker) = ack_holder.borrow().as_ref() {
|
||||
let msg = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&msg, &"type".into(), &"ack".into());
|
||||
let _ = js_sys::Reflect::set(&msg, &"sequence".into(), &sequence);
|
||||
let _ = worker.post_message(&msg);
|
||||
}
|
||||
});
|
||||
let _ = web_sys::window()
|
||||
.unwrap()
|
||||
.request_animation_frame(ack.unchecked_ref());
|
||||
}
|
||||
},
|
||||
));
|
||||
let handler = Closure::<dyn FnMut(web_sys::CustomEvent)>::new(
|
||||
move |event: web_sys::CustomEvent| {
|
||||
if let Some(id) = event.detail().as_string() {
|
||||
choose(id);
|
||||
}
|
||||
},
|
||||
);
|
||||
let _ = window
|
||||
.add_event_listener_with_callback("rid-select", handler.as_ref().unchecked_ref());
|
||||
handler.forget();
|
||||
loop {
|
||||
let options = web_sys::WorkerOptions::new();
|
||||
options.set_type(web_sys::WorkerType::Module);
|
||||
let worker = match web_sys::Worker::new_with_options("/workers/entry.js", &options)
|
||||
{
|
||||
Ok(w) => w,
|
||||
Err(_) => {
|
||||
status.set("Worker 启动失败".into());
|
||||
return;
|
||||
}
|
||||
};
|
||||
worker.set_onmessage(Some(callback.as_ref().as_ref().unchecked_ref()));
|
||||
*worker_ref.borrow_mut() = Some(worker);
|
||||
break;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
let mut last_mode = String::new();
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/realtime/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(value) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
input_mode.set(if value["mode"] == "synthetic-input-enabled" {
|
||||
"隔离仿真输入已开启;全部为模拟数据。".into()
|
||||
} else {
|
||||
"设备接收模式;请确认连接与解码状态。".into()
|
||||
});
|
||||
}
|
||||
loop {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/maps/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(value) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
let mode = value["mode"].as_str().unwrap_or("offline");
|
||||
let label = if value["keyConfigured"] == false {
|
||||
"离线卫星与战术网格(未配置天地图密钥)"
|
||||
} else if mode == "offline" {
|
||||
"在线卫星暂不可用,已自动切到离线资源"
|
||||
} else {
|
||||
"天地图卫星在线优先 / 本地缓存"
|
||||
};
|
||||
map_status.set(format!(
|
||||
"{} · 缺失瓦片累计 {}",
|
||||
label, value["missingTiles"]
|
||||
));
|
||||
if !last_mode.is_empty() && last_mode != mode {
|
||||
let _ = map_call("refresh", &args(&[]));
|
||||
}
|
||||
last_mode = mode.to_owned();
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(5000).await;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
view! {
|
||||
<main class="rt-page">
|
||||
<header class="mc-topbar">
|
||||
<div class="mc-brand">
|
||||
<div class="mc-brand-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="mc-brand-text">
|
||||
<strong class="mc-brand-title">"任务指挥"</strong>
|
||||
<span class="mc-brand-sub">"MISSION CONTROL"</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mc-nav-tabs" aria-label="工作台模式">
|
||||
<button class=move||if layout_mode.get()=="a"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("a".into())>
|
||||
"飞行监控"
|
||||
</button>
|
||||
<button class=move||if layout_mode.get()=="b"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("b".into())>
|
||||
"调度指挥"
|
||||
</button>
|
||||
<button class=move||if layout_mode.get()=="c"{"mc-nav-tab active"}else{"mc-nav-tab"} on:click=move |_|layout_mode.set("c".into())>
|
||||
"目标研判"
|
||||
</button>
|
||||
<a class="mc-nav-tab mc-nav-link" href="/">
|
||||
"设备登记"
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<div class="mc-top-status-capsule">
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-capsule-icon">"🛸"</span>
|
||||
<span>{move||format!("当前控制: {}", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-pulse-dot green"></span>
|
||||
<span>"已连接"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span>"🎮 手动模式"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span>"📶 GNSS 18"</span>
|
||||
</div>
|
||||
<div class="mc-capsule-divider"></div>
|
||||
<div class="mc-capsule-item">
|
||||
<span class="mc-battery-tag">"🔋 电量 86%"</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class=move||format!("mc-workspace mc-workspace-{}", layout_mode.get())>
|
||||
{move||match layout_mode.get().as_str() {
|
||||
"a" => view! {
|
||||
<div class="mc-layout-a">
|
||||
<!-- Left Floating Drawer: 机队概览 -->
|
||||
<aside class="mc-floating-panel mc-drawer-left">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||format!("机队概览 · {}架在线", matches.get().len())}</h3>
|
||||
<span class="mc-panel-header-icon">"⌃"</span>
|
||||
</div>
|
||||
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
|
||||
<div class="mc-search-box">
|
||||
<input class="mc-input" aria-label="搜索实时目标" placeholder="🔍 按目标编号筛选…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
</div>
|
||||
|
||||
<nav class="mc-pagination" aria-label="目标目录分页">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀ 上一组"</button>
|
||||
<span class="mc-page-text">{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(100).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*100 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"下一组 ▶"</button>
|
||||
</nav>
|
||||
|
||||
<div class="mc-target-list">
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{
|
||||
let label = id.clone();
|
||||
let picked1 = id.clone();
|
||||
let picked2 = id.clone();
|
||||
let picked3 = id.clone();
|
||||
let target_id2 = id.clone();
|
||||
view!{
|
||||
<div class=move||if selected.get() == picked1 {"mc-vehicle-card active"}else{"mc-vehicle-card"} on:click=move |_|choose(id.clone())>
|
||||
<div class="mc-vc-row1">
|
||||
<span class="mc-vc-icon">"🛸"</span>
|
||||
<strong class="mc-vc-name">{label}</strong>
|
||||
<span class=move||if selected.get() == picked2 {"mc-vc-badge active"}else{"mc-vc-badge"}>
|
||||
{move||if selected.get() == picked3 {"当前控制"}else{"就绪"}}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mc-vc-row2">
|
||||
<span class="mc-vc-bat">"🔋 86%"</span>
|
||||
<span class="mc-vc-status">"● 就绪"</span>
|
||||
<button class="mc-vc-btn-locate" title="在地图上居中" on:click=move|e|{
|
||||
e.stop_propagation();
|
||||
choose(target_id2.clone());
|
||||
let _ = map_call("centerSelected", &args(&[]));
|
||||
}>"🎯"</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}).collect_view()}
|
||||
</div>
|
||||
|
||||
<!-- Bottom Multi-vehicle operations -->
|
||||
<div class="mc-fleet-actions">
|
||||
<div class="mc-fleet-title">"多机协同 · 快速操作"</div>
|
||||
<div class="mc-fleet-grid">
|
||||
<button class="mc-fleet-btn">"🔒 解锁"</button>
|
||||
<button class="mc-fleet-btn">"🔓 上锁"</button>
|
||||
<button class="mc-fleet-btn primary">"▶ 开始任务"</button>
|
||||
<button class="mc-fleet-btn">"⏸ 暂停"</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center Map Area -->
|
||||
<section class="mc-map-area">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
|
||||
<!-- Floating Top Warning Banner -->
|
||||
<div class="mc-map-alert-banner">
|
||||
<span class="mc-alert-icon">"⚠️"</span>
|
||||
<span class="mc-alert-msg">{move||format!("{}: 目标信号正常保持中 · 遥控器在线", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</span>
|
||||
<a class="mc-alert-action" href="#c">"查看详情 ›"</a>
|
||||
</div>
|
||||
|
||||
<!-- Floating Map Toolstrip on left of map -->
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图切换" on:click=move|_|{let _=map_call("refresh", &args(&[]));}>
|
||||
<span class="mc-ts-icon">"🗺️"</span>
|
||||
<span class="mc-ts-label">"地图"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="态势图层">
|
||||
<span class="mc-ts-icon">"📑"</span>
|
||||
<span class="mc-ts-label">"图层"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="视口居中选中目标" on:click=center_target>
|
||||
<span class="mc-ts-icon">"📍"</span>
|
||||
<span class="mc-ts-label">"定位"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D 俯仰视角切换" on:click=toggle_3d>
|
||||
<span class="mc-ts-icon">"🌐"</span>
|
||||
<span class="mc-ts-label">"2D/3D"</span>
|
||||
</button>
|
||||
<button class="mc-toolstrip-btn" title="复位正北" on:click=reset_north>
|
||||
<span class="mc-ts-icon">"🧭"</span>
|
||||
<span class="mc-ts-label">"测量"</span>
|
||||
</button>
|
||||
<div class="mc-toolstrip-divider"></div>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
|
||||
<!-- Floating Bottom Telemetry Ribbon -->
|
||||
<div class="mc-telemetry-ribbon">
|
||||
<div class="mc-ribbon-item brand">
|
||||
<span class="mc-ribbon-drone">"🛸"</span>
|
||||
<strong>{move||if selected.get().is_empty(){"01号机".into()}else{selected.get()}}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"相对高度"</span>
|
||||
<strong class="mc-ribbon-val">{move||format!("{:.1} m", selected_alt.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"地速"</span>
|
||||
<strong class="mc-ribbon-val">"12.4 m/s"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"空速"</span>
|
||||
<strong class="mc-ribbon-val">"12.0 m/s"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"航向"</span>
|
||||
<strong class="mc-ribbon-val">{move||format!("{:03.0}°", selected_heading.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<div class="mc-ribbon-item">
|
||||
<span class="mc-ribbon-label">"飞行时间"</span>
|
||||
<strong class="mc-ribbon-val">"00:14:32"</strong>
|
||||
</div>
|
||||
<div class="mc-ribbon-divider"></div>
|
||||
<button class="mc-ribbon-btn" on:click=reset_north>"⚙️ 仪表设置"</button>
|
||||
</div>
|
||||
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<!-- Right Floating Panel: 单机工作台 -->
|
||||
<aside class="mc-floating-panel mc-hud-right">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||format!("单机工作台 · {}", if selected.get().is_empty(){"01号机".into()}else{selected.get()})}</h3>
|
||||
<span class="mc-panel-header-icon">"⌃"</span>
|
||||
</div>
|
||||
|
||||
<!-- Checklist items -->
|
||||
<div class="mc-checklist">
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"📋"</span>
|
||||
<span class="mc-check-name">"飞前检查"</span>
|
||||
<span class="mc-check-badge ok">"已通过 ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🎮"</span>
|
||||
<span class="mc-check-name">"遥控器"</span>
|
||||
<span class="mc-check-status ok">"● 等待连接 ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🛰️"</span>
|
||||
<span class="mc-check-name">"GNSS"</span>
|
||||
<span class="mc-check-status ok">"● 正常 (18) ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🔋"</span>
|
||||
<span class="mc-check-name">"电池电量"</span>
|
||||
<span class="mc-check-status ok">"● 86% ›"</span>
|
||||
</div>
|
||||
<div class="mc-check-row">
|
||||
<span class="mc-check-icon">"🛡️"</span>
|
||||
<span class="mc-check-name">"机身状态"</span>
|
||||
<span class="mc-check-status ok">"● 正常 ›"</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Flight operations buttons -->
|
||||
<div class="mc-flight-ops">
|
||||
<div class="mc-ops-title">"飞行操作"</div>
|
||||
<div class="mc-ops-grid">
|
||||
<button class="mc-ops-btn primary">"起飞"</button>
|
||||
<button class="mc-ops-btn">"暂停"</button>
|
||||
<button class="mc-ops-btn">"返航"</button>
|
||||
<button class="mc-ops-btn">"降落"</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dual Instruments: Attitude Indicator & Heading Compass -->
|
||||
<div class="mc-dual-instruments">
|
||||
<!-- Instrument 1: Artificial Horizon -->
|
||||
<div class="mc-inst-box">
|
||||
<svg class="mc-horizon-svg" viewBox="0 0 100 100">
|
||||
<defs>
|
||||
<clipPath id="horizon-clip">
|
||||
<circle cx="50" cy="50" r="44"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#horizon-clip)">
|
||||
<!-- Sky -->
|
||||
<rect x="0" y="0" width="100" height="50" fill="#0284c7"/>
|
||||
<!-- Earth -->
|
||||
<rect x="0" y="50" width="100" height="50" fill="#854d0e"/>
|
||||
<!-- Horizon Line -->
|
||||
<line x1="0" y1="50" x2="100" y2="50" stroke="#ffffff" stroke-width="1.5"/>
|
||||
<!-- Pitch Ladder -->
|
||||
<line x1="38" y1="36" x2="62" y2="36" stroke="#ffffff" stroke-width="1"/>
|
||||
<text x="32" y="38" fill="#ffffff" font-size="6">"10"</text>
|
||||
<text x="64" y="38" fill="#ffffff" font-size="6">"10"</text>
|
||||
<line x1="38" y1="64" x2="62" y2="64" stroke="#ffffff" stroke-width="1"/>
|
||||
<text x="30" y="66" fill="#ffffff" font-size="6">"-10"</text>
|
||||
<text x="64" y="66" fill="#ffffff" font-size="6">"-10"</text>
|
||||
</g>
|
||||
<!-- Aircraft Reticle Wings -->
|
||||
<line x1="26" y1="50" x2="42" y2="50" stroke="#facc15" stroke-width="2.5"/>
|
||||
<circle cx="50" cy="50" r="2.5" fill="#facc15"/>
|
||||
<line x1="58" y1="50" x2="74" y2="50" stroke="#facc15" stroke-width="2.5"/>
|
||||
<!-- Instrument Bezel Ring -->
|
||||
<circle cx="50" cy="50" r="46" stroke="rgba(255,255,255,0.2)" stroke-width="2" fill="none"/>
|
||||
</svg>
|
||||
<div class="mc-inst-label">"俯仰 0.0° · 横滚 0.0°"</div>
|
||||
</div>
|
||||
|
||||
<!-- Instrument 2: Heading Compass Dial -->
|
||||
<div class="mc-inst-box">
|
||||
<svg class="mc-compass-svg" viewBox="0 0 100 100">
|
||||
<circle cx="50" cy="50" r="46" stroke="rgba(48,100,180,0.4)" stroke-width="2" fill="rgba(6,12,24,0.85)"/>
|
||||
<circle cx="50" cy="50" r="38" stroke="rgba(255,255,255,0.1)" stroke-width="1" fill="none"/>
|
||||
<line x1="50" y1="8" x2="50" y2="15" stroke="#38bdf8" stroke-width="2"/>
|
||||
<line x1="50" y1="92" x2="50" y2="85" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<line x1="8" y1="50" x2="15" y2="50" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<line x1="92" y1="50" x2="85" y2="50" stroke="rgba(255,255,255,0.3)" stroke-width="1"/>
|
||||
<text x="50" y="24" fill="#38bdf8" font-size="8" font-weight="bold" text-anchor="middle">"N"</text>
|
||||
<text x="82" y="53" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"E"</text>
|
||||
<text x="50" y="80" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"S"</text>
|
||||
<text x="18" y="53" fill="rgba(255,255,255,0.6)" font-size="7" text-anchor="middle">"W"</text>
|
||||
<g transform=move||format!("rotate({}, 50, 50)", selected_heading.get())>
|
||||
<polygon points="50,16 46,50 54,50" fill="#ef4444"/>
|
||||
<polygon points="50,84 46,50 54,50" fill="rgba(255,255,255,0.25)"/>
|
||||
<circle cx="50" cy="50" r="4" fill="#0b172a" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
</g>
|
||||
</svg>
|
||||
<div class="mc-inst-label">{move||format!("航向 {:03.0}°", selected_heading.get())}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Target Coordinates Box -->
|
||||
<div class="mc-hud-grid">
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"相对高度"</span>
|
||||
<strong class="mc-metric-val">{move||format!("{:.1}m", selected_alt.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"航向角"</span>
|
||||
<strong class="mc-metric-val">{move||format!("{:.1}°", selected_heading.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"经度"</span>
|
||||
<strong class="mc-metric-val sm">{move||format!("{:.5}", selected_lon.get())}</strong>
|
||||
</div>
|
||||
<div class="mc-metric-box">
|
||||
<span class="mc-metric-label">"纬度"</span>
|
||||
<strong class="mc-metric-val sm">{move||format!("{:.5}", selected_lat.get())}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-details-card">
|
||||
<p class="mc-details-text">{move||details.get()}</p>
|
||||
<div class="mc-age-tag">
|
||||
<span>"数据年龄:"</span>
|
||||
<strong>{move||format!("{} ms", age.get())}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-quick-actions">
|
||||
<button class="mc-btn mc-btn-primary" on:click=center_target>"🎯 视口居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary" href=move||format!("/?q={}", selected.get())>"📋 备案查询"</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
"b" => view! {
|
||||
<div class="mc-layout-b">
|
||||
<section class="mc-map-area-top">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图" on:click=move|_|{let _=map_call("refresh", &args(&[]));}><span class="mc-ts-icon">"🗺️"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="视口居中" on:click=center_target><span class="mc-ts-icon">"🎯"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D" on:click=toggle_3d><span class="mc-ts-icon">"🌐"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="正北复位" on:click=reset_north><span class="mc-ts-icon">"🧭"</span></button>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<section class="mc-hud-dock">
|
||||
<div class="mc-dock-header">
|
||||
<div class="mc-dock-tabs">
|
||||
<button class=move||if hud_tab.get()=="targets"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("targets".into())>
|
||||
{move||format!("无人机态势列表 ({})", matches.get().len())}
|
||||
</button>
|
||||
<button class=move||if hud_tab.get()=="receiver"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("receiver".into())>
|
||||
"接收机与解码"
|
||||
</button>
|
||||
<button class=move||if hud_tab.get()=="events"{"mc-dock-tab active"}else{"mc-dock-tab"} on:click=move|_|hud_tab.set("events".into())>
|
||||
"事件与日志"
|
||||
</button>
|
||||
</div>
|
||||
<div class="mc-dock-substatus">
|
||||
<span>{move||input_mode.get()}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-dock-body">
|
||||
{move||match hud_tab.get().as_str() {
|
||||
"receiver" => view! {
|
||||
<div class="mc-dock-scroll">
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
"events" => view! {
|
||||
<div class="mc-events-stream">
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"实时通道"</span>
|
||||
<span class="mc-event-badge ok">"CONNECTED"</span>
|
||||
<span class="mc-event-desc">{move||status.get()}</span>
|
||||
</div>
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"底图引擎"</span>
|
||||
<span class="mc-event-badge info">"SATELLITE"</span>
|
||||
<span class="mc-event-desc">{move||map_status.get()}</span>
|
||||
</div>
|
||||
<div class="mc-event-item">
|
||||
<span class="mc-event-time">"遥测刷新"</span>
|
||||
<span class="mc-event-badge info">"TELEMETRY"</span>
|
||||
<span class="mc-event-desc">{move||format!("当前在线目标 {} 架,数据延迟 {} ms", matches.get().len(), age.get())}</span>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
_ => view! {
|
||||
<div class="mc-dock-split">
|
||||
<div class="mc-dock-table-wrap">
|
||||
<div class="mc-table-controls">
|
||||
<input class="mc-input mc-table-search" placeholder="🔍 快速查找目标 SN / 编号…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
<div class="mc-table-pages">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀"</button>
|
||||
<span>{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(20).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*20 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"▶"</button>
|
||||
</div>
|
||||
</div>
|
||||
<table class="mc-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>"#"</th>
|
||||
<th>"目标编号 (RID)"</th>
|
||||
<th>"状态"</th>
|
||||
<th>"遥测数据"</th>
|
||||
<th>"操作"</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*20).take(20).enumerate().map(|(idx, id)|{
|
||||
let label = id.clone();
|
||||
let is_active = selected.get() == id;
|
||||
let tid = id.clone();
|
||||
view!{
|
||||
<tr class=if is_active{"mc-tr active"}else{"mc-tr"} on:click=move|_|choose(tid.clone())>
|
||||
<td>{visible_page.get()*20 + idx + 1}</td>
|
||||
<td><strong class="mc-id-code">{label}</strong></td>
|
||||
<td><span class="mc-pill-ok">"● 在线"</span></td>
|
||||
<td>
|
||||
{if is_active && has_target_coords.get(){
|
||||
format!("{:.1}m · {:.1}°", selected_alt.get(), selected_heading.get())
|
||||
} else {
|
||||
"实时解码".to_string()
|
||||
}}
|
||||
</td>
|
||||
<td>
|
||||
<button class="mc-action-btn" on:click=move|e|{
|
||||
e.stop_propagation();
|
||||
choose(id.clone());
|
||||
let _ = map_call("centerSelected", &args(&[]));
|
||||
}>"聚焦"</button>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}).collect_view()}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mc-dock-instrument-pane">
|
||||
<div class="mc-quad-header">
|
||||
<span class="mc-quad-name">{move||if selected.get().is_empty(){"01号机 (DEMO)".to_owned()}else{selected.get()}}</span>
|
||||
<span class="mc-quad-state">"● 实时报文"</span>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-layout">
|
||||
<div class="mc-quad-schematic">
|
||||
<svg viewBox="0 0 80 80" class="mc-quad-svg">
|
||||
<line x1="22" y1="22" x2="58" y2="58" stroke="#38bdf8" stroke-width="3"/>
|
||||
<line x1="22" y1="58" x2="58" y2="22" stroke="#38bdf8" stroke-width="3"/>
|
||||
<circle cx="40" cy="40" r="12" fill="#0b172a" stroke="#38bdf8" stroke-width="2"/>
|
||||
<circle cx="22" cy="22" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="58" cy="22" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="22" cy="58" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<circle cx="58" cy="58" r="9" fill="none" stroke="rgba(56,189,248,0.7)" stroke-width="2"/>
|
||||
<polygon points="40,32 36,44 44,44" fill="#38bdf8" transform=move||format!("rotate({}, 40, 40)", selected_heading.get())/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-metrics">
|
||||
<div class="mc-quad-metric-row"><span>"椭球高"</span><strong>{move||if has_target_coords.get(){format!("{:.1} m", selected_alt.get())}else{"--".into()}}</strong></div>
|
||||
<div class="mc-quad-metric-row"><span>"航向"</span><strong>{move||if has_target_coords.get(){format!("{:.1}°", selected_heading.get())}else{"--".into()}}</strong></div>
|
||||
<div class="mc-quad-metric-row"><span>"采样年龄"</span><strong>{move||format!("{} ms", age.get())}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mc-quad-actions">
|
||||
<button class="mc-btn mc-btn-primary mc-btn-sm" on:click=center_target>"🎯 居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary mc-btn-sm" href=move||format!("/?q={}", selected.get())>"📋 档案"</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
}.into_any(),
|
||||
|
||||
_ => view! {
|
||||
<div class="mc-layout-c">
|
||||
<aside class="mc-column-left">
|
||||
<div class="mc-panel-header">
|
||||
<h3>"目标目录与研判"</h3>
|
||||
<span class="mc-tag">{move||format!("{} 目标", matches.get().len())}</span>
|
||||
</div>
|
||||
<crate::receiver_ui::ReceiverControls/>
|
||||
<div class="mc-search-box">
|
||||
<input class="mc-input" aria-label="搜索实时目标" placeholder="🔍 检索 RID / SN…" on:input=move|e|{directory_page.set(0);query.set(event_target_value(&e));}/>
|
||||
</div>
|
||||
<nav class="mc-pagination" aria-label="目标目录分页">
|
||||
<button class="mc-btn-sm" disabled=move||visible_page.get()==0 on:click=move |_|directory_page.set(visible_page.get().saturating_sub(1))>"◀ 上一组"</button>
|
||||
<span class="mc-page-text">{move||format!("{} / {}", visible_page.get()+1, matches.get().len().div_ceil(100).max(1))}</span>
|
||||
<button class="mc-btn-sm" disabled=move||{ (visible_page.get()+1)*100 >= matches.get().len() } on:click=move |_|directory_page.set(visible_page.get()+1)>"下一组 ▶"</button>
|
||||
</nav>
|
||||
<div class="mc-target-list">
|
||||
{move||matches.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{
|
||||
let label = id.clone();
|
||||
let picked = id.clone();
|
||||
view!{
|
||||
<button class="mc-target-item" aria-pressed=move||(selected.get()==picked).to_string() on:click=move |_|choose(id.clone())>
|
||||
<span class="mc-target-dot"></span>
|
||||
<span class="mc-target-name">{label}</span>
|
||||
</button>
|
||||
}
|
||||
}).collect_view()}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="mc-map-area-c">
|
||||
<div id="rt-map" class="rt-map-canvas"></div>
|
||||
<div class="mc-map-toolstrip">
|
||||
<button class="mc-toolstrip-btn active" title="底图" on:click=move|_|{let _=map_call("refresh", &args(&[]));}><span class="mc-ts-icon">"🗺️"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="聚焦选定目标" on:click=center_target><span class="mc-ts-icon">"🎯"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="2D/3D" on:click=toggle_3d><span class="mc-ts-icon">"🌐"</span></button>
|
||||
<button class="mc-toolstrip-btn" title="复位正北" on:click=reset_north><span class="mc-ts-icon">"🧭"</span></button>
|
||||
<button class="mc-toolstrip-btn zoom" title="放大" on:click=zoom_in>"+"</button>
|
||||
<button class="mc-toolstrip-btn zoom" title="缩小" on:click=zoom_out>"-"</button>
|
||||
</div>
|
||||
<div class="mc-map-infobar">{move || map_status.get()}</div>
|
||||
</section>
|
||||
|
||||
<section class="mc-dossier-panel">
|
||||
<div class="mc-panel-header">
|
||||
<h3>{move||if selected.get().is_empty(){"目标研判档案卡".to_owned()}else{format!("研判标的:{}", selected.get())}}</h3>
|
||||
<div class="mc-header-actions">
|
||||
<button class="mc-btn mc-btn-primary mc-btn-sm" on:click=center_target>"🎯 视口居中"</button>
|
||||
<a class="mc-btn mc-btn-secondary mc-btn-sm" href=move||format!("/?q={}", selected.get())>"📋 核对登记"</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mc-dossier-grid">
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"空间几何坐标"</span>
|
||||
<p class="mc-dossier-val">{move||details.get()}</p>
|
||||
</div>
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"报文时效与链路"</span>
|
||||
<p class="mc-dossier-val">{move||format!("数据延迟:{} ms\n输入模式:{}\n服务状态:{}", age.get(), input_mode.get(), status.get())}</p>
|
||||
</div>
|
||||
<div class="mc-dossier-card">
|
||||
<span class="mc-dossier-label">"研判核验结论"</span>
|
||||
<p class="mc-dossier-val">{move||if selected.get().is_empty(){"请从左侧选择目标进行比对".to_owned()}else{"已捕获 RID 广播帧,可一键跳转本地数据库核验 SN 匹配记录。".to_owned()}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
use leptos::prelude::*;
|
||||
use serde_json::json;
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
|
||||
#[component]
|
||||
pub fn ReceiverControls() -> impl IntoView {
|
||||
let enabled = RwSignal::new(false);
|
||||
let transport = RwSignal::new("serial".to_owned());
|
||||
let format = RwSignal::new("raw".to_owned());
|
||||
let serial_port = RwSignal::new(String::new());
|
||||
let baud = RwSignal::new("115200".to_owned());
|
||||
let ip = RwSignal::new("127.0.0.1".to_owned());
|
||||
let port = RwSignal::new("8788".to_owned());
|
||||
let message = RwSignal::new(String::new());
|
||||
let status = RwSignal::new("接收未启用".to_owned());
|
||||
let capture = RwSignal::new(String::new());
|
||||
let ports = RwSignal::new(Vec::<String>::new());
|
||||
let busy = RwSignal::new(false);
|
||||
Effect::new(move |_| {
|
||||
spawn_local(async move {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/config")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
enabled.set(v["enabled"].as_bool().unwrap_or(false));
|
||||
transport.set(v["transport"].as_str().unwrap_or("serial").into());
|
||||
format.set(v["format"].as_str().unwrap_or("raw").into());
|
||||
serial_port.set(v["serialPort"].as_str().unwrap_or("").into());
|
||||
baud.set(v["baudRate"].to_string());
|
||||
ip.set(v["bindIp"].as_str().unwrap_or("127.0.0.1").into());
|
||||
port.set(v["port"].to_string());
|
||||
}
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/ports")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
ports.set(
|
||||
v["ports"]
|
||||
.as_array()
|
||||
.map(|p| {
|
||||
p.iter()
|
||||
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
loop {
|
||||
if let Ok(response) = gloo_net::http::Request::get("/api/receiver/status")
|
||||
.send()
|
||||
.await
|
||||
&& let Ok(v) = response.json::<serde_json::Value>().await
|
||||
{
|
||||
let state = match v["state"].as_str().unwrap_or("stopped") {
|
||||
"serial-open" => "串口已打开",
|
||||
"udp-listening" => "UDP 监听中",
|
||||
"tcp-listening" => "TCP 监听中",
|
||||
"connecting" => "正在连接",
|
||||
"disconnected" => "连接失败或断开,自动重试中",
|
||||
_ => "接收未启用",
|
||||
};
|
||||
status.set(format!(
|
||||
"{} {}\n接收 {} 字节 · 解码 {} 帧 · 接受 {} 条 · 拒绝 {} 帧\n{}",
|
||||
state,
|
||||
v["endpoint"].as_str().unwrap_or(""),
|
||||
v["receivedBytes"],
|
||||
v["decodedFrames"],
|
||||
v["acceptedObservations"],
|
||||
v["rejectedFrames"],
|
||||
v["lastError"].as_str().unwrap_or("")
|
||||
));
|
||||
capture.set(v["captureHex"].as_str().unwrap_or("").into());
|
||||
}
|
||||
gloo_timers::future::TimeoutFuture::new(1000).await;
|
||||
}
|
||||
});
|
||||
});
|
||||
let save = move |_| {
|
||||
if busy.get_untracked() {
|
||||
return;
|
||||
}
|
||||
busy.set(true);
|
||||
let value = json!({"enabled":enabled.get_untracked(),"transport":transport.get_untracked(),"format":format.get_untracked(),"serialPort":serial_port.get_untracked(),"baudRate":baud.get_untracked().parse::<u32>().unwrap_or(0),"bindIp":ip.get_untracked(),"port":port.get_untracked().parse::<u16>().unwrap_or(0)});
|
||||
spawn_local(async move {
|
||||
let request = gloo_net::http::Request::post("/api/receiver/config").json(&value);
|
||||
match request {
|
||||
Ok(request) => match request.send().await {
|
||||
Ok(response) => {
|
||||
let ok = response.ok();
|
||||
let v = response
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
message.set(if ok {
|
||||
"配置已保存,实际状态见下方。".into()
|
||||
} else {
|
||||
v["error"].as_str().unwrap_or("配置保存失败").into()
|
||||
});
|
||||
}
|
||||
Err(_) => message.set("请求失败,请核对服务状态。".into()),
|
||||
},
|
||||
Err(_) => message.set("配置格式无效。".into()),
|
||||
}
|
||||
busy.set(false);
|
||||
});
|
||||
};
|
||||
view! {
|
||||
<details class="rt-receiver">
|
||||
<summary class="rt-receiver-summary">
|
||||
<span class="rt-summary-title">"📡 接收机设置 · 接口与解码"</span>
|
||||
<span class="rt-summary-tag">{move||if enabled.get(){"● 接收中"}else{"○ 未启用"}}</span>
|
||||
</summary>
|
||||
<div class="rt-receiver-body">
|
||||
<label class="rt-switch-label">
|
||||
<input type="checkbox" prop:checked=move||enabled.get() on:change=move|e|enabled.set(event_target_checked(&e))/>
|
||||
<span class="rt-switch-text">"启用数据接收(打开选定串口或监听端口)"</span>
|
||||
</label>
|
||||
<div class="rt-form-group">
|
||||
<label class="rt-label">"连接方式"
|
||||
<select class="rt-select" aria-label="连接方式" prop:value=move||transport.get() on:change=move|e|transport.set(event_target_value(&e))>
|
||||
<option value="serial">"🔌 USB 串口"</option>
|
||||
<option value="udp">"🌐 UDP 接收监听"</option>
|
||||
<option value="tcp-listen">"⚡ TCP 接收监听"</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{move||if transport.get()=="serial"{
|
||||
view!{
|
||||
<div class="rt-form-row">
|
||||
<label class="rt-label">"串口号"
|
||||
<input class="rt-input" aria-label="串口" list="receiver-ports" placeholder="例如 COM3" prop:value=move||serial_port.get() on:input=move|e|serial_port.set(event_target_value(&e))/>
|
||||
</label>
|
||||
<datalist id="receiver-ports">{move||ports.get().into_iter().map(|name|view!{<option value=name/>}).collect_view()}</datalist>
|
||||
<label class="rt-label">"波特率"
|
||||
<input class="rt-input" aria-label="波特率" prop:value=move||baud.get() on:input=move|e|baud.set(event_target_value(&e))/>
|
||||
</label>
|
||||
</div>
|
||||
}.into_any()
|
||||
}else{
|
||||
view!{
|
||||
<div class="rt-form-row">
|
||||
<label class="rt-label">"监听 IP"
|
||||
<input class="rt-input" aria-label="电脑监听 IP" prop:value=move||ip.get() on:input=move|e|ip.set(event_target_value(&e))/>
|
||||
</label>
|
||||
<label class="rt-label">"接收端口"
|
||||
<input class="rt-input" aria-label="接收端口" prop:value=move||port.get() on:input=move|e|port.set(event_target_value(&e))/>
|
||||
</label>
|
||||
</div>
|
||||
}.into_any()
|
||||
}}
|
||||
<div class="rt-form-group">
|
||||
<label class="rt-label">"报文解码格式"
|
||||
<select class="rt-select" aria-label="报文解码" prop:value=move||format.get() on:change=move|e|format.set(event_target_value(&e))>
|
||||
<option value="raw">"🔍 原始数据诊断(厂商格式待确认)"</option>
|
||||
<option value="json-lines">"📄 约定 JSON / JSON Lines"</option>
|
||||
<option value="postcard">"📦 约定 Postcard 二进制"</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="rt-btn-row">
|
||||
<button class="rt-btn rt-btn-primary rt-config-save" disabled=move||busy.get() on:click=save>"💾 保存接收配置"</button>
|
||||
<button class="rt-btn rt-btn-secondary rt-config-save" on:click=move |_|spawn_local(async move {
|
||||
if let Ok(response)=gloo_net::http::Request::get("/api/receiver/capture").send().await
|
||||
&& let Ok(text)=response.text().await {
|
||||
let copied=wasm_bindgen_futures::JsFuture::from(web_sys::window().unwrap().navigator().clipboard().write_text(&text)).await;
|
||||
message.set(if copied.is_ok(){"已复制最近 4 KiB 诊断数据。".into()}else{"复制失败,请手动保存。".into()});
|
||||
}
|
||||
})>"📋 复制诊断数据"</button>
|
||||
</div>
|
||||
<p class="rt-msg-pill" role="status">{move||message.get()}</p>
|
||||
<div class="rt-receiver-stat-box">
|
||||
<p class="rt-muted rt-receiver-status">{move||status.get()}</p>
|
||||
</div>
|
||||
<div class="rt-capture-box">
|
||||
<div class="rt-capture-head">"最新诊断报文 (HEX)"</div>
|
||||
<code class="rt-capture">{move||capture.get()}</code>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
<!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="light">
|
||||
<title>FPV-RID · 本地登记与核验</title>
|
||||
<link rel="icon" type="image/png" href="/fpv-rid-icon.png">
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
<script defer src="/vendor/qrcode.js"></script>
|
||||
<script defer src="/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="topbar">
|
||||
<img class="brand-mark" src="/fpv-rid-icon.png" alt="FPV-RID 图标">
|
||||
<div class="brand-copy"><strong>FPV-RID</strong><small>本地登记工作台</small></div>
|
||||
<div class="top-status"><i></i> 仅在本机运行</div>
|
||||
<div class="brand-copy">
|
||||
<strong>任务指挥 MISSION CONTROL</strong>
|
||||
<small>FPV-RID · 本地备案与核验中心</small>
|
||||
</div>
|
||||
<nav class="mc-nav-tabs" style="margin-left: 20px;">
|
||||
<span class="mc-nav-pill active"><span class="mc-pill-icon">📋</span> 设备备案登记</span>
|
||||
<a class="mc-nav-pill mc-nav-link" href="/realtime"><span class="mc-pill-icon">🗺️</span> 实时态势工作台</a>
|
||||
</nav>
|
||||
<div class="top-status"><i></i> 本机沙盒运行</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
@@ -97,6 +91,4 @@
|
||||
</div>
|
||||
<p id="edit-message" role="status"></p><div class="result-actions"><button id="edit-save" class="secondary" type="submit">保存修改</button><button id="edit-cancel" class="ghost" type="button">取消</button></div>
|
||||
</form>
|
||||
</dialog>
|
||||
</body>
|
||||
</html>
|
||||
</dialog>
|
||||
@@ -0,0 +1,765 @@
|
||||
//! Registration interactions compiled from Rust; no JavaScript business fallback.
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use gloo_net::http::Request;
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use qrcodegen::{QrCode, QrCodeEcc};
|
||||
use serde_json::{Value, json};
|
||||
use std::{cell::RefCell, collections::HashSet, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
||||
use web_sys::{
|
||||
Element, Event, HtmlAnchorElement, HtmlButtonElement, HtmlCanvasElement, HtmlDialogElement,
|
||||
HtmlInputElement,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
rows: Vec<Value>,
|
||||
selected: HashSet<String>,
|
||||
active: Option<Value>,
|
||||
editing: Option<Value>,
|
||||
page: u64,
|
||||
pages: u64,
|
||||
generation: u64,
|
||||
busy: bool,
|
||||
}
|
||||
type Shared = Rc<RefCell<State>>;
|
||||
type Result<T> = std::result::Result<T, String>;
|
||||
fn window() -> web_sys::Window {
|
||||
web_sys::window().unwrap()
|
||||
}
|
||||
fn document() -> web_sys::Document {
|
||||
window().document().unwrap()
|
||||
}
|
||||
fn el(id: &str) -> Element {
|
||||
document()
|
||||
.get_element_by_id(id)
|
||||
.expect("static registry element")
|
||||
}
|
||||
fn input(id: &str) -> HtmlInputElement {
|
||||
el(id).unchecked_into()
|
||||
}
|
||||
fn text(id: &str, value: &str) {
|
||||
el(id).set_text_content(Some(value));
|
||||
}
|
||||
fn value(id: &str) -> String {
|
||||
input(id).value().trim().to_owned()
|
||||
}
|
||||
fn field<'a>(v: &'a Value, name: &str) -> &'a str {
|
||||
v[name].as_str().unwrap_or("")
|
||||
}
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
fn hidden(id: &str, hide: bool) {
|
||||
if hide {
|
||||
let _ = el(id).set_attribute("hidden", "");
|
||||
} else {
|
||||
let _ = el(id).remove_attribute("hidden");
|
||||
}
|
||||
}
|
||||
fn disabled(id: &str, disable: bool) {
|
||||
if disable {
|
||||
let _ = el(id).set_attribute("disabled", "");
|
||||
} else {
|
||||
let _ = el(id).remove_attribute("disabled");
|
||||
}
|
||||
}
|
||||
fn dialog() -> HtmlDialogElement {
|
||||
el("edit-dialog").unchecked_into()
|
||||
}
|
||||
fn message(id: &str, msg: &str, error: bool) {
|
||||
text(id, msg);
|
||||
let _ = el(id).set_attribute(
|
||||
"class",
|
||||
if error {
|
||||
"form-message error"
|
||||
} else {
|
||||
"form-message"
|
||||
},
|
||||
);
|
||||
}
|
||||
fn err(e: JsValue) -> String {
|
||||
e.as_string()
|
||||
.unwrap_or_else(|| "浏览器操作失败,请刷新核对保存结果".into())
|
||||
}
|
||||
|
||||
async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
|
||||
let req = match method {
|
||||
"POST" => Request::post(url),
|
||||
"PATCH" => Request::patch(url),
|
||||
"DELETE" => Request::delete(url),
|
||||
_ => Request::get(url),
|
||||
};
|
||||
let response = if let Some(body) = body {
|
||||
req.json(&body).map_err(|e| e.to_string())?.send().await
|
||||
} else {
|
||||
req.send().await
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
let status = response.ok();
|
||||
let payload: Value = response.json().await.map_err(|e| e.to_string())?;
|
||||
if status {
|
||||
Ok(payload)
|
||||
} else {
|
||||
Err(payload["error"].as_str().unwrap_or("请求失败").to_owned())
|
||||
}
|
||||
}
|
||||
fn archive_status(payload: &Value) {
|
||||
if payload["archiveStatus"] == "pending" {
|
||||
hidden("archive-warning", false);
|
||||
text(
|
||||
"archive-warning-text",
|
||||
payload["warning"]
|
||||
.as_str()
|
||||
.unwrap_or("数据已保存,档案备份待同步。"),
|
||||
);
|
||||
} else if payload["archiveStatus"] == "synced" {
|
||||
hidden("archive-warning", true);
|
||||
}
|
||||
}
|
||||
fn selection(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
let n = s.selected.len();
|
||||
text("selected-count", &format!("({n})"));
|
||||
input("select-all").set_checked(!s.rows.is_empty() && n == s.rows.len());
|
||||
input("select-all").set_indeterminate(n > 0 && n < s.rows.len());
|
||||
disabled("export-archive", n == 0);
|
||||
disabled("export-excel", n == 0);
|
||||
}
|
||||
fn page_buttons(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
disabled("previous-page", s.page <= 1);
|
||||
disabled("next-page", s.page >= s.pages);
|
||||
}
|
||||
fn clear_selection(state: &Shared) {
|
||||
state.borrow_mut().selected.clear();
|
||||
render_rows(state);
|
||||
}
|
||||
fn render_rows(state: &Shared) {
|
||||
let s = state.borrow();
|
||||
let mut html = String::new();
|
||||
for row in &s.rows {
|
||||
let id = escape(field(row, "id"));
|
||||
let sn = escape(field(row, "serialNo"));
|
||||
let selected = s.selected.contains(field(row, "id"));
|
||||
html.push_str(&format!("<article class=\"archive-card{}\" data-id=\"{id}\"><label class=\"archive-select\"><input type=\"checkbox\" data-action=\"select\" aria-label=\"选择档案 {sn}\" {}>导出</label><h3>{sn}</h3><strong>{}</strong><p>{} · {} · {}</p><div class=\"archive-thumbs\">",if selected {" selected"} else {""},if selected {"checked"} else {""},escape(field(row,"uasCode")),escape(field(row,"modelName")),escape(field(row,"ownerName")),escape(field(row,"createdAt"))));
|
||||
for slot in [1, 2] {
|
||||
let url = field(row, &format!("photo{slot}Url"));
|
||||
if url.is_empty() {
|
||||
html.push_str(&format!("<div>照片 {slot} 未上传</div>"));
|
||||
} else {
|
||||
html.push_str(&format!(
|
||||
"<div><img loading=\"lazy\" alt=\"登记照片 {slot}\" src=\"{}\"></div>",
|
||||
escape(url)
|
||||
));
|
||||
}
|
||||
}
|
||||
html.push_str(&format!("</div><div class=\"archive-actions\"><button type=\"button\" data-action=\"edit\">编辑资料 / 照片</button><a href=\"{}\" target=\"_blank\" rel=\"noopener\">打开档案卡</a><a href=\"{}\">下载离线档案卡</a><button type=\"button\" data-action=\"qr\">查看二维码</button><button type=\"button\" class=\"delete-record\" data-action=\"delete\">删除档案</button></div></article>",escape(field(row,"archiveUrl")),escape(field(row,"downloadArchiveUrl"))));
|
||||
}
|
||||
el("history-cards").set_inner_html(&html);
|
||||
hidden("history-empty", !s.rows.is_empty());
|
||||
drop(s);
|
||||
selection(state);
|
||||
}
|
||||
async fn load(state: Shared, mut page: u64) -> Result<()> {
|
||||
let generation = {
|
||||
let mut s = state.borrow_mut();
|
||||
s.generation += 1;
|
||||
s.generation
|
||||
};
|
||||
let query = value("history-query");
|
||||
disabled("previous-page", true);
|
||||
disabled("next-page", true);
|
||||
loop {
|
||||
let url = format!(
|
||||
"/api/records?q={}&page={page}&pageSize=20",
|
||||
js_sys::encode_uri_component(&query)
|
||||
);
|
||||
let response = api(&url, "GET", None).await;
|
||||
if state.borrow().generation != generation {
|
||||
return Ok(());
|
||||
}
|
||||
let payload = match response {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
page_buttons(&state);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let pages = payload["totalPages"].as_u64().unwrap_or(0);
|
||||
if page > pages.max(1) {
|
||||
page = pages.max(1);
|
||||
continue;
|
||||
}
|
||||
{
|
||||
let mut s = state.borrow_mut();
|
||||
s.page = page;
|
||||
s.pages = pages;
|
||||
s.rows = payload["records"].as_array().cloned().unwrap_or_default();
|
||||
let ids: HashSet<String> = s.rows.iter().map(|r| field(r, "id").to_owned()).collect();
|
||||
s.selected.retain(|id| ids.contains(id));
|
||||
}
|
||||
text(
|
||||
"page-status",
|
||||
&format!(
|
||||
"第 {page} / {} 页 · 共 {} 条",
|
||||
pages.max(1),
|
||||
payload["total"]
|
||||
),
|
||||
);
|
||||
text(
|
||||
"search-count",
|
||||
&if query.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{} 条", payload["total"])
|
||||
},
|
||||
);
|
||||
text(
|
||||
"history-empty",
|
||||
if query.is_empty() {
|
||||
"暂无登记记录。"
|
||||
} else {
|
||||
"没有找到匹配的档案。"
|
||||
},
|
||||
);
|
||||
render_rows(&state);
|
||||
page_buttons(&state);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
async fn photo(id: &str) -> Result<Option<String>> {
|
||||
let Some(file) = input(id).files().and_then(|files| files.get(0)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !matches!(
|
||||
file.type_().as_str(),
|
||||
"image/jpeg" | "image/png" | "image/webp"
|
||||
) || file.size() > 5.0 * 1024.0 * 1024.0
|
||||
{
|
||||
return Err("照片仅支持 5 MB 以内的 JPG、PNG 或 WebP".into());
|
||||
}
|
||||
let data = JsFuture::from(file.array_buffer()).await.map_err(err)?;
|
||||
Ok(Some(format!(
|
||||
"data:{};base64,{}",
|
||||
file.type_(),
|
||||
STANDARD.encode(js_sys::Uint8Array::new(&data).to_vec())
|
||||
)))
|
||||
}
|
||||
fn draw(state: &Shared, record: Value) {
|
||||
hidden("empty-result", true);
|
||||
hidden("record-result", false);
|
||||
for (id, key) in [
|
||||
("display-uas", "uasCode"),
|
||||
("display-sn", "serialNo"),
|
||||
("display-model", "modelName"),
|
||||
("display-owner", "ownerName"),
|
||||
("display-url", "qrUrl"),
|
||||
] {
|
||||
text(id, field(&record, key));
|
||||
}
|
||||
for (id, key) in [
|
||||
("open-card", "archiveUrl"),
|
||||
("download-card", "downloadArchiveUrl"),
|
||||
] {
|
||||
let _ = el(id).set_attribute("href", field(&record, key));
|
||||
}
|
||||
let mut has_photos = false;
|
||||
for slot in [1, 2] {
|
||||
let url = field(&record, &format!("photo{slot}Url"));
|
||||
has_photos |= !url.is_empty();
|
||||
hidden(&format!("photo-{slot}-link"), url.is_empty());
|
||||
let _ = el(&format!("photo-{slot}-link")).set_attribute("href", url);
|
||||
let _ = el(&format!("photo-{slot}-preview"))
|
||||
.set_attribute("src", &format!("{url}?v={}", js_sys::Date::now()));
|
||||
}
|
||||
hidden("saved-photos", !has_photos);
|
||||
if let Ok(qr) = QrCode::encode_text(field(&record, "qrUrl"), QrCodeEcc::Medium) {
|
||||
let size = qr.size();
|
||||
let extent = size + 8;
|
||||
let mut svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><g fill=\"black\">"
|
||||
);
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
if qr.get_module(x, y) {
|
||||
svg.push_str(&format!(
|
||||
"<rect x=\"{}\" y=\"{}\" width=\"1\" height=\"1\"/>",
|
||||
x + 4,
|
||||
y + 4
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
svg.push_str("</g></svg>");
|
||||
el("qr-stage").set_inner_html(&svg);
|
||||
}
|
||||
state.borrow_mut().active = Some(record);
|
||||
}
|
||||
fn edit(state: &Shared, row: Value) {
|
||||
text("edit-message", "");
|
||||
text(
|
||||
"edit-identity",
|
||||
&format!("{} · {}", field(&row, "serialNo"), field(&row, "uasCode")),
|
||||
);
|
||||
input("edit-model").set_value(field(&row, "modelName"));
|
||||
input("edit-owner").set_value(field(&row, "ownerName"));
|
||||
for slot in [1, 2] {
|
||||
let url = field(&row, &format!("photo{slot}Url"));
|
||||
hidden(&format!("edit-preview-{slot}"), url.is_empty());
|
||||
let _ = el(&format!("edit-preview-{slot}")).set_attribute("src", url);
|
||||
input(&format!("edit-photo-{slot}")).set_value("");
|
||||
input(&format!("edit-delete-{slot}")).set_checked(false);
|
||||
input(&format!("edit-delete-{slot}")).set_disabled(url.is_empty());
|
||||
}
|
||||
state.borrow_mut().editing = Some(row);
|
||||
let _ = dialog().show_modal();
|
||||
let _ = input("edit-model").focus();
|
||||
}
|
||||
fn editing_controls(disable: bool) {
|
||||
let elements = el("edit-form").query_selector_all("input,button").unwrap();
|
||||
for i in 0..elements.length() {
|
||||
let node = elements.get(i).unwrap();
|
||||
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
|
||||
input.set_disabled(disable);
|
||||
} else if let Some(button) = node.dyn_ref::<HtmlButtonElement>() {
|
||||
button.set_disabled(disable);
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn save(state: Shared, editing: bool) -> Result<()> {
|
||||
if state.borrow().busy {
|
||||
return Ok(());
|
||||
}
|
||||
state.borrow_mut().busy = true;
|
||||
let result = save_inner(state.clone(), editing).await;
|
||||
state.borrow_mut().busy = false;
|
||||
if editing {
|
||||
editing_controls(false);
|
||||
if let Some(row) = state.borrow().editing.clone() {
|
||||
for slot in [1, 2] {
|
||||
input(&format!("edit-delete-{slot}"))
|
||||
.set_disabled(field(&row, &format!("photo{slot}Url")).is_empty());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
disabled("register-button", false);
|
||||
}
|
||||
result
|
||||
}
|
||||
async fn save_inner(state: Shared, editing: bool) -> Result<()> {
|
||||
let mut body = if editing {
|
||||
json!({"modelName":value("edit-model"),"ownerName":value("edit-owner")})
|
||||
} else {
|
||||
let digits = value("uas-code");
|
||||
json!({"serialNo":value("serial-no"),"modelName":value("model-name"),"ownerName":value("owner-name"),"uasCode":if digits.is_empty(){String::new()}else{format!("FPV{digits}")}})
|
||||
};
|
||||
if editing {
|
||||
editing_controls(true);
|
||||
} else {
|
||||
disabled("register-button", true);
|
||||
}
|
||||
for slot in [1, 2] {
|
||||
let id = if editing {
|
||||
format!("edit-photo-{slot}")
|
||||
} else {
|
||||
format!("photo-{slot}")
|
||||
};
|
||||
if editing && input(&format!("edit-delete-{slot}")).checked() {
|
||||
body[format!("photo{slot}")] = Value::Null;
|
||||
} else if let Some(p) = photo(&id).await? {
|
||||
body[format!("photo{slot}")] = json!(p);
|
||||
}
|
||||
}
|
||||
let url = if editing {
|
||||
let s = state.borrow();
|
||||
format!(
|
||||
"/api/records/{}",
|
||||
field(s.editing.as_ref().ok_or("请选择档案")?, "id")
|
||||
)
|
||||
} else {
|
||||
"/api/records".into()
|
||||
};
|
||||
let payload = api(&url, if editing { "PATCH" } else { "POST" }, Some(body)).await?;
|
||||
archive_status(&payload);
|
||||
if editing {
|
||||
dialog().close();
|
||||
message("history-message", "档案修改已保存。", false);
|
||||
let is_active = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|r| r["id"] == payload["record"]["id"]);
|
||||
if is_active {
|
||||
draw(&state, payload["record"].clone());
|
||||
}
|
||||
} else {
|
||||
draw(&state, payload["record"].clone());
|
||||
message(
|
||||
"form-message",
|
||||
if payload["existing"] == true {
|
||||
"该 SN 已登记,照片和填写的信息已保存。"
|
||||
} else {
|
||||
"登记成功,二维码已生成。"
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
let page = state.borrow().page.max(1);
|
||||
if let Err(error) = load(state, page).await {
|
||||
message(
|
||||
"history-message",
|
||||
&format!("已保存,但列表刷新失败:{error}"),
|
||||
true,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn download(url: &str, name: &str) {
|
||||
let a: HtmlAnchorElement = document().create_element("a").unwrap().unchecked_into();
|
||||
a.set_href(url);
|
||||
a.set_download(name);
|
||||
document().body().unwrap().append_child(&a).unwrap();
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
async fn export(state: Shared, kind: &str) -> Result<()> {
|
||||
let ids: Vec<_> = state.borrow().selected.iter().cloned().collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let response = Request::post(&format!("/api/export/{kind}"))
|
||||
.json(&json!({"ids":ids}))
|
||||
.map_err(|e| e.to_string())?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !response.ok() {
|
||||
return Err("导出失败,请重试".into());
|
||||
}
|
||||
let data = response.binary().await.map_err(|e| e.to_string())?;
|
||||
let array = js_sys::Array::new();
|
||||
array.push(&js_sys::Uint8Array::from(data.as_slice()));
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence(&array).map_err(err)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(err)?;
|
||||
download(
|
||||
&url,
|
||||
if kind == "excel" {
|
||||
"FPV-RID-登记记录.xlsx"
|
||||
} else {
|
||||
"FPV-RID-档案库.zip"
|
||||
},
|
||||
);
|
||||
message(
|
||||
"history-message",
|
||||
&format!("已导出 {} 条档案。", ids.len()),
|
||||
false,
|
||||
);
|
||||
spawn_local(async move {
|
||||
TimeoutFuture::new(30000).await;
|
||||
let _ = web_sys::Url::revoke_object_url(&url);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn download_qr(state: &Shared) -> Result<()> {
|
||||
let s = state.borrow();
|
||||
let row = s.active.as_ref().ok_or("请先登记")?;
|
||||
let qr = QrCode::encode_text(field(row, "qrUrl"), QrCodeEcc::Medium)
|
||||
.map_err(|_| "二维码生成失败")?;
|
||||
let canvas: HtmlCanvasElement = document()
|
||||
.create_element("canvas")
|
||||
.map_err(err)?
|
||||
.unchecked_into();
|
||||
canvas.set_width(640);
|
||||
canvas.set_height(640);
|
||||
let context: web_sys::CanvasRenderingContext2d = canvas
|
||||
.get_context("2d")
|
||||
.map_err(err)?
|
||||
.ok_or("Canvas 不可用")?
|
||||
.unchecked_into();
|
||||
context.set_fill_style_str("white");
|
||||
context.fill_rect(0.0, 0.0, 640.0, 640.0);
|
||||
context.set_fill_style_str("black");
|
||||
let cell = 640.0 / f64::from(qr.size() + 8);
|
||||
for y in 0..qr.size() {
|
||||
for x in 0..qr.size() {
|
||||
if qr.get_module(x, y) {
|
||||
let left = (f64::from(x + 4) * cell).floor();
|
||||
let top = (f64::from(y + 4) * cell).floor();
|
||||
let right = (f64::from(x + 5) * cell).ceil();
|
||||
let bottom = (f64::from(y + 5) * cell).ceil();
|
||||
context.fill_rect(left, top, right - left, bottom - top);
|
||||
}
|
||||
}
|
||||
}
|
||||
download(
|
||||
&canvas.to_data_url().map_err(err)?,
|
||||
&format!(
|
||||
"{}-{}-LOCAL.png",
|
||||
field(row, "serialNo"),
|
||||
field(row, "uasCode")
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn listen(name: &str, handler: impl FnMut(Event) + 'static) {
|
||||
let closure = Closure::<dyn FnMut(Event)>::new(handler);
|
||||
document()
|
||||
.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
closure.forget();
|
||||
}
|
||||
pub fn init() {
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
page: 1,
|
||||
..State::default()
|
||||
}));
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("submit", move |event| {
|
||||
let Some(target) = event.target().and_then(|t| t.dyn_into::<Element>().ok()) else {
|
||||
return;
|
||||
};
|
||||
let editing = target.id() == "edit-form";
|
||||
if !editing && target.id() != "register-form" {
|
||||
return;
|
||||
}
|
||||
event.prevent_default();
|
||||
let state = state.clone();
|
||||
spawn_local(async move {
|
||||
if let Err(e) = save(state, editing).await {
|
||||
message(
|
||||
if editing {
|
||||
"edit-message"
|
||||
} else {
|
||||
"form-message"
|
||||
},
|
||||
&e,
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("input", move |event| {
|
||||
if event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.is_some_and(|t| t.id() == "history-query")
|
||||
{
|
||||
clear_selection(&state);
|
||||
let generation = {
|
||||
let mut s = state.borrow_mut();
|
||||
s.generation += 1;
|
||||
s.generation
|
||||
};
|
||||
let state = state.clone();
|
||||
spawn_local(async move {
|
||||
TimeoutFuture::new(180).await;
|
||||
if state.borrow().generation != generation {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = load(state, 1).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("change", move |event| {
|
||||
let Some(t) = event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<HtmlInputElement>().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let id = t.id();
|
||||
if id == "select-all" {
|
||||
let mut s = state.borrow_mut();
|
||||
s.selected = if t.checked() {
|
||||
s.rows.iter().map(|r| field(r, "id").to_owned()).collect()
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
drop(s);
|
||||
render_rows(&state);
|
||||
} else if t.get_attribute("data-action").as_deref() == Some("select") {
|
||||
if let Some(card) = t.closest("[data-id]").ok().flatten() {
|
||||
let id = card.get_attribute("data-id").unwrap();
|
||||
if t.checked() {
|
||||
state.borrow_mut().selected.insert(id);
|
||||
} else {
|
||||
state.borrow_mut().selected.remove(&id);
|
||||
}
|
||||
render_rows(&state);
|
||||
}
|
||||
} else {
|
||||
for slot in [1, 2] {
|
||||
if id == format!("edit-photo-{slot}") {
|
||||
input(&format!("edit-delete-{slot}")).set_checked(false);
|
||||
}
|
||||
if id == format!("edit-delete-{slot}") && t.checked() {
|
||||
input(&format!("edit-photo-{slot}")).set_value("");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
listen("click", move |event| {
|
||||
let Some(t) = event
|
||||
.target()
|
||||
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||
.and_then(|t| t.closest("button").ok().flatten())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let id = t.id();
|
||||
let state = state.clone();
|
||||
if id == "edit-cancel" {
|
||||
dialog().close();
|
||||
return;
|
||||
}
|
||||
if id == "download-qr" {
|
||||
if let Err(e) = download_qr(&state) {
|
||||
message("form-message", &e, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(action) = t.get_attribute("data-action") {
|
||||
let Some(card) = t.closest("[data-id]").ok().flatten() else {
|
||||
return;
|
||||
};
|
||||
let record_id = card.get_attribute("data-id").unwrap();
|
||||
let row = state
|
||||
.borrow()
|
||||
.rows
|
||||
.iter()
|
||||
.find(|r| field(r, "id") == record_id)
|
||||
.cloned();
|
||||
let Some(row) = row else { return };
|
||||
if action == "edit" {
|
||||
edit(&state, row);
|
||||
return;
|
||||
}
|
||||
if action == "qr" {
|
||||
draw(&state, row);
|
||||
return;
|
||||
}
|
||||
if action == "delete" {
|
||||
if !window()
|
||||
.confirm_with_message(&format!(
|
||||
"确定删除 {} 的登记档案和照片吗?",
|
||||
field(&row, "serialNo")
|
||||
))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
spawn_local(async move {
|
||||
match api(&format!("/api/records/{record_id}"), "DELETE", None).await {
|
||||
Ok(p) => {
|
||||
archive_status(&p);
|
||||
state.borrow_mut().selected.remove(&record_id);
|
||||
let is_active = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|r| field(r, "id") == record_id);
|
||||
if is_active {
|
||||
state.borrow_mut().active = None;
|
||||
hidden("record-result", true);
|
||||
hidden("empty-result", false);
|
||||
}
|
||||
let page = state.borrow().page;
|
||||
if let Err(e) = load(state, page).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
}
|
||||
Err(e) => message("history-message", &e, true),
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
spawn_local(async move {
|
||||
let result = match id.as_str() {
|
||||
"previous-page" | "next-page" => {
|
||||
let page = {
|
||||
let s = state.borrow();
|
||||
if id == "previous-page" {
|
||||
s.page.saturating_sub(1).max(1)
|
||||
} else {
|
||||
s.page + 1
|
||||
}
|
||||
};
|
||||
clear_selection(&state);
|
||||
load(state, page).await
|
||||
}
|
||||
"refresh-list" => {
|
||||
let page = state.borrow().page;
|
||||
load(state, page).await
|
||||
}
|
||||
"export-excel" => export(state, "excel").await,
|
||||
"export-archive" => export(state, "archive").await,
|
||||
"retry-archive" => {
|
||||
disabled("retry-archive", true);
|
||||
let p = api("/api/archive/retry", "POST", Some(json!({}))).await;
|
||||
disabled("retry-archive", false);
|
||||
p.map(|p| archive_status(&p))
|
||||
}
|
||||
"copy-url" => {
|
||||
let url = state
|
||||
.borrow()
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|r| field(r, "qrUrl").to_owned());
|
||||
if let Some(url) = url {
|
||||
JsFuture::from(window().navigator().clipboard().write_text(&url))
|
||||
.await
|
||||
.map(|_| message("form-message", "本地二维码链接已复制。", false))
|
||||
.map_err(err)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
let close = Closure::<dyn FnMut(Event)>::new(move |event: Event| {
|
||||
if state.borrow().busy {
|
||||
event.prevent_default();
|
||||
}
|
||||
});
|
||||
el("edit-dialog")
|
||||
.add_event_listener_with_callback("cancel", close.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
close.forget();
|
||||
}
|
||||
spawn_local(async move {
|
||||
if let Err(e) = load(state, 1).await {
|
||||
message("history-message", &e, true);
|
||||
}
|
||||
match api("/api/archive/status", "GET", None).await {
|
||||
Ok(p) => archive_status(&p),
|
||||
Err(e) => message("history-message", &e, true),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "rid-web-worker"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
rid-shared = { path = "../rid-shared" }
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "WebSocket", "BinaryType", "MessageEvent", "CloseEvent", "ErrorEvent", "console"] }
|
||||
@@ -0,0 +1,8 @@
|
||||
// Module bootstrap only; telemetry decoding and state handling live in Rust.
|
||||
import init, {connect, acknowledge} from './rid_web_worker.js';
|
||||
const ready = init();
|
||||
self.onmessage = async event => {
|
||||
await ready;
|
||||
if (event.data?.type === 'connect') connect(event.data.url);
|
||||
if (event.data?.type === 'ack') acknowledge(event.data.sequence);
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
//! WebSocket decoding and latest-state merge execute outside the UI thread.
|
||||
use rid_shared::{Frame, PROTOCOL_VERSION, Target};
|
||||
use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
|
||||
use wasm_bindgen::{JsCast, prelude::*};
|
||||
|
||||
thread_local! {
|
||||
static PENDING: RefCell<Option<(web_sys::WebSocket, u64)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn acknowledge(sequence: f64) {
|
||||
PENDING.with(|pending| {
|
||||
if let Some((socket, expected)) = pending.borrow_mut().take() {
|
||||
if sequence as u64 == expected {
|
||||
let _ = socket.send_with_str(&expected.to_string());
|
||||
} else {
|
||||
let _ = socket.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
targets: BTreeMap<String, Target>,
|
||||
epoch: Option<u64>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn topology_changed(&self, frame: &Frame) -> bool {
|
||||
self.epoch.is_none()
|
||||
|| (frame.snapshot && self.targets.len() != frame.targets.len())
|
||||
|| !frame.removed.is_empty()
|
||||
|| frame
|
||||
.targets
|
||||
.iter()
|
||||
.any(|t| !self.targets.contains_key(&t.observation.target_id))
|
||||
}
|
||||
fn apply(&mut self, frame: &Frame) -> Result<(), &'static str> {
|
||||
if frame.version != PROTOCOL_VERSION {
|
||||
return Err("unsupported protocol version");
|
||||
}
|
||||
if frame.snapshot {
|
||||
self.targets.clear();
|
||||
self.epoch = Some(frame.epoch);
|
||||
} else if self.epoch != Some(frame.epoch) || frame.sequence < self.sequence {
|
||||
return Err("snapshot required");
|
||||
}
|
||||
self.sequence = frame.sequence;
|
||||
for id in &frame.removed {
|
||||
self.targets.remove(id);
|
||||
}
|
||||
for target in &frame.targets {
|
||||
self.targets
|
||||
.insert(target.observation.target_id.clone(), target.clone());
|
||||
}
|
||||
if self.targets.len() > 10000 {
|
||||
return Err("target capacity exceeded");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn post_status(scope: &web_sys::DedicatedWorkerGlobalScope, text: &str) {
|
||||
let object = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&object, &"status".into(), &text.into());
|
||||
let _ = scope.post_message(&object);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn connect(url: &str) -> Result<(), JsValue> {
|
||||
let scope: web_sys::DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let socket = web_sys::WebSocket::new(url)?;
|
||||
socket.set_binary_type(web_sys::BinaryType::Arraybuffer);
|
||||
let state = Rc::new(RefCell::new(State::default()));
|
||||
let sender = socket.clone();
|
||||
let output = scope.clone();
|
||||
let handler =
|
||||
Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
let data = js_sys::Uint8Array::new(&event.data()).to_vec();
|
||||
let frame = match postcard::from_bytes::<Frame>(&data) {
|
||||
Ok(f) => f,
|
||||
Err(_) => {
|
||||
post_status(&output, "invalid-frame");
|
||||
let _ = sender.close();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut state = state.borrow_mut();
|
||||
let topology_changed = state.topology_changed(&frame);
|
||||
if let Err(e) = state.apply(&frame) {
|
||||
post_status(&output, e);
|
||||
let _ = sender.close();
|
||||
return;
|
||||
}
|
||||
let mut positions = Vec::with_capacity(state.targets.len() * 4);
|
||||
let ids = js_sys::Array::new();
|
||||
let mut max_age = 0;
|
||||
for (id, target) in &state.targets {
|
||||
let o = &target.observation;
|
||||
if topology_changed {
|
||||
ids.push(&JsValue::from_str(id));
|
||||
}
|
||||
positions.extend_from_slice(&[
|
||||
o.longitude,
|
||||
o.latitude,
|
||||
f64::from(o.altitude_m),
|
||||
f64::from(o.heading_deg),
|
||||
]);
|
||||
max_age = max_age.max(frame.server_time_ms.saturating_sub(target.received_at_ms));
|
||||
}
|
||||
let array = js_sys::Float64Array::from(positions.as_slice());
|
||||
let buffer = array.buffer();
|
||||
let object = js_sys::Object::new();
|
||||
let memory: js_sys::WebAssembly::Memory = wasm_bindgen::memory().unchecked_into();
|
||||
let memory_buffer: js_sys::ArrayBuffer = memory.buffer().unchecked_into();
|
||||
for (key, value) in [
|
||||
("positions", array.into()),
|
||||
("sequence", JsValue::from_f64(frame.sequence as f64)),
|
||||
("serverAgeMs", JsValue::from_f64(max_age as f64)),
|
||||
("status", JsValue::from_str("connected")),
|
||||
(
|
||||
"wasmMemoryBytes",
|
||||
JsValue::from_f64(f64::from(memory_buffer.byte_length())),
|
||||
),
|
||||
] {
|
||||
let _ = js_sys::Reflect::set(&object, &key.into(), &value);
|
||||
}
|
||||
if topology_changed {
|
||||
let _ = js_sys::Reflect::set(&object, &"ids".into(), &ids);
|
||||
}
|
||||
let transfer = js_sys::Array::new();
|
||||
transfer.push(&buffer);
|
||||
if output
|
||||
.post_message_with_transfer(&object, &transfer)
|
||||
.is_ok()
|
||||
{
|
||||
PENDING
|
||||
.with(|pending| *pending.borrow_mut() = Some((sender.clone(), frame.sequence)));
|
||||
}
|
||||
});
|
||||
socket.set_onmessage(Some(handler.as_ref().unchecked_ref()));
|
||||
handler.forget();
|
||||
let output = scope.clone();
|
||||
let close = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_| {
|
||||
post_status(&output, "disconnected")
|
||||
});
|
||||
socket.set_onclose(Some(close.as_ref().unchecked_ref()));
|
||||
close.forget();
|
||||
let output = scope.clone();
|
||||
let error = Closure::<dyn FnMut(web_sys::ErrorEvent)>::new(move |_| {
|
||||
post_status(&output, "connection-error")
|
||||
});
|
||||
socket.set_onerror(Some(error.as_ref().unchecked_ref()));
|
||||
error.forget();
|
||||
post_status(&scope, "connecting");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn requires_snapshot_on_epoch_change() {
|
||||
let mut state = State::default();
|
||||
let mut frame = Frame {
|
||||
version: PROTOCOL_VERSION,
|
||||
epoch: 1,
|
||||
sequence: 1,
|
||||
snapshot: false,
|
||||
server_time_ms: 0,
|
||||
targets: vec![],
|
||||
removed: vec![],
|
||||
};
|
||||
assert!(state.apply(&frame).is_err());
|
||||
frame.snapshot = true;
|
||||
assert!(state.apply(&frame).is_ok());
|
||||
frame.epoch = 2;
|
||||
frame.snapshot = false;
|
||||
assert!(state.apply(&frame).is_err());
|
||||
frame.snapshot = true;
|
||||
assert!(state.apply(&frame).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# 天地图与自动离线资源
|
||||
|
||||
## 实现方式
|
||||
|
||||
浏览器始终请求本机 `/api/maps/tile/{layer}/{z}/{x}/{y}`,前端不接触天地图密钥。当前地图界面默认使用 `vec_w` 矢量底图的栅格瓦片与 `cva_w` 中文标注;代理也支持 `img_w`、`cia_w`,尚未增加影像切换控件。
|
||||
|
||||
在线部分使用天地图 WMTS 的 Web 墨卡托 `_w` 资源(tileMatrixSet=w),不是经纬度 `_c` 切片。RID 经纬度按共享协议的 WGS84 解释,地图投影由 MapLibre 处理;真实设备基准及精度仍需联调确认,不做 GCJ-02 偏移。
|
||||
|
||||
选择顺序:已有在线缓存 → 天地图在线请求(已配置密钥且不处于退避期)→ 离线 XYZ / MBTiles → 缺失提示。在线请求最多四个并发、总超时两秒;失败退避三十秒,期间使用离线资源。退避期结束后恢复在线优先,页面监测到模式变化会刷新瓦片源。
|
||||
|
||||
离线资源没有覆盖的区域返回 404,并在界面显示缺失瓦片累计数量;不返回伪造的街道或卫星图。离线坐标网格仅作位置参考。
|
||||
|
||||
## 本机密钥
|
||||
|
||||
在启动程序的环境中配置 `TIANDITU_TOKEN` 为自己的天地图服务端密钥,然后重启程序。无需将密钥发送到聊天中,也不要写进源码、Git 或网页。可以通过 Windows 用户环境变量配置,让下一次启动继承。
|
||||
|
||||
`GET /api/maps/status` 仅返回 keyConfigured,不返回密钥。上游 URL 和请求错误不写日志,以免其中包含 tk 参数。当前未取得有效密钥,因此天地图真实授权访问尚未实测;自动失败切换和恢复已通过本机受控上游测试。
|
||||
|
||||
## 离线资源位置
|
||||
|
||||
路径相对于 `--data-root`;默认是 exe 所在目录:
|
||||
|
||||
```text
|
||||
maps/
|
||||
offline/
|
||||
vec_w/{z}/{x}/{y}.png
|
||||
cva_w/{z}/{x}/{y}.png
|
||||
vec_w.mbtiles
|
||||
cva_w.mbtiles
|
||||
cache/
|
||||
vec_w/{z}/{x}/{y}.tile
|
||||
cva_w/{z}/{x}/{y}.tile
|
||||
```
|
||||
|
||||
XYZ 文件支持 png、jpg、jpeg 或带正确图像内容的 tile 扩展名。MBTiles 必须是 PNG/JPEG 栅格瓦片,默认按照 TMS 翻转行号;metadata.scheme=xyz 时不翻转。不支持把 PBF 矢量 MBTiles 直接当成栅格使用。
|
||||
|
||||
资源必须与 Web 墨卡托、256 像素瓦片和对应缩放级别兼容。当前级别范围为 0–18。在线缓存与离线预置资源分别存放,程序不删除用户离线文件。
|
||||
|
||||
缓存新增写入默认限额 512 MiB,满额后停止新增,不批量清理旧文件。缓存目录已有超额内容时不会主动删除。单瓦片最大 2 MiB;禁止通过符号链接跳出地图目录。
|
||||
|
||||
没有预置离线数据、也没有成功缓存的区域无法凭空离线显示地图。正式交付仍需要实际的离线地图文件,并验证目标区域与缩放级别覆盖。
|
||||
|
||||
## 验证
|
||||
|
||||
- `cargo test -p fpv-rid-registry maps::tests`:离线查找、MBTiles TMS、缓存限额、受控上游失败转离线与恢复。
|
||||
- `node scripts/test-maps.mjs`:独立 Release 进程,读取真实 PNG 测试瓦片与 SQLite MBTiles;检查图像字节、权限、边界及缺失状态。
|
||||
- 断网切换测试模拟的是上游网络故障。本地 127.0.0.1 服务仍需可访问;浏览器 DevTools 的全站 Offline 会同时阻断本机服务,不等价于电脑断开外网。
|
||||
@@ -0,0 +1,63 @@
|
||||
# RID 接收端:USB 串口、UDP 与 TCP
|
||||
|
||||
## 当前能力与实机边界
|
||||
|
||||
接收代码位于 `src/receiver.rs`,配置界面在目标研判页的“电脑接收设置”。传输层支持 Windows USB 串口、UDP 监听、TCP 监听;当前提供原始诊断、约定 JSON、约定 Postcard 三种解码模式。
|
||||
|
||||
厂商 RID 模块的具体型号、波特率和输出协议尚未提供,因此默认 **原始诊断**,不会把未知字节猜成位置,也不宣称已完成 ASTM/OpenDroneID 或某厂商报文的适配。USB 串口测试使用内存流验证分片;UDP/TCP 测试使用本机网络,均不替代真实模块联调。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[RID 接收端] -->|USB| B[选定 COM 串口]
|
||||
A -->|UDP / TCP 发送到电脑 IP 与端口| C[电脑接收监听]
|
||||
B --> D[有界原始诊断 / 已知协议解码]
|
||||
C --> D
|
||||
D --> E[共享实时目标存储]
|
||||
E --> F[WebSocket → Rust Worker → 地图]
|
||||
```
|
||||
|
||||
## USB 首次使用
|
||||
|
||||
1. 安装模块对应的 USB 串口驱动,确认实际 COM 号;界面可列出现有串口,也可手动输入。
|
||||
2. 选择 USB 串口,按模块文档填写波特率。115200 只是初始值,不代表已经确认模块参数;当前串口使用默认 8N1。
|
||||
3. 选择“原始数据诊断”,勾选启用,再保存。
|
||||
4. 核对状态、字节数是否增加、最近接收时间和诊断内容。仅枚举出 COM 或打开成功,不证明模块正在输出有效 RID 位置。
|
||||
5. “复制诊断数据”读取最近最多 4 KiB 的接收字节,可用于后续厂商协议适配。停止接收后仍保留诊断,重新启用接收时重置。
|
||||
|
||||
程序只读串口,不发送模块配置指令。打开串口会应用选定的通信参数;设备对开口、控制线和驱动的实际行为仍需实机确认。
|
||||
|
||||
115200 baud、8N1 的理论有效载荷上限约为 11520 字节/秒;若一条记录 100 字节,约为 115 条/秒,不能因为软件使用 Rust 就越过串口带宽。实际频率必须按模块报文长度与设备输出测量。
|
||||
|
||||
## 后续 UDP / TCP
|
||||
|
||||
用户确认的方向是模块主动发送到电脑,因此这里实现 **监听端**,不是让电脑主动连接远端服务。
|
||||
|
||||
- 测试默认监听 127.0.0.1:8788,只能接收本机数据。
|
||||
- 模块在局域网发送时,监听 IP 应配置为电脑的对应网卡地址,或明确选择 0.0.0.0;模块的目标 IP 应填写电脑可达的实际地址,不能填写 0.0.0.0 或 127.0.0.1。
|
||||
- 模块目标 IP/端口通过其配套工具配置;本项目尚未获得厂商配置指令,不会自动向模块写入网络设置。
|
||||
- 实际网络还需放行对应入站端口;本轮不自动修改 Windows 防火墙。
|
||||
- TCP 同时最多 8 个连接,空闲读超时 30 秒;UDP 每包上限受数据报大小限制。传输失败或串口断开后每 2 秒重试,切换配置或禁用时终止旧任务和旧连接。
|
||||
|
||||
## 已知格式
|
||||
|
||||
字段定义见 `synthetic-protocol.md` 的 Observation,共享同一 Rust 类型。即使使用真实传输,这些仍是本项目约定格式,不能假设厂商已经支持。
|
||||
|
||||
- JSON:USB/TCP 为每行一个 JSON 对象或数组,LF 分隔,可使用 CRLF。每行最大 64 KiB;超长行丢弃到下一行边界。UDP 每包一个对象或数组。
|
||||
- Postcard:正文为 `Vec<Observation>`。USB/TCP 使用四字节大端长度前缀,正文最大 2 MiB;UDP 每包直接放正文,不带长度前缀。
|
||||
- 每批最多 4096 条。坐标和身份字段通过校验后才进入目标存储;重复序号由实时核心拒绝。
|
||||
- 原始模式只更新字节统计和诊断,不生成目标。原始环形缓冲最多 4096 字节,状态仅展示最后 64 字节的十六进制摘要。
|
||||
|
||||
这不是多基站定位融合,也没有把目标 ID 擅自当作备案 SN;可信的身份映射需要厂商协议确认后接入。
|
||||
|
||||
## 配置与 API
|
||||
|
||||
`receiver-config.json` 位于数据根目录。首次默认禁用;保存为启用后,下一次启动会自动重连。配置原子写入,修改操作串行化;无效文件保留并报告错误,不覆盖成默认值。
|
||||
|
||||
- GET/POST `/api/receiver/config`:读取/保存配置。
|
||||
- GET `/api/receiver/status`:状态、端点、接收字节、解码/拒绝帧数、接受目标更新数、最后数据时间及错误。
|
||||
- GET `/api/receiver/ports`:只读枚举串口,不打开设备。
|
||||
- GET `/api/receiver/capture`:最近最多 4 KiB 的十六进制诊断。
|
||||
|
||||
配置接口只允许本机工作台来源。接收端点不提供身份认证或加密;局域网设备的协议校验、身份与网络隔离要在实机适配时明确。
|
||||
|
||||
`node scripts/test-receiver.mjs` 使用独立数据目录,验证 UDP/TCP 输入、分片、切换释放、禁用、持久化及来源限制,不访问真实串口。
|
||||
@@ -0,0 +1,60 @@
|
||||
# 实时通道 v1(合成数据适配器)
|
||||
|
||||
本协议为本项目实现的测试输入与网页推送契约,不是任何厂商的 RID 无线报文格式,也不包含接收设备驱动。
|
||||
|
||||
## 启动与输入
|
||||
|
||||
正常启动不允许写入实时目标。隔离测试时运行:
|
||||
|
||||
```powershell
|
||||
fpv-rid-registry.exe --data-root "D:\独立测试目录" --simulation-api
|
||||
```
|
||||
|
||||
`POST /api/realtime/ingest` 支持 application/json 的 Observation 数组,也支持 application/octet-stream 的 Postcard Vec<Observation>,类型与锁定依赖均来自共享 Rust crate。单请求最多 4096 条、2 MiB;完整批次字段校验不通过时返回 400 且不应用该批。容量或旧序号可逐条拒绝,返回 accepted 及累计指标。
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"target_id": "SIM-00001",
|
||||
"receiver_id": "SIMULATOR",
|
||||
"source_epoch": 1,
|
||||
"sequence": 1,
|
||||
"longitude": 120.1,
|
||||
"latitude": 30.0,
|
||||
"altitude_m": 100.0,
|
||||
"heading_deg": 90.0
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- ID 只允许 1–64 位 ASCII 字母、数字、连字符和下划线。
|
||||
- 坐标为 WGS84,经度 [-180,180]、纬度 [-90,90];高度为椭球高,范围 [-1000,100000] m;航向 [0,360) 度。拒绝非有限浮点值。
|
||||
- 每个接收站的 source_epoch 必须在重启后严格增加;同一 epoch 内 sequence 严格增加。旧 epoch、重复或倒序 sequence 不更新状态。
|
||||
- 每目标最多记住 8 个接收站;当前使用“最新接受的到达值”,没有未经验证的多基站定位融合。
|
||||
- 当前单进程容量 10000 目标,TTL 为 30 秒(每秒执行清理)。达到容量后拒绝新增目标,不静默驱逐在线目标。
|
||||
- 未提供模块 SN 与设备身份的可信对应关系,因此不会将 target_id 擅自当成备案 serialNo。
|
||||
|
||||
## 读取与推送
|
||||
|
||||
- `GET /api/realtime/status`:模式、目标数量、接受/旧数据/拒绝/过期计数、客户端数量及限制。
|
||||
- `GET /api/realtime/snapshot`:当前 JSON 快照,供诊断和测试,不作为高频轮询接口。
|
||||
- `GET /api/realtime/ws`:WebSocket 二进制帧;数据结构见 `crates/rid-shared/src/lib.rs` 的 Frame,使用锁定版本 Postcard 编码。
|
||||
- 所有接口只监听 127.0.0.1:8787,拒绝不属于本机登记站的 Origin。没有独立的远程用户鉴权,不能直接转发到公网。
|
||||
|
||||
Frame.version 为 1;epoch 是服务进程会话标识;sequence 是状态水位,而非连续的推送包编号。首次连接发送 snapshot=true;之后每 20 ms 最多一批合并增量。有限变更日志已覆盖客户端游标时会重新发完整快照。targets 为最新状态,removed 为已移除目标 ID。
|
||||
|
||||
客户端完成解码、合并并提交主线程绘制后,发送文本形式的 sequence 确认。每客户端最多一个未确认批次;发送超时 200 ms、确认超时 1 秒,超过即断开。重连必须从快照开始;当前最多 4 个并发客户端。
|
||||
|
||||
Rust Worker 保留有界目标状态并向主线程转移 TypedArray;主线程反馈后才确认服务端。页面后台暂停绘制可能触发确认超时,恢复可见后重新创建 Worker 并获取快照。Worker 内部占用随 terminate 释放。
|
||||
|
||||
## 合成负载工具
|
||||
|
||||
先启动独立测试服务,再运行:
|
||||
|
||||
```powershell
|
||||
cargo run --release -p realtime-core --bin rid-simulator -- --targets 1000 --interval-ms 20 --seconds 30
|
||||
```
|
||||
|
||||
此工具发送 HTTP Postcard 二进制批次,并输出实际执行时间和未达到请求周期的次数;请求 1 ms 不表示实际达到 1 ms,也不模拟无线传输可靠性。测试数据仅留在实时内存,不写入备案 SQLite。
|
||||
|
||||
自动浏览器测试可用 RID_INPUT_FORMAT=binary 调用独立 Rust 生成器,默认使用 HTTP JSON。自动浏览器测试:`node scripts/test-realtime.mjs`。环境变量 RID_TARGETS(最多 10000)和 RID_SOAK_SECONDS(最多 7200)控制负载。该测试使用自己的临时数据目录,并拒绝附着到已经占用 8787 的服务。
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"checked_on": "2026-10-21",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"meaning": "Observed official metadata; not a compatibility test. max_version may be prerelease.",
|
||||
"versions": [
|
||||
{
|
||||
"name": "yew",
|
||||
"source": "https://crates.io/api/v1/crates/yew",
|
||||
"stable": "0.23.0",
|
||||
"latest": "0.23.0",
|
||||
"published": "2026-03-10T11:49:00.296931Z",
|
||||
"rust_version": "1.84.0",
|
||||
"repository": "https://github.com/yewstack/yew"
|
||||
},
|
||||
{
|
||||
"name": "axum",
|
||||
"source": "https://crates.io/api/v1/crates/axum",
|
||||
"stable": "0.8.9",
|
||||
"latest": "0.8.9",
|
||||
"published": "2026-04-14T07:55:20.258398Z",
|
||||
"rust_version": "1.80",
|
||||
"repository": "https://github.com/tokio-rs/axum"
|
||||
},
|
||||
{
|
||||
"name": "dioxus",
|
||||
"source": "https://crates.io/api/v1/crates/dioxus",
|
||||
"stable": "0.7.10",
|
||||
"latest": "0.8.0-alpha.3",
|
||||
"published": "2026-07-30T23:14:52.497403Z",
|
||||
"rust_version": "1.83.0",
|
||||
"repository": "https://github.com/DioxusLabs/dioxus/"
|
||||
},
|
||||
{
|
||||
"name": "leptos",
|
||||
"source": "https://crates.io/api/v1/crates/leptos",
|
||||
"stable": "0.8.22",
|
||||
"latest": "0.9.0-rc0",
|
||||
"published": "2026-10-05T13:28:16.443095Z",
|
||||
"rust_version": "1.88",
|
||||
"repository": "https://github.com/leptos-rs/leptos"
|
||||
},
|
||||
{
|
||||
"name": "cargo-leptos",
|
||||
"source": "https://crates.io/api/v1/crates/cargo-leptos",
|
||||
"stable": "0.3.11",
|
||||
"latest": "0.3.11",
|
||||
"published": "2026-10-02T18:10:37.647666Z",
|
||||
"rust_version": "1.82.0",
|
||||
"repository": "https://github.com/leptos-rs/cargo-leptos"
|
||||
},
|
||||
{
|
||||
"name": "deck",
|
||||
"source": "https://api.github.com/repos/visgl/deck.gl/releases/latest",
|
||||
"stable": "v9.4.0",
|
||||
"published": "2026-09-05T21:54:36Z",
|
||||
"url": "https://github.com/visgl/deck.gl/releases/tag/v9.4.0",
|
||||
"prerelease": false
|
||||
},
|
||||
{
|
||||
"name": "wasm-bindgen",
|
||||
"source": "https://crates.io/api/v1/crates/wasm-bindgen",
|
||||
"stable": "0.2.129",
|
||||
"latest": "0.2.129",
|
||||
"published": "2026-09-25T07:13:40.367031Z",
|
||||
"rust_version": "1.81",
|
||||
"repository": "https://github.com/wasm-bindgen/wasm-bindgen"
|
||||
},
|
||||
{
|
||||
"name": "tokio",
|
||||
"source": "https://crates.io/api/v1/crates/tokio",
|
||||
"stable": "1.54.0",
|
||||
"latest": "1.54.0",
|
||||
"published": "2026-10-19T16:33:48.98743Z",
|
||||
"rust_version": "1.85",
|
||||
"repository": "https://github.com/tokio-rs/tokio"
|
||||
},
|
||||
{
|
||||
"name": "cesium",
|
||||
"source": "https://api.github.com/repos/CesiumGS/cesium/releases/latest",
|
||||
"stable": "1.146",
|
||||
"published": "2026-10-01T20:55:53Z",
|
||||
"url": "https://github.com/CesiumGS/cesium/releases/tag/1.146",
|
||||
"prerelease": false
|
||||
},
|
||||
{
|
||||
"name": "tauri",
|
||||
"source": "https://crates.io/api/v1/crates/tauri",
|
||||
"stable": "2.12.4",
|
||||
"latest": "3.0.0-alpha.5",
|
||||
"published": "2026-10-14T18:52:10.735395Z",
|
||||
"rust_version": "1.90",
|
||||
"repository": "https://github.com/tauri-apps/tauri"
|
||||
},
|
||||
{
|
||||
"name": "trunk",
|
||||
"source": "https://crates.io/api/v1/crates/trunk",
|
||||
"stable": "0.22.0",
|
||||
"latest": "0.22.0",
|
||||
"published": "2026-10-20T08:55:16.985923Z",
|
||||
"rust_version": "1.96.1",
|
||||
"repository": "https://github.com/trunk-rs/trunk"
|
||||
},
|
||||
{
|
||||
"name": "maplibre-gl-js",
|
||||
"stable": "v6.15.0",
|
||||
"published": "2026-10-18T12:57:17Z",
|
||||
"source": "https://api.github.com/repos/maplibre/maplibre-gl-js/releases/latest",
|
||||
"url": "https://github.com/maplibre/maplibre-gl-js/releases/tag/v6.15.0",
|
||||
"prerelease": false
|
||||
},
|
||||
{
|
||||
"name": "rust",
|
||||
"stable": "1.99.1 (58cf8f9c3 2026-10-13)",
|
||||
"manifest_date": "2026-10-15",
|
||||
"source": "https://static.rust-lang.org/dist/channel-rust-stable.toml"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
# Rust 全栈与无人机实时目标平台:方案审查及实施计划
|
||||
|
||||
核查日期:2026-10-21(Asia/Shanghai)。状态:原始计划,已进入实施;进展见同目录上级 review/implementation-status.md;版本信息已在线核查,性能数字均为拟议验收目标或负载计算,不是本项目跑分。
|
||||
|
||||
## 1. 结论与范围
|
||||
|
||||
推荐 **Leptos CSR/Wasm + 现有 Axum/Tokio + 独立实时状态通道 + MapLibre 地图适配层**。前后端业务代码使用 Rust,统一 Cargo workspace,由一条构建入口先生成前端资源,再嵌入后端,继续交付 Windows x64 单 exe。
|
||||
|
||||
这比当前方案新增的核心能力是:Rust 前端、共享数据契约、实时接收与状态处理、地图及可重复的容量测试。不是只把原 app.js 翻译成 Rust。
|
||||
|
||||
交付含义必须明确:
|
||||
|
||||
- 业务前后端统一 Rust;浏览器仍使用 HTML/CSS、Wasm 加载胶水和成熟地图引擎的 JavaScript。
|
||||
- 统一构建命令,不等于仅编译一个 target:后端是 Windows 原生 target,前端是 wasm32-unknown-unknown。
|
||||
- 程序发布后不需要 Node.js;开发主构建链也以 Cargo/Trunk 为目标,现有 Node 测试脚本可继续作为开发工具。
|
||||
- 单 exe 可内嵌代码资源,但地图瓦片、字体、精灵、地形等外部数据不会自动离线可用;离线地图另设数据包和授权验收。
|
||||
- 桌面窗口封装暂不引入 Tauri;未来确需窗口再评估,其 WebView2 运行时属于额外环境边界。
|
||||
|
||||
## 2. 已知、假设与待确认
|
||||
|
||||
已知:用户明确要求 Rust 前后端一体化;未来有大量无人机实时目标;单机上报被描述为“毫秒级”,数量及准确间隔未知。
|
||||
|
||||
“时间戳精度为毫秒”和“每隔几毫秒产生一条位置”不同;毫秒级暂作为待确认的高频输入要求,不能直接认定为 1,000 Hz。设备有效位置刷新率、重复报文和多个基站对同一目标的重复报告也必须分别统计。
|
||||
|
||||
当前默认假设:Windows 本地部署、先一台终端、二维地图作为容量验证基线;三维、远程多终端、全量原始报文长期留存均未被确认。该假设用于完成计划,不等同于用户已选地图产品或正式 UI。
|
||||
|
||||
本机只读硬件信息:Ryzen 7 5800H(8 核 / 16 线程)、约 31.4 GiB 可见内存、RTX 3070 Laptop GPU 与 AMD 集成显卡并存。测试必须记录浏览器实际启用的 GPU、供电与温度状态;硬件列表不是性能承诺。
|
||||
|
||||
实施前收集:真实报文样本和协议;UDP/TCP/串口等接入方式;准确上报周期;目标 ID 与接收站 ID;坐标系、经纬度及高度基准;二维/三维;离线地图需求;原始数据保留策略。现阶段可用明确标注的仿真源推进独立验证,不能宣称完成设备适配。
|
||||
|
||||
## 3. 当前代码审查
|
||||
|
||||
### 已可复用
|
||||
|
||||
- `src/store.rs`:备案 SQLite、事务、照片、旧数据导入。
|
||||
- `src/archive.rs`:离线卡片、备份、ZIP/XLSX;继续服务低频备案业务。
|
||||
- `src/http.rs`:现有 HTTP 契约和静态资源出口。
|
||||
- `scripts/package.ps1`:暂存、发布白名单、运行数据保护和校验和。
|
||||
- `scripts/test-browser.mjs` 等:可复用的用户流程验收,不需要为移除 Node 后端而全部重写。
|
||||
- `Cargo.lock` 当前锁定 Axum 0.8.9、Tokio 1.54.0;与本次官方稳定版查询一致。Rust 工具链 1.99.1 也与官方 stable manifest 一致。
|
||||
|
||||
### 必须在实时平台建设时处理的限制
|
||||
|
||||
1. **单一工作队列**:`src/main.rs:8` 使用 `std::sync::mpsc`,`:55` 创建无界 channel;`src/http.rs:132` 将请求工作集中送入该线程,连静态资源响应也在同一个闭包中处理。当前适用于小型登记站,不应作为高频遥测总入口。
|
||||
2. **写入触发全量派生文件同步**:`src/http.rs:139` 等调用 `archive::finish`;`src/archive.rs:98` 读取全部备案并生成档案、备份。高频位置更新不得触发这条链路;导出/备份也不得阻塞目标推送。
|
||||
3. **尚无实时协议**:当前依赖未启用 Axum `ws`,代码无目标快照、增量、乱序、丢帧、订阅或重连恢复实现。需要新增,不是开启一个配置即可获得。
|
||||
4. **资源路由尚不适配 Wasm**:目前硬编码少量 HTML/JS/CSS 资源;需要支持哈希资源名、`.wasm` MIME、模块 JS、Worker、地图资产及资源版本一致性。
|
||||
5. **现有 CSP 会阻碍 Wasm**:当前 `script-src 'self'` 未允许 Wasm 编译。迁移时用最小权限补上 `'wasm-unsafe-eval'`,按实际 Worker 构建配置限定 `worker-src`;不能为了能运行整体关闭 CSP。
|
||||
6. **表单前端不能直接扩成海量目标 DOM 列表**:Leptos 负责控件与详情;目标坐标走独立缓冲区和地图图层,不能为每架飞机每条报文触发组件重建。
|
||||
|
||||
这些是面向新负载的架构限制,不代表已验证登记流程当前不可用。本轮没有修改这些实现。
|
||||
|
||||
## 4. 最新稳定版核查与选型
|
||||
|
||||
以下为 2026-10-21 官方 crates.io / GitHub / Rust manifest 的实时查询结果,详细来源见同目录 `official-version-snapshot.json`。发布频繁,正式开始 P1 时重查安全公告与兼容性,之后锁定,不在构建中追踪 latest。
|
||||
|
||||
- **Rust 1.99.1**:官方 stable manifest 日期 2026-10-15,当前项目已使用;维持。
|
||||
- **Leptos 0.8.22**:稳定版发布于 2026-10-05;0.9.0-rc0 是预发布。本项目首选稳定版 CSR。
|
||||
- **Trunk 0.22.0**:发布于 2026-10-20,最低 Rust 1.96.1;当前工具链满足其声明要求。由于刚发布,先通过 Windows/Worker/资源嵌入 PoC 再锁定,不能把版本新当成已兼容。
|
||||
- **wasm-bindgen 0.2.129**:前端 crate 与生成胶水的 CLI 版本必须匹配;统一记录工具版本。
|
||||
- **Axum 0.8.9 / Tokio 1.54.0**:继续使用,按需启用 WebSocket、同步和时间等 features。
|
||||
- **MapLibre GL JS 6.15.0**:稳定 release 于 2026-10-18;作为二维/倾斜地图候选基线。高频更新性能需要实测,不能用静态海量点示例代替。
|
||||
- **deck.gl 9.4.0**:仅作为 GPU 目标/轨迹图层的候选,不与自研图层同时默认引入。
|
||||
- **CesiumJS 1.146**:用户确认真实三维地球、地形和三维模型需求后单独做 PoC,不在首期同时维护两套地图。
|
||||
|
||||
比较过的其他路线:
|
||||
|
||||
- **Dioxus 0.7.10**(0.8.0-alpha.3 为预发布):适合更强调跨端的项目;本项目已有 Axum/网页/单 exe 结构,采用 Leptos CSR 的迁移边界更直接。不是断言 Dioxus 性能更差。
|
||||
- **Yew 0.23.0**:可行,但当前没有 Yew 存量需要继承;不为本项目另加一套框架。框架间性能优劣需同场景测试,不能凭框架机制给跑分结论。
|
||||
- **cargo-leptos 0.3.11**:服务端渲染路线的工具候选;本机操作台没有已知 SEO 或 SSR 需求,首期不引入 SSR/hydration,使用 Trunk 构建 CSR。
|
||||
- **Tauri 2.12.4**(3.0.0-alpha.5 为预发布):未来桌面外壳选项,不是 Rust 前端的必要条件,也不会自动加速地图。
|
||||
- **纯 Rust 原生 UI / 自研完整地图引擎**:需要重新处理地图生态与渲染能力,当前收益不足,不作为这一轮迁移前提。WebGPU/wgpu 也先作为后续实验项,不作为首期依赖。
|
||||
|
||||
## 5. 推荐运行结构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[设备或独立仿真源] --> B[Rust 协议接入与校验]
|
||||
B --> C[按目标维护最新状态\n时间戳、序号、有效性]
|
||||
B --> E[事件与历史通道\n独立持久化策略]
|
||||
C --> D[订阅过滤与有界增量批次]
|
||||
D -->|WebSocket 二进制| W[Web Worker + Rust Wasm\n解码、合并、过期处理]
|
||||
W -->|可转移缓冲区| M[地图适配层与 GPU 图层]
|
||||
M --> U[Leptos 控件、选择和详情]
|
||||
R[备案 API / SQLite / 档案导出] --> U
|
||||
```
|
||||
|
||||
### 服务端
|
||||
|
||||
- 从模块化单体开始,继续一个原生进程;设备接入、实时状态、会话推送、备案数据库、档案任务分别具有任务/队列边界。
|
||||
- 首先按协议校验身份字段、时间和坐标。`receiver_id` 与 `target_id` 分开;没有证据时,不按距离擅自合并两架无人机。
|
||||
- 单源序号、设备会话和接收时间用于去重与乱序处理;不同基站的序号不能直接比较。没有可靠采样时间时,标记数据质量,采用可解释的接收顺序策略。
|
||||
- 最新状态按目标覆盖,使用有容量上限的表、TTL 与准入策略;所有队列同时限制条数/字节/允许滞后时间,并暴露容量与丢弃/合并指标。
|
||||
- 区分“位置状态可合并”和“告警/业务事件需要保留”。UDP 输入无法靠内部队列保证无丢包;必须统计系统接收丢包、应用拒绝和序号缺口。持久化事件需要可恢复游标、确认/重试及容量规划后才能承诺可靠性。
|
||||
- 当前 SQLite 保留备案职责;位置高频写入不直接落进现有档案同步。历史记录采用独立分批写入路径,先按保留期限估算数据量;未确认留存需求前不引入 Kafka/时序集群。
|
||||
|
||||
### 推送协议
|
||||
|
||||
- REST 管理备案;独立 `/api/realtime/ws` 承载实时流(拟议接口,尚未实现)。
|
||||
- 消息包含协议版本、会话 epoch、快照 ID/序号、批次序号、服务端时间、目标稳定 ID,以及新增/更新/移除和质量标记。
|
||||
- 首次连接先发送有上限、可分块的快照,再从快照水位接增量;序号不连续或订阅版本变化时明确重同步,防止快照覆盖较新的数据。
|
||||
- 首期使用共享 Rust 数据模型与二进制编码做 PoC;具体编码以 schema 演进、Worker 解码耗时和包体测试后冻结。优先评估版本化 Postcard;若确定对外 Java/Go 消费则评估 Protobuf。编码方案未验证前不写死到正式协议。
|
||||
- 推送按时间预算和字节预算合批,不按报文逐条发送;先比较 10/20/50 ms。视口外目标可降低展示更新频率,但不能因此停止后台告警计算。
|
||||
- 标准 WebSocket 没有自动接收背压。服务器对慢客户端限制积压、设置发送超时、按序号/应用进度判断延迟;必要时关闭连接并重建快照。已经进入 TCP 的旧数据不能“原地替换”,所以必须在发送前合并。
|
||||
- 遥测可覆盖旧状态;如果将来增加设备指令,必须有独立权限、审计和确认语义,不能复用可丢弃的位置通道。
|
||||
|
||||
### 浏览器 / Rust 前端
|
||||
|
||||
- Leptos 管理表单、筛选、选中目标、详情、连接质量和告警列表;高频位置数据独立于每个组件的响应式状态。
|
||||
- Worker 中使用 Rust/Wasm 完成批次解码、合并、有限历史和质量处理,主线程接收适合渲染的 TypedArray/ArrayBuffer。
|
||||
- 通过可转移缓冲区和缓冲池减少跨线程复制;转移后发送方缓冲区不可继续使用。Wasm 线性内存到可转移缓冲区、以及上传 GPU 仍可能发生复制,不宣称端到端零拷贝。
|
||||
- 主线程按 requestAnimationFrame 绘制,绘制频率不等于传感器有效刷新率。显示原始数据年龄;插值/外推分别标记,过期阈值依输入周期配置,不能伪装为新位置。
|
||||
- 页面隐藏、恢复、Worker 重启、网络断开、地图上下文丢失、地图样式切换都要有明确恢复流程。
|
||||
- 首期不强制 SharedArrayBuffer 或共享 Wasm 多线程;这涉及跨源隔离及地图资源头配置,只有测出传输瓶颈后再评估。
|
||||
|
||||
## 6. 地图方案与选择门槛
|
||||
|
||||
地图底图和高频目标图层分开。独立 PoC 比较以下两条路径,使用同一负载、同一浏览器与同一实际 GPU:
|
||||
|
||||
1. MapLibre 内置图层 + 有稳定 feature ID 的 `GeoJSONSource.updateData`,作为实现成本较低的基线。官方明确需要唯一 ID;不是每条报文调用全量 setData。
|
||||
2. MapLibre + 批量 GPU 目标图层:比较定制 WebGL2 实例化图层与 deck.gl binary attributes,择一。地图已有底图坐标与相机管理,高频层只负责目标、选择和有限轨迹。
|
||||
|
||||
只有基线达到目标负载下的帧时间、数据年龄和内存指标,才能采用。否则切换批量图层,不能无限增加刷新节流来掩盖延迟。
|
||||
|
||||
主要规则:批量上传变化;屏幕外剔除;标签设数量预算;轨迹设时间/点数上限并按缩放简化;只为当前选中或少数悬停目标创建 DOM 详情。不能给所有目标持续展示弹窗,也不能反复重建整张地图。
|
||||
|
||||
坐标契约统一说明经纬度单位、轴顺序、WGS84/GCJ-02/BD-09 和高度基准。地图商使用什么坐标就在哪个边界做转换,禁止重复纠偏。测试跨日期变更线、异常坐标和负高度。第三方底图 token、配额与授权另行验证。
|
||||
|
||||
若选择 Cesium 三维,复用相同实时协议与状态逻辑,单独验证 Primitive/实例化更新、地形遮挡、拾取、资源释放及三维帧预算;二维结果不能当三维验收。
|
||||
|
||||
## 7. 统一构建与项目组织
|
||||
|
||||
先建立最小 workspace:
|
||||
|
||||
```text
|
||||
crates/
|
||||
server/ # 现有 Axum 后端与备案模块
|
||||
web-ui/ # Leptos CSR 界面
|
||||
shared/ # 经过筛选的 DTO、协议版本与纯校验逻辑
|
||||
xtask/ # 统一构建、校验和、打包入口
|
||||
```
|
||||
|
||||
实时 PoC 开始后再按实际边界增加 `realtime-core`、`web-worker` 和仿真工具,避免先造空模块。共享 crate 不依赖 SQLite、Tokio 网络或浏览器 DOM;现有 JSON 驼峰字段与接口兼容性保持明确。
|
||||
|
||||
拟议统一入口:`cargo xtask package`(目前不存在,P1 实现)。流程:
|
||||
|
||||
1. 检查锁定的 Rust、Trunk、wasm-bindgen 和所需 target。
|
||||
2. 构建 Worker/Wasm 与 Leptos 页面,收集 CSS、加载 JS、地图 SDK、字体/精灵/Worker 文件。
|
||||
3. 从生成清单嵌入前端资源,构建 Windows Release;不在 build.rs 中递归启动前端 Cargo。
|
||||
4. 在临时数据目录启动做资源与 API 冒烟,再按白名单打包、生成源码版本/工具链/资源哈希和依赖许可清单。
|
||||
|
||||
保留已有 `scripts/package.ps1` 作为兼容入口,后续调用统一任务,避免两套打包逻辑。原生与 Wasm 产物分目录;不要全局把 build.target 改成 Wasm。现有 Windows 静态 CRT 设置只适用于对应原生 target。
|
||||
|
||||
地图 SDK 采取固定版本的浏览器发行文件并本地化、记录校验和与许可,加载时不依赖 CDN。Trunk 本身不等于任意 npm 包的通用打包器;若某候选地图扩展只有 npm 模块且必须 Node 构建,先在 PoC 暴露成本,再决定预构建资产或替代方案,不能隐瞒新增工具依赖。
|
||||
|
||||
发布资源需要正确 MIME(特别是 application/wasm)、内容版本一致、CSP、Worker 路径和离线启动验证。页面资源可按哈希缓存,API 不沿用静态资源长缓存;升级测试不得加载旧 JS 配新 Wasm。
|
||||
|
||||
## 8. 未知容量下的验证方法
|
||||
|
||||
设目标数为 N、实际每目标间隔为 T 毫秒,则输入更新率为 `N × 1000 / T`。若一次更新按 64 字节有效负载估算,吞吐为 `更新率 × 64`;64 字节只是测算假设,不含协议、TLS、重复接收和对象开销。
|
||||
|
||||
用于逐级发现瓶颈的起始档位,均不是承诺容量:
|
||||
|
||||
- 1,000 目标 / 100 ms:10,000 更新/秒,约 0.64 MB/s。
|
||||
- 1,000 目标 / 10 ms:100,000 更新/秒,约 6.4 MB/s。
|
||||
- 10,000 目标 / 20 ms:500,000 更新/秒,约 32 MB/s。
|
||||
- 10,000 目标 / 10 ms:1,000,000 更新/秒,约 64 MB/s。
|
||||
- 10,000 目标 / 1 ms:10,000,000 更新/秒,约 640 MB/s;仅作为极端边界探索,可能首先受设备/网络/生成器限制。
|
||||
|
||||
分别改变 N、间隔(100/50/20/10/5/1 ms)、可见目标比例、标签/轨迹密度、客户端数(1/2/4)、突发倍数。单维加压后再测组合;超出预算停止升级负载,记录首次失败边界,不能把压垮机器作为验收方式。
|
||||
|
||||
负载分五段:生成器独立校准 → 接收/解码 → 状态合并/推送 → Worker/地图 → 带备案导出和备份的混合负载。生成器能力必须单独证明,必要时异机发包;同机发包会争抢 CPU,不能据此推断生产网络极限。
|
||||
|
||||
拟议本机验收门槛,待 P0/P1 实测后冻结:
|
||||
|
||||
- 对宣布支持的档位,服务端“接收完成→最新状态发布”p95 ≤ 20 ms、p99 ≤ 50 ms。
|
||||
- “服务端接收→浏览器应用并提交绘制”p95 ≤ 100 ms、p99 ≤ 200 ms;它是软件测量口径,不等于屏幕像素实际点亮延迟。
|
||||
- 交互目标 60 FPS;支持档位下帧时间 p95 ≤ 33.3 ms,并统计长任务、拾取响应和卡顿分布;平均 FPS 不足以验收。
|
||||
- 热身后 30 分钟观察内存平台,持续 2 小时无无限增长、无持续增加的状态年龄;上限在 P0 按目标存储、轨迹和渲染预算明确。
|
||||
- 记录丢包、拒绝、合并、过期与重同步次数。可合并的位置不得误报为数据完整保留;可靠事件不得静默丢失。
|
||||
- 网络中断、乱序、重复、突发、慢客户端、后台标签页恢复后,状态在限定恢复窗口内重新一致,旧位置不覆盖新位置。
|
||||
- 原有备案九项测试及浏览器操作继续通过;导出或备份故障不让实时通道积压。
|
||||
|
||||
端到端设备采样延迟只有在设备时间可用且时钟对齐误差可测时才验收;否则报告接收后的处理延迟与网络 RTT,不能把不同机器的时间直接相减。
|
||||
|
||||
最终发布容量报告必须同时列出目标数、输入频率、可见目标数、地图类型、标签/轨迹设置、客户端数、硬件/浏览器/GPU、推送频率、延迟分位数、内存与丢弃策略。没有这些条件,“支持多少架”没有可重复意义。
|
||||
|
||||
## 9. 分阶段执行计划
|
||||
|
||||
### P0:事实与负载基线(1–2 人日)
|
||||
|
||||
产出:设备样本/待确认项、仿真负载定义、指标口径、现有备案基线、部署与地图假设。
|
||||
|
||||
验收:有可重复的输入生成/回放描述;准确区分采样、上报、接收、展示频率;没有设备协议时明确保留适配缺口。
|
||||
|
||||
### P1:Rust 全栈最小闭环(2–4 人日,依赖 P0)
|
||||
|
||||
产出:最小 workspace、Leptos 页面、Worker 消息往返、与 Axum 的简单调用、统一构建命令和资源嵌入。
|
||||
|
||||
验收:干净环境可构建;发布 exe 在无 Node PATH、中文目录和不同 cwd 下启动;Wasm、Worker、CSP、哈希资源与离线代码资源加载通过。锁定版本后才开始全面迁移。
|
||||
|
||||
### P2:登记界面等价迁移(3–5 人日,依赖 P1)
|
||||
|
||||
产出:登记、照片、分页、搜索、编辑、二维码、导出与同步状态的 Rust 组件。
|
||||
|
||||
验收:现有 API/浏览器场景全部通过;事件卸载、焦点、错误状态和网络失败正确;不同时改数据库业务规则。迁移通过后删除旧 app.js 业务实现,二维码依赖若保留则作为第三方资产标明。
|
||||
|
||||
### P3:实时通道与独立仿真(4–7 人日,依赖 P1、P0)
|
||||
|
||||
产出:有界接入、目标状态、去重/乱序、快照/增量、慢客户端处理、基础指标、独立仿真工具。
|
||||
|
||||
验收:逐级负载下时间和队列可观测;重连一致;导出/备份与实时处理互不阻塞。真实设备协议未到位时仅宣称仿真完成。
|
||||
|
||||
### P4:地图技术 PoC 与 UI 选择(3–5 人日,依赖 P1;可使用 P3 仿真)
|
||||
|
||||
产出:MapLibre 增量基线与 GPU 图层候选的同条件测量,明确是否需要 Cesium;独立地图工作台 A/B/C 三个实质不同的可视原型。
|
||||
|
||||
验收:以帧时间、数据年龄、内存和开发成本选技术;用户明确选定正式界面方案后才能接入新地图页面。可视原型标明模拟数据,不连接设备。等待用户选择的时间不计入人日。
|
||||
|
||||
### P5:正式地图接入(4–7 人日,依赖 P3、P4 选择结果)
|
||||
|
||||
产出:目标、朝向、选择、标签预算、有限轨迹、数据年龄、失联/连接状态和备案关联。
|
||||
|
||||
验收:坐标正确;地图生命周期和资源释放正确;不将“预测”显示为真实新数据;完整异常状态通过。
|
||||
|
||||
### P6:容量、故障与混合负载验收(3–5 人日,依赖 P2、P5)
|
||||
|
||||
产出:稳定档位与首次失败档位、2 小时运行数据、网络故障测试、导出/备份并行影响、优化前后对比。
|
||||
|
||||
验收:达到冻结指标;出现瓶颈时只优化证据指向的阶段。单机无法满足时,再提出分片接收/独立存储/多客户端分区方案及成本,不提前上微服务。
|
||||
|
||||
### P7:发布与交接(1–2 人日,依赖 P6)
|
||||
|
||||
产出:Rust 单 exe 发布包、校验和、依赖许可、容量报告、使用说明、升级与备份恢复步骤。
|
||||
|
||||
验收:第二台 Windows 机器验证、端口与数据目录保护、资源完整性;有设备则做真实联调,没有设备则明确未验收。保留已验证发布包作为程序级回滚,不重新引入 Node 后端。
|
||||
|
||||
首期粗估 **21–37 人日**,按上述阶段串行相加;不含等待 UI 选择、未知协议逆向、三维专题、外部地图授权和采购。仅为排期参考,不是完成日期承诺。先执行 P0/P1 后根据实测重新估算。
|
||||
|
||||
## 10. 实施授权和文档维护
|
||||
|
||||
本轮交付技术审查与计划,未迁移正式前端,未修改接口、数据和运行行为。当前未发现已安装的 Spec Kit 配置;若执行前出现 `.specify` 或项目 constitution,实施必须按其流程重新对齐。
|
||||
|
||||
用户的全局 UI 规则要求“只有用户选定后,才可修改正式界面代码、资源或运行行为”。新地图工作台必须在 P4 提供至少三种有实质差异的可视版本再选;不得将本技术方案的认可以为具体 UI 已获选择。现有页面的纯等价技术迁移若涉及视觉/交互重设计,也进入这一选择门槛。
|
||||
|
||||
下一步建议是 **P0 + P1**:先证明 Rust 前端、Worker、现有后端和单 exe 发布闭环,再迁移全部业务界面。此顺序能尽早暴露最新版本与 Windows 工具链兼容问题。
|
||||
|
||||
## 11. 官方参考与核查边界
|
||||
|
||||
- [Leptos 版本元数据](https://crates.io/api/v1/crates/leptos);[CSR 部署与 Trunk](https://book.leptos.dev/deployment/csr.html);[JavaScript / web-sys 集成](https://book.leptos.dev/web_sys.html)。
|
||||
- [Rust stable manifest](https://static.rust-lang.org/dist/channel-rust-stable.toml);[Trunk 版本](https://crates.io/api/v1/crates/trunk);[Trunk 官方仓库](https://github.com/trunk-rs/trunk)。
|
||||
- [MapLibre 6.15.0](https://github.com/maplibre/maplibre-gl-js/releases/tag/v6.15.0);[大数据指南](https://maplibre.org/maplibre-gl-js/docs/guides/large-data/);[GeoJSONSource.updateData](https://maplibre.org/maplibre-gl-js/docs/API/classes/GeoJSONSource/#updatedata);[自定义图层](https://maplibre.org/maplibre-gl-js/docs/API/interfaces/CustomLayerInterface/)。
|
||||
- [deck.gl 性能指南](https://deck.gl/docs/developer-guide/performance):二进制数据、Worker 与属性更新;官方示例不构成本项目容量承诺。
|
||||
- [WebSocket 背压限制](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket);[Transferable objects](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects);[CSP 与 Wasm](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/script-src#unsafe_webassembly_execution)。
|
||||
- [Tauri 进程模型](https://v2.tauri.app/concept/process-model/);Dioxus/Yew/Cesium 等版本来源见快照。
|
||||
|
||||
证据区分:源码结构与本机硬件为本次只读核查;版本和上述官方文档为联网核查;架构选择为工程建议;所有新架构性能、兼容性、容量及工期均尚待实际实施验证。Trunk 文档站请求被拒绝,已改读官方仓库 README 和 Leptos 官方部署文档;Leptos GitHub latest 请求超时,其版本使用 crates.io 元数据核查。
|
||||
|
||||
## 12. 实施期间的用户确认
|
||||
|
||||
用户已选择 C「目标研判」布局,并确认在线使用天地图、离线时自动切换本地资源;该变化已纳入实际实现。数据来源确认为 RID 接收模块,但具体连接方式、型号和报文格式仍待确认。实际完成与验证边界以实施记录为准,不把本计划全部条目自动视为已验收。
|
||||
@@ -0,0 +1,15 @@
|
||||
# Rust HUD 隔离验证版
|
||||
|
||||
日期:2026-10-21。
|
||||
|
||||
当前 HUD 已由 Rust/Leptos 编译为 Wasm。保留 MapLibre/WebGL 互操作 JavaScript,不需要 Node.js 后端或 Node.js 运行依赖。
|
||||
|
||||
验证版发布目录:`D:/Rust_Contact/Rid_Drone_Receivev/dist/HUD-Rust-Verified-20261021/`。
|
||||
|
||||
源码与完整验证记录:`C:/Users/20143/.codex/worktrees/rust-fullstack-c/Rid_Drone_Receivev/`,记录位于该目录 `doc/realtime/platform/review/implementation-status.md`。该工作目录已附加到当前聊天;保留它以继续维护本版本。
|
||||
|
||||
默认目标研判 C,保留 A/B/C HUD。修复地图切换、接收轮询清理、分页、窄屏和错误状态表达。发布包使用源文件哈希校验,正式测试只访问独立临时数据库。
|
||||
|
||||
原工作目录存在其他写入,后续加入了固定演示目标和状态。本轮没有覆盖这些并发文件,也不把它们视为已验收。隔离版与原目录的最终合并尚未完成。
|
||||
|
||||
10000 个合成目标在 60 秒内接受 10350000 次更新,但请求的每 10ms 一轮没有达到:实际约每秒 17.25 轮。此为同机负载基线,不能替代设备到屏幕时延或两小时稳定性验收。尚缺真实 RID 厂商报文、有效天地图密钥与实际离线瓦片;这些联调仍未完成。
|
||||
@@ -0,0 +1,70 @@
|
||||
# Rust 全栈实施与验收记录
|
||||
|
||||
日期:2026-10-21。状态:实施后的最终集成验证进行中;不把仿真或本机测试当成实机、跨机或设备到屏幕的延迟验收。
|
||||
|
||||
## 用户确认与落地范围
|
||||
|
||||
- 正式实时界面采用用户选择的 C「目标研判」:左侧目标检索,右上地图,右下详情。
|
||||
- 当前接收方式为 USB 串口,后续支持模块主动发送 UDP/TCP 到电脑的监听 IP/端口。
|
||||
- 在线使用天地图资源;在线不可用时读取离线资源。实际在线密钥、离线地图文件、模块型号与厂商报文仍未提供。
|
||||
|
||||
## 已实现
|
||||
|
||||
- Cargo workspace:现有后端、rid-shared、realtime-core、web-ui、web-worker、xtask。
|
||||
- Leptos 0.8.22 CSR/Wasm 登记界面,保留既有布局;登记、分页、搜索、选择、编辑、照片、导出、备份状态、二维码及 PNG 下载逻辑均为 Rust。
|
||||
- 原 `registry/web/app.js` 及其二维码 JavaScript 依赖移除;公共样式和图标迁入 `crates/web-ui/public/`。仅保留地图引擎和必要地图/模块互操作 JavaScript。
|
||||
- 独立实时目标状态与 WebSocket,容量 10000、变更日志 40000、过期 30 秒、最多四个浏览器客户端;每客户端一批未确认数据、超时关闭与快照恢复。
|
||||
- Rust Worker 解码 Postcard、合并状态、转移 TypedArray;主线程提交后确认,避免后台标签页无限积压。目录每组最多 100 个 DOM 目标,可分页和搜索全部目标。
|
||||
- MapLibre 6.15.0 + WebGL2 实例化目标图层;选中标签最多一个,轨迹最多 200 点/30 秒;支持拾取、朝向、过期清理、断线标识与恢复。
|
||||
- 天地图服务端代理,密钥留在服务器环境;在线缓存、XYZ 栅格与 TMS/XYZ MBTiles 自动回退;缺失瓦片明确返回 404。最多四个上游请求、两秒超时、三十秒退避、512 MiB 缓存新增限额。
|
||||
- USB 串口读取、UDP/TCP 监听、接收设置持久化与自动重连;默认禁用、原始格式默认不解析。诊断环形缓冲 4 KiB,状态按需生成最后 64 字节摘要。
|
||||
- JSON Lines、约定 Postcard 解码,TCP/串口二进制长度边界、TCP 最多八个连接与空闲超时;切换配置释放旧任务。未知厂商格式只诊断,不伪造目标。
|
||||
- 备案数据库工作队列由无界改为 64 项;静态资源与实时路由不再排队进入数据库线程;服务退出显式发送工作线程停止消息。
|
||||
- `cargo xtask package` 统一前端/Worker/原生 Release 构建,资源内嵌;CSP、Wasm/MJS MIME、外部化初始化脚本已适配。
|
||||
- 构建互斥、运行数据目录保护、临时打包、七文件白名单、许可清单、源码哈希和工具版本记录、文件与 ZIP 校验和。
|
||||
|
||||
## 已取得的测试证据
|
||||
|
||||
- Rust 单元与网络集成测试目前共 22 项通过;包括原备案九项、实时快照/增量/确认超时/来源/客户端上限、状态去重/容量/过期、Worker 会话、离线与在线失败回退、USB 式分片、UDP/TCP 以及原始模式不生成目标。
|
||||
- Native 与 Wasm 严格 Clippy、格式检查通过;后续最终构建仍需保持通过。
|
||||
- 实际 Chrome 的原登记流程、原子编辑、错误图片回滚、分页、搜索、Excel、窄屏和页面异常检查通过。
|
||||
- 分页测试改为直接驱动 Rust/Wasm 页面,验证失败保留页码、成功提交页码、旧响应不能覆盖新搜索;不再测试复制的 JavaScript 函数。
|
||||
- JSON 入口短时验证:1000 与 10000 模拟目标。10000 目标一轮 15 秒接受 1500000 次更新;这是合成负载,不是每目标毫秒级或端到端时延保证。
|
||||
- Postcard 入口短时验证:1000 目标,请求间隔 10 ms,30 秒接受 2889000 次更新,生成器执行 2889 轮;请求周期不等于设备真实采样周期。
|
||||
- Chrome 检测到实际使用 ANGLE / NVIDIA RTX 3070 Laptop / D3D11;绘制提交间隔指标不是 GPU 渲染耗时或屏幕实际刷新率。
|
||||
- 该 30 秒样本的后端私有内存约 8.8–9.4 MB,页面 JS 堆约 7.7–12.6 MB;短时样本不能替代长期稳定性测试,也不包含浏览器全部进程/驱动内存。
|
||||
- 独立核心状态基准曾处理 10000 目标、1000000 次更新,用时约 0.665 秒;只测内存状态 apply,不含接收、网络、Worker 或地图,不作为系统吞吐宣称。
|
||||
- 独立进程离线地图测试读取真实 PNG 测试瓦片和 SQLite MBTiles,核对字节、TMS 行号、来源限制、边界和缺失状态。
|
||||
- 包装保护测试通过:已用目录拒绝且数据不变,干净目录重复打包,旧 ZIP 在拒绝时不变,清理仅限本次暂存。
|
||||
|
||||
## 证据路径(本机临时测试数据)
|
||||
|
||||
- 原登记浏览器:`C:/Users/20143/AppData/Local/Temp/RID-浏览器验收-Apy4aA/`。
|
||||
- 分页:`C:/Users/20143/AppData/Local/Temp/RID-pagination-xGooPs/`。
|
||||
- JSON 10000:`C:/Users/20143/AppData/Local/Temp/RID-realtime-vKKln6/`。
|
||||
- Postcard 1000 / 30 秒:`C:/Users/20143/AppData/Local/Temp/RID-realtime-IQygif/`。
|
||||
- 离线地图:`C:/Users/20143/AppData/Local/Temp/RID-maps-m2VPto/`。
|
||||
- API/备份:`C:/Users/20143/AppData/Local/Temp/RID-中文验证-DUBaQc/`。
|
||||
- 包装保护:`C:/Users/20143/AppData/Local/Temp/RID-package-review-f594297d0a444ff6bdf7c36a4f3dc002/`。
|
||||
|
||||
## 最终仍需补齐或确认的边界
|
||||
|
||||
- 新增串口与地图配置界面的最终 Release 进程/浏览器复验、长期持续负载和最终包一致性正在执行;结果在本记录后续更新。
|
||||
- 真实接收模块尚缺型号/输出报文。传输已实现,厂商解码及真实目标身份到备案 SN 的映射不能凭空完成。使用原始诊断取得样例后再适配。
|
||||
- 未取得有效天地图密钥,也没有用户真实离线地图文件;线上授权、实际区域覆盖和真实断网切换仍需使用这些资源验收。本机模拟上游测试不替代它们。
|
||||
- 无第二台 Windows 机器、真实模块或独立网络发包设备的验收;没有设备时钟同步证据,因此未给出设备采样到屏幕的 p95/p99 延迟结论。
|
||||
- 标准合同接收与渲染不等于多基站定位融合或硬实时系统;可靠告警、全量历史留存、三维专题及超出当前上限的容量需按后续真实需求建设。
|
||||
|
||||
## 修复与保留项
|
||||
|
||||
- 人工查看截图发现 MapLibre CSS 覆盖地图容器定位,已修复并增加实际画布尺寸验收;不能只检查目标计数。
|
||||
- 修复 PowerShell 子进程继承模块路径造成打包 Get-FileHash 不可用的问题。
|
||||
- 仿真器改为复用 HTTP 连接,避免高频新建连接耗尽本机临时端口。
|
||||
- 检测到外部旧实例占用原构建 exe,未中断它;开发产物使用独立 `fpv-rid-registry-fullstack.exe`,发布包内仍为 `fpv-rid-registry.exe`。更新同一数据目录前需关闭旧实例。
|
||||
- 验收脚本原先在环境变量未刷新时触发用户目录工具链安装,已移除 API 验收中的 Cargo 调用,构建统一加载集中环境。意外生成的 `C:/Users/20143/.rustup` 清理被自动审批审查以 `blocked by policy` 拒绝,未绕过、未宣称已清理;该目录不参与集中构建。
|
||||
|
||||
本轮未提交或推送;验收只使用独立临时数据目录,未向正式备案库写入测试记录。
|
||||
|
||||
## 并发工作阻碍最终集成
|
||||
|
||||
最终打包时检测到实时界面与样式被另一处工作改成 mc/HUD 布局;当前出现未闭合字符串等 Rust 编译错误,原先的 .rt-* 验收选择器也不再对应。已向用户请求确认保留本次 C 方案还是当前 HUD 改动,未回滚或覆盖并发工作。后端测试继续推进,最终发布与浏览器验收等待界面版本稳定。构建流程增加前后源码哈希核对,避免构建中变化的源码被误记为已发布版本。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 运行
|
||||
|
||||
Windows x64 发布目录中双击 `启动Rust版.cmd`,保持窗口打开,使用浏览器访问 http://127.0.0.1:8787/ 。不需要 Node.js;不包含无线 RID 接收或设备上位机。
|
||||
Windows x64 发布目录中双击 `启动Rust版.cmd`,保持窗口打开,使用浏览器访问 http://127.0.0.1:8787/ 。不需要 Node.js;包含 USB/UDP/TCP 接收传输层;厂商 RID 解析需协议适配,不包含原版设备写入上位机。
|
||||
|
||||
默认数据目录是 exe 所在目录,不是命令行当前目录。目录必须可写,不要放在 Program Files。数据库仍为 `registry/data/registry.sqlite`,自动档案仍在 `档案库/`。高级用法:`fpv-rid-registry.exe --data-root "D:\我的备案"`。
|
||||
|
||||
@@ -39,10 +39,26 @@ Windows x64 发布目录中双击 `启动Rust版.cmd`,保持窗口打开,使
|
||||
|
||||
仓库 `.cargo/config.toml` 固定本机构建缓存目录,发布脚本通过 Cargo metadata 获取产物位置。发布包仍生成到仓库 `dist/`,业务数据库不放在 util。更换开发机器时调整该本机路径配置。共享 Node.js、Visual Studio 和 Windows SDK 不属于此次清理范围。
|
||||
|
||||
安装 Rust stable MSVC 及 Visual Studio C++ Build Tools 后,运行 `cargo run -- --data-root .`。检查:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`。Release:`cargo build --release --locked`。
|
||||
安装 Rust stable MSVC 及 Visual Studio C++ Build Tools 后,先运行 `cargo xtask web`,再运行 `cargo run -p fpv-rid-registry -- --data-root .`。检查:`cargo fmt --check`、`cargo clippy --all-targets -- -D warnings`、`cargo test`。完整发布:`cargo xtask package`。
|
||||
|
||||
本仓库将稳定工具链固定为 1.99.1。已有终端若未刷新环境,可先在 PowerShell 执行 `. ./scripts/rust-env.ps1`。Rust 编译依赖保存在 util/cargo/registry;Windows SDK、Visual Studio 等共享组件保留在原安装目录。
|
||||
|
||||
`scripts/package.ps1` 通过独立暂存目录及六文件白名单,生成 `dist/FPV-RID-Rust/`、Windows ZIP 和两份 SHA-256 清单,不打包备案数据。若已有发布目录含数据库、档案或其他非发布文件,脚本会停止并保留原内容及旧 ZIP;请使用 `./scripts/package.ps1 -OutputRoot "D:\单独发布目录"` 指定干净输出目录。禁止把正在使用的数据目录作为打包暂存目录。
|
||||
|
||||
`node scripts/verify.mjs` 在独立临时目录执行 Rust Release 版接口、导出、重启和旧数据导入验收;Node.js 仅作为开发测试工具;`powershell -ExecutionPolicy Bypass -File scripts/test-package.ps1` 验证重复打包、运行数据隔离及校验和。临时验收目录保留作为证据,不触及正式数据。
|
||||
|
||||
## Rust 前端与实时目标
|
||||
|
||||
当前登记交互和二维码生成均由 Rust/Wasm 实现,原 JavaScript 业务文件已移除。地图引擎仍包含固定版本的第三方 JavaScript,少量模块加载和地图互操作代码用于接入浏览器。
|
||||
|
||||
从登记页进入“实时目标研判”,或访问 `/realtime`。采用已选择的 C 布局,显示目标目录、地图、GPU 目标图层与选中目标详情。在线优先使用天地图,失败后自动读取本地离线资源。轨迹只保留当前选择目标最近 30 秒、最多 200 点;标签最多一个。请在启动环境配置 TIANDITU_TOKEN,并将实际离线资源放入 exe 旁 maps/offline/。支持 vec_w、cva_w 的 XYZ 栅格目录或同名 MBTiles(默认 TMS 行号)。没有数据覆盖时会提示缺失,网格不等于街道或卫星底图。
|
||||
|
||||
首次启动默认不启用设备接收、不生成模拟数据;已保存为启用的接收配置会在后续启动自动重连。合成输入仅在 `--simulation-api` 模式开启,目标状态只在内存保存,30 秒未更新自动过期。不得把隔离测试结果当成真实 RID 接收或设备到屏幕的延迟验收。
|
||||
|
||||
开发构建另需 Trunk 0.22.0、wasm-bindgen CLI 0.2.129。Windows PowerShell 子进程通过清理继承的 PSModulePath 避免不同 PowerShell 版本模块路径冲突。前端、Worker 和后端统一发布不依赖 Node.js 构建;浏览器验收脚本仍使用 Node/Playwright。
|
||||
|
||||
## USB 与网络接收
|
||||
|
||||
在实时目标页展开“电脑接收设置”,当前 USB 请选择真实 COM 号与设备要求的波特率,未知厂商格式先用原始诊断。可以复制最近 4 KiB 字节用于协议适配。串口打开或端口监听成功不代表已解码出真实 RID 位置。
|
||||
|
||||
UDP/TCP 为电脑监听模式:填写电脑本机 IP 和接收端口,再用模块工具把目标地址设置为这台电脑。程序不自动写入未知厂商的模块配置命令。配置保存在数据目录 receiver-config.json,禁用会释放监听与串口。
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
# FPV-RID 本地登记与验证
|
||||
|
||||
## 打开
|
||||
|
||||
双击 `启动本地登记站.cmd`,在同一台电脑打开 `http://127.0.0.1:8787/`。双击 `打开FPV-RID上位机.cmd` 可启动新版上位机(程序位于 `host/FPV-RID-本地FPV版.exe`)。两个程序须在同一台电脑运行。
|
||||
|
||||
## 登记与绑定
|
||||
|
||||
输入模块 SN,可填写机型、登记人、两张照片和 FPV 编号的后 8 位数字。留空时自动生成 `FPV` 加 8 位数字。二维码指向本机档案卡;上位机从本地网站读取记录、比对模块 SN,然后通过 `$WRITE_UOM:FPVxxxxxxxx` 将完整 FPV 编号写入模块。已有 UOM 绑定的模块可能拒绝再次写入,此时需按设备原有流程处理绑定状态。
|
||||
|
||||
## 档案与导出
|
||||
|
||||
- 网站数据库:`registry/data/registry.sqlite`。
|
||||
- 自动档案库:`档案库/`。每条登记都有内含照片的离线 HTML 档案卡,另有 `记录索引.json` 和数据库最新、上一次备份。
|
||||
- 勾选单条或使用“全选”,可导出 ZIP 档案包(离线档案卡、照片原件、JSON 索引)或 Excel `.xlsx` 登记表。Excel 登记表列出照片有无;照片原件在 ZIP 档案包中。
|
||||
- 记录区可按模块 SN、FPV 编号、机型或登记人搜索;“全选”只选中当前搜索结果。
|
||||
- 每张档案卡有“删除档案”。删除后记录及照片从网站数据库和自动档案库移除。导出到电脑其他位置的文件不会自动删除。
|
||||
|
||||
本地生成的编号与二维码用于本机登记和模块操作;官方登记状态需以官方系统为准。
|
||||
|
||||
更新程序时请保留现有的 `registry/data/registry.sqlite` 和 `档案库/`,不要用新压缩包里的空数据库覆盖已有档案。
|
||||
@@ -1,43 +0,0 @@
|
||||
# 本地接口清单(Rust 版本)
|
||||
|
||||
服务地址:`http://127.0.0.1:8787`。以下是现有功能,均由 Rust 后端 `src/http.rs` 提供。
|
||||
|
||||
| 方法和路径 | 用途 |
|
||||
| --- | --- |
|
||||
| `GET /api/records?q=关键词` | 列出/搜索备案;结果为 `{ "records": [...] }` |
|
||||
| `GET /api/records?q=关键词&page=1&pageSize=20` | 分页搜索,返回记录、当前页、每页数量、总条数和总页数 |
|
||||
| `POST /api/records` | 新增或更新登记及照片 |
|
||||
| `PATCH /api/records/:id` | 在同一事务中编辑机型、登记人与照片 |
|
||||
| `DELETE /api/records/:id` | 删除记录和照片,并同步档案库 |
|
||||
| `GET /api/records/:id/photos/1` | 第一张照片;`2` 是第二张 |
|
||||
| `DELETE /api/records/:id/photos/1` | 删除指定照片;`2` 是第二张 |
|
||||
| `GET /api/records/:id/archive` | 下载单条离线 HTML 档案卡 |
|
||||
| `POST /api/export/archive` | 按 `ids` 数组导出 ZIP |
|
||||
| `POST /api/export/excel` | 按 `ids` 数组导出 Excel |
|
||||
| `GET /api/resolve?url=二维码内容` | 解析本机生成的登记二维码 |
|
||||
| `GET /api/archive/status` | 查询档案备份同步状态 |
|
||||
| `POST /api/archive/retry` | 重试生成档案卡、索引和数据库备份 |
|
||||
| `GET /r/:id` | 查看档案卡网页 |
|
||||
|
||||
分页、编辑字段语义、同步状态和错误码详见 [Rust 接口补充](../doc/registry/rust/接口变更.md)。
|
||||
|
||||
一条记录的主要返回字段:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "示意:36位十六进制档案ID",
|
||||
"serialNo": "示意模块SN",
|
||||
"uasCode": "FPV12345678",
|
||||
"modelName": "示意机型",
|
||||
"ownerName": "示意登记人",
|
||||
"createdAt": "ISO时间",
|
||||
"source": "local-fpv-registry",
|
||||
"qrUrl": "http://127.0.0.1:8787/r/档案ID",
|
||||
"archiveUrl": "/r/档案ID",
|
||||
"downloadArchiveUrl": "/api/records/档案ID/archive",
|
||||
"photo1Url": null,
|
||||
"photo2Url": null
|
||||
}
|
||||
```
|
||||
|
||||
以上为字段示意,不是实际备案数据。接口无账号认证,只监听本机;局域网共享前需要单独设计身份验证与授权。`GET /api/records` 包含登记人字段,因此平台同步时应限制调用端和前端展示范围。
|
||||
@@ -1,47 +0,0 @@
|
||||
# 源码结构与 RID 平台联动
|
||||
|
||||
## 现有数据怎么走
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[用户在本机网页登记] --> B[src/http.rs / Axum]
|
||||
B --> C[src/store.rs / SQLite]
|
||||
C --> D[档案库 / 离线档案卡和备份]
|
||||
B --> E[网页二维码]
|
||||
E --> F[本地版上位机]
|
||||
F --> G[核对模块 SN 并写入 FPV 编号]
|
||||
```
|
||||
|
||||
这份源码只负责**备案**。地图上的无人机位置、飞手位置、航线和基站状态,仍来自你规划的 RID 基站采集链路,不来自备案库。
|
||||
|
||||
## 数据表(现有代码)
|
||||
|
||||
`registry/data/registry.sqlite` 中有两张业务表和一张内部元数据表:
|
||||
|
||||
| 表 | 主要字段 | 白话解释 |
|
||||
| --- | --- | --- |
|
||||
| `records` | `id`, `serial_no`, `uas_code`, `model_name`, `owner_name`, `created_at` | 一台模块对应一条备案;SN 和 FPV 编号都不能重复 |
|
||||
| `photos` | `record_id`, `slot`, `mime_type`, `image` | 每条备案最多两张照片,照片二进制保存在数据库中 |
|
||||
| `registry_meta` | `key`, `value` | 保存旧数据导入标记及档案备份待同步状态 |
|
||||
|
||||
网页接口把字段转换成驼峰命名,例如 `serial_no` 变为 `serialNo`,`uas_code` 变为 `uasCode`。`ownerName` 目前兼作“登记人 / 备注”,以后若要区分真实飞手和备注,应新增独立字段,不要直接推断两者相同。
|
||||
|
||||
## 与 RID 实时报文怎么比对
|
||||
|
||||
RID 报文示例中的 `serial` 可作为候选匹配字段;备案库用 `serialNo` 保存模块 SN。**只有确认基站报送的 `serial` 与备案时填的模块 SN 是同一编号**,才可直接按完全相等匹配。若设备上报的是其他序列号,应建立编号映射表。`uasCode` 是本地 FPV 编号,亦可作为经过核实的辅助匹配键。
|
||||
|
||||
建议平台显示三种结果:
|
||||
|
||||
- **已匹配备案**:同一编号找到一条本地备案,可显示机型、FPV 编号、登记人。
|
||||
- **未匹配备案**:当前库里找不到对应编号;这只说明没有匹配到,不能直接认定违规。
|
||||
- **编号待核实**:RID 上报编号与模块 SN 的对应关系尚未确认,避免误关联。
|
||||
|
||||
同一架无人机可能被多个基站同时接收。平台先对基站报文去重、融合,再拿目标编号查询备案;备案库本身无需处理多基站合并。
|
||||
|
||||
## 最容易落地的对接方式
|
||||
|
||||
**登记站与 RID 平台后端在同一台电脑时:** 平台后端读取 `http://127.0.0.1:8787/api/records`,按 `serialNo` 建立备案索引;或读取自动生成的 `档案库/记录索引.json`。只同步文字字段即可,地图不需要原始照片。
|
||||
|
||||
**分开电脑时:** 在登记站电脑定期导出或同步上述索引,由 RID 平台后端接收。不要把二维码里的 `127.0.0.1` 当作跨电脑地址;它始终指向打开链接的那台电脑。
|
||||
|
||||
平台后端保存一份备案索引缓存后,前端只显示业务结论和必要字段。涉及 `ownerName`、照片等个人信息时,应按账号权限控制可见范围。
|
||||
Binary file not shown.
@@ -0,0 +1,105 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mission Control · 实时态势工作台原型</title><style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:#070e1a;background-image:radial-gradient(circle at 50% 0%,rgba(32,65,199,0.25) 0%,transparent 60%),radial-gradient(circle at 85% 90%,rgba(16,185,129,0.08) 0%,transparent 50%);color:#f8fafc;font:14px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC",sans-serif;min-height:100vh}
|
||||
header{padding:14px 24px;background:rgba(10,18,32,0.85);backdrop-filter:blur(20px);border-bottom:1px solid rgba(64,150,255,0.22);display:flex;align-items:center;justify-content:space-between;box-shadow:0 4px 20px rgba(0,0,0,0.4)}
|
||||
.brand{display:flex;align-items:center;gap:12px}
|
||||
.brand-icon{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,rgba(32,65,199,0.7),rgba(48,182,245,0.4));border:1px solid rgba(48,182,245,0.45);display:grid;place-items:center;color:#fff;font-size:18px;box-shadow:0 0 12px rgba(48,182,245,0.3)}
|
||||
header b{font-size:16px;color:#fff;letter-spacing:.03em}
|
||||
header small{color:#30b6f5;font-size:12px;margin-left:8px}
|
||||
nav{display:flex;gap:8px;padding:12px 24px;background:rgba(6,12,22,0.4);border-bottom:1px solid rgba(255,255,255,0.06)}
|
||||
nav button{cursor:pointer;color:#94a3b8;background:transparent;border:1px solid transparent;padding:7px 16px;border-radius:9999px;font-size:13px;font-weight:600;transition:all .2s ease}
|
||||
nav button:hover{color:#fff;background:rgba(255,255,255,0.06)}
|
||||
nav button.active{background:linear-gradient(135deg,rgba(32,65,199,0.8),rgba(48,182,245,0.45));color:#fff;border-color:#30b6f5;box-shadow:0 0 14px rgba(48,182,245,0.3)}
|
||||
.description{padding:10px 24px;color:#94a3b8;font-size:12px}
|
||||
.workspace{height:calc(100vh - 165px);min-height:540px;margin:0 24px 20px;display:grid;grid-template-columns:260px 1fr 300px;gap:14px}
|
||||
.pane{background:rgba(11,22,39,0.76);backdrop-filter:blur(24px) saturate(180%);border:1px solid rgba(64,150,255,0.22);border-radius:14px;padding:18px;overflow:auto;box-shadow:0 14px 40px rgba(0,0,0,0.5),inset 0 1px 1px rgba(255,255,255,0.15)}
|
||||
.pane h2{font-size:15px;margin:0 0 14px;color:#fff;border-bottom:1px solid rgba(255,255,255,0.08);padding-bottom:10px}
|
||||
.muted{color:#64748b;font-size:12px}
|
||||
article{padding:12px 0;border-bottom:1px solid rgba(255,255,255,0.06);line-height:1.7;font-size:12px;color:#cbd5e1}
|
||||
article strong{color:#30b6f5}
|
||||
.map{position:relative;background:#091220;overflow:hidden;padding:0;border:1px solid rgba(64,150,255,0.22);border-radius:14px;box-shadow:0 14px 40px rgba(0,0,0,0.5)}
|
||||
.map svg{width:100%;height:100%;display:block}
|
||||
.badge{position:absolute;top:16px;left:16px;padding:6px 14px;background:rgba(10,18,32,0.85);backdrop-filter:blur(10px);border:1px solid rgba(64,150,255,0.3);border-radius:9999px;font-size:11px;color:#30b6f5}
|
||||
.bar{position:absolute;bottom:16px;left:16px;right:16px;background:rgba(10,18,32,0.85);backdrop-filter:blur(10px);border:1px solid rgba(64,150,255,0.22);border-radius:9999px;padding:8px 18px;display:flex;justify-content:space-between;font-size:12px;color:#94a3b8}
|
||||
.feed{display:none}
|
||||
.workspace.b{grid-template-columns:1fr 320px;grid-template-rows:1fr 180px}
|
||||
.b .filters{display:none}
|
||||
.b .map{grid-row:1;grid-column:1}
|
||||
.b .details{grid-column:2;grid-row:1 / 3}
|
||||
.b .feed{display:block;grid-row:2;grid-column:1}
|
||||
.workspace.c{grid-template-columns:360px 1fr;grid-template-rows:1fr 200px}
|
||||
.c .filters{grid-column:1;grid-row:1 / 3}
|
||||
.c .details{grid-column:2;grid-row:2}
|
||||
.c .details article{display:inline-block;width:31%;vertical-align:top;margin-right:2%}
|
||||
.c .details h2{margin-bottom:6px}
|
||||
@media(max-width:850px){.workspace,.workspace.b,.workspace.c{height:auto;display:flex;flex-direction:column}.map{height:420px}.pane{min-height:140px}}
|
||||
</style>
|
||||
<header>
|
||||
<div class="brand">
|
||||
<div class="brand-icon">⌘</div>
|
||||
<div><b>任务指挥 MISSION CONTROL</b><small>实时态势感知与研判</small></div>
|
||||
</div>
|
||||
<div class="badge" style="position:static;">● Apple 风格半透明色调</div>
|
||||
</header>
|
||||
<nav>
|
||||
<button data-v="a" class="active">A · 地图监控 (HUD 浮窗)</button>
|
||||
<button data-v="b">B · 调度指挥 (底部指令坞)</button>
|
||||
<button data-v="c">C · 目标研判 (宽侧栏检索)</button>
|
||||
</nav>
|
||||
<div class="description" id="description"></div>
|
||||
<main class="workspace a" id="workspace">
|
||||
<aside class="pane filters">
|
||||
<h2 id="left-title">监控范围</h2>
|
||||
<article>视域<br><strong>全部在线目标 · 实时渲染</strong></article>
|
||||
<article>状态筛选<br>已备案匹配 · 实时在线 · 待核验</article>
|
||||
<article>目标列表<br>DEMO-001 正常跟踪<br>DEMO-002 待核查 SN<br>DEMO-003 正常跟踪</article>
|
||||
<article class="muted">支持十万级目标硬件实例化渲染<br>点选高亮显示航迹与姿态指针</article>
|
||||
</aside>
|
||||
<section class="map">
|
||||
<div class="badge">天地图影像 / 坐标网格</div>
|
||||
<svg viewBox="0 0 900 650">
|
||||
<defs><pattern id="grid" width="60" height="60" patternUnits="userSpaceOnUse"><path d="M60 0H0V60" fill="none" stroke="rgba(64,150,255,0.12)" stroke-width="1"/></pattern></defs>
|
||||
<rect width="900" height="650" fill="url(#grid)"/>
|
||||
<path d="M0 530Q250 280 480 460T900 190" fill="none" stroke="rgba(32,65,199,0.3)" stroke-width="60"/>
|
||||
<path d="M70 80L800 560M20 270L870 410M330 0L500 650" fill="none" stroke="rgba(255,255,255,0.06)" stroke-width="3"/>
|
||||
<path d="M180 430L270 350L380 330L480 260L570 190" fill="none" stroke="#30b6f5" stroke-width="2.5" stroke-dasharray="6 4"/>
|
||||
<g fill="#30b6f5" stroke="#070e1a" stroke-width="2">
|
||||
<path d="M570 176l11 29-11-6-11 6z"/>
|
||||
<path d="M350 145l11 29-11-6-11 6z"/>
|
||||
<path d="M690 420l11 29-11-6-11 6z"/>
|
||||
<path d="M230 500l11 29-11-6-11 6z"/>
|
||||
</g>
|
||||
<circle cx="570" cy="190" r="32" fill="none" stroke="#30b6f5" stroke-width="1.5"/>
|
||||
<text x="612" y="186" fill="#f8fafc" font-size="16" font-weight="700">DEMO-001</text>
|
||||
<g fill="#ff9f0a"><path d="M730 210l11 29-11-6-11 6z"/></g>
|
||||
</svg>
|
||||
<div class="bar"><span>数据通道:已连接 120 FPS</span><span>平均数据延迟:18 ms</span></div>
|
||||
</section>
|
||||
<aside class="pane details">
|
||||
<h2>选中目标 · DEMO-001</h2>
|
||||
<article>身份与备案<br><strong>已匹配本地备案 (FPV00000001)</strong><br>机型:5寸穿越机 · 飞手:演示登记人</article>
|
||||
<article>空间遥测 (WGS84)<br>经度:120.123456 · 纬度:30.123456<br>椭球高:125.4 m · 航向:302.5°</article>
|
||||
<article>时效与告警<br>报文年龄:24 ms · 接收链路:USB 串口<br>告警级别:正常无冲突</article>
|
||||
</aside>
|
||||
<section class="pane feed">
|
||||
<h2>事件时间轴 · 实时态势</h2>
|
||||
<div style="font-size:13px;color:#e2e8f0;padding:6px 0;">[00:12] 捕获新目标 DEMO-001 ─── [00:14] 自动匹配备案库 ─── [00:18] 态势航迹已就绪</div>
|
||||
<p class="muted">突出关键调度决策与事件告警;符合 Mission Control 苹果半透明控制中心风格。</p>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const descriptions={
|
||||
a:'A 地图监控:左右悬浮毛玻璃 HUD,中心地图广阔通透。适合日常全域态势监视。',
|
||||
b:'B 调度指挥:上方大屏地图 + 下方任务指挥 HUD 仪表坞。突出实时参数、姿态角与事件流。',
|
||||
c:'C 目标研判:左侧高密度目录检索,右上方地图与右下方综合研判档案卡。适合目标身份细致比对。'
|
||||
};
|
||||
function choose(v){
|
||||
document.querySelector('#workspace').className='workspace '+v;
|
||||
document.querySelector('#description').textContent=descriptions[v];
|
||||
document.querySelector('#left-title').textContent=v==='c'?'目标目录与检索':'监控范围';
|
||||
document.querySelectorAll('nav button').forEach(b=>b.classList.toggle('active',b.dataset.v===v))
|
||||
}
|
||||
document.querySelectorAll('nav button').forEach(b=>b.onclick=()=>choose(b.dataset.v));
|
||||
choose('a')
|
||||
</script>
|
||||
</html>
|
||||
@@ -0,0 +1,787 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>RID 无人机远程识别态势与研判平台 · 苹果半透明风格原型</title>
|
||||
<style>
|
||||
:root {
|
||||
--mc-bg: #060b14;
|
||||
--mc-panel-bg: rgba(9, 18, 36, 0.82);
|
||||
--mc-panel-card: rgba(14, 25, 48, 0.65);
|
||||
--mc-panel-card-hover: rgba(18, 34, 64, 0.8);
|
||||
--mc-panel-card-active: rgba(18, 42, 82, 0.9);
|
||||
--mc-border: rgba(48, 85, 140, 0.38);
|
||||
--mc-border-light: rgba(255, 255, 255, 0.1);
|
||||
--mc-accent: #38bdf8;
|
||||
--mc-accent-blue: #0a84ff;
|
||||
--mc-success: #30d158;
|
||||
--mc-warning: #ff9f0a;
|
||||
--mc-danger: #ff453a;
|
||||
--mc-text: #f8fafc;
|
||||
--mc-text-muted: #94a3b8;
|
||||
--mc-text-dim: #64748b;
|
||||
--mc-radius-lg: 14px;
|
||||
--mc-radius-md: 10px;
|
||||
--mc-radius-sm: 8px;
|
||||
--mc-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", sans-serif;
|
||||
color-scheme: dark;
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--mc-bg);
|
||||
color: var(--mc-text);
|
||||
font-size: 13px;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Topbar */
|
||||
.topbar {
|
||||
height: 56px;
|
||||
background: rgba(8, 15, 28, 0.88);
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
||||
border-bottom: 1px solid var(--mc-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 20px;
|
||||
z-index: 100;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.4);
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.brand-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, rgba(10,132,255,0.7), rgba(56,189,248,0.35));
|
||||
border: 1px solid rgba(56,189,248,0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #38bdf8;
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.brand-title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.brand-sub {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
/* Nav Tabs */
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
.nav-tab {
|
||||
height: 100%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 18px;
|
||||
background: transparent;
|
||||
color: var(--mc-text-muted);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.nav-tab:hover {
|
||||
color: #fff;
|
||||
background: rgba(255,255,255,0.04);
|
||||
}
|
||||
.nav-tab.active {
|
||||
color: #38bdf8;
|
||||
border-bottom-color: #38bdf8;
|
||||
text-shadow: 0 0 10px rgba(56,189,248,0.4);
|
||||
}
|
||||
.top-capsule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
background: rgba(14, 25, 45, 0.75);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
border-radius: 9999px;
|
||||
padding: 6px 14px;
|
||||
font-size: 11px;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.pulse-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.pulse-dot.green { background: var(--mc-success); box-shadow: 0 0 8px var(--mc-success); }
|
||||
.pulse-dot.amber { background: var(--mc-warning); box-shadow: 0 0 8px var(--mc-warning); }
|
||||
|
||||
/* Workspace */
|
||||
.workspace {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.layout {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: none;
|
||||
}
|
||||
.layout.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Common Glass Card */
|
||||
.glass-panel {
|
||||
background: var(--mc-panel-bg);
|
||||
backdrop-filter: blur(28px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(190%);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
box-shadow: var(--mc-shadow);
|
||||
z-index: 10;
|
||||
}
|
||||
.panel-header {
|
||||
padding: 14px 16px 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
.panel-header h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tag {
|
||||
font-size: 10px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.tag-blue { background: rgba(56,189,248,0.2); color: #38bdf8; border: 1px solid rgba(56,189,248,0.4); }
|
||||
.tag-green { background: rgba(48,209,88,0.2); color: #4ade80; border: 1px solid rgba(48,209,88,0.4); }
|
||||
.tag-amber { background: rgba(255,159,10,0.2); color: #fbbf24; border: 1px solid rgba(255,159,10,0.4); }
|
||||
.tag-red { background: rgba(255,69,58,0.2); color: #f87171; border: 1px solid rgba(255,69,58,0.4); }
|
||||
|
||||
/* Map canvas & overlays */
|
||||
.map-container {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #060b14 radial-gradient(circle at 50% 50%, rgba(20,40,75,0.3) 0%, transparent 75%);
|
||||
}
|
||||
.map-canvas-svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Target item in list */
|
||||
.target-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.target-card:hover {
|
||||
background: var(--mc-panel-card-hover);
|
||||
border-color: rgba(56, 140, 248, 0.45);
|
||||
}
|
||||
.target-card.active {
|
||||
background: var(--mc-panel-card-active);
|
||||
border-color: #1a72ff;
|
||||
box-shadow: 0 4px 16px rgba(26,114,255,0.3), inset 0 1px 0 rgba(255,255,255,0.15);
|
||||
}
|
||||
.tc-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.tc-title {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tc-sub {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
/* Mode A Specific */
|
||||
.mode-a-left {
|
||||
position: absolute;
|
||||
left: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.mode-a-right {
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 360px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.map-toolstrip {
|
||||
position: absolute;
|
||||
left: 352px;
|
||||
top: 16px;
|
||||
background: rgba(9, 18, 36, 0.85);
|
||||
backdrop-filter: blur(24px);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: 10px;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
z-index: 20;
|
||||
}
|
||||
.ts-btn {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.ts-btn:hover { background: rgba(255,255,255,0.08); color: #fff; }
|
||||
.ts-btn.active { background: rgba(26,114,255,0.25); color: #38bdf8; }
|
||||
.alert-bar {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
left: 410px;
|
||||
right: 396px;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
height: 36px;
|
||||
background: rgba(30,22,10,0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(245,158,11,0.6);
|
||||
border-radius: 8px;
|
||||
padding: 0 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 12px;
|
||||
color: #fbbf24;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
/* Mode B Specific (Dispatch & Timeline) */
|
||||
.mode-b-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
.mode-b-top {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
}
|
||||
.mode-b-dock {
|
||||
height: 240px;
|
||||
background: rgba(8, 15, 28, 0.92);
|
||||
backdrop-filter: blur(28px);
|
||||
border-top: 1px solid var(--mc-border);
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 340px;
|
||||
z-index: 10;
|
||||
}
|
||||
.timeline-pane {
|
||||
padding: 14px 18px;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid var(--mc-border);
|
||||
}
|
||||
.timeline-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: rgba(14,25,48,0.5);
|
||||
border: 1px solid rgba(38,68,115,0.3);
|
||||
border-radius: 6px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.t-time { color: var(--mc-text-dim); font-size: 11px; min-width: 55px; }
|
||||
.t-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; font-weight: 700; }
|
||||
.t-desc { flex: 1; color: #cbd5e1; }
|
||||
|
||||
/* Mode C Specific (Forensics & Deep Analysis) */
|
||||
.mode-c-wrap {
|
||||
display: grid;
|
||||
grid-template-columns: 340px 1fr 380px;
|
||||
height: 100%;
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
}
|
||||
.c-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Dossier Info Blocks */
|
||||
.dossier-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.dossier-label {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.dossier-val {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: #e2e8f0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.btn-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(180deg, #1d68cf 0%, #1557b0 100%);
|
||||
border: 1px solid rgba(147,197,253,0.35);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: rgba(255,255,255,0.08);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
/* Choice Gate Banner */
|
||||
.gate-banner {
|
||||
background: rgba(14, 25, 48, 0.9);
|
||||
border-bottom: 1px solid rgba(56, 189, 248, 0.3);
|
||||
padding: 8px 20px;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.gate-banner strong { color: #38bdf8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Topbar -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<div class="brand-icon">📡</div>
|
||||
<div>
|
||||
<div class="brand-title">RID / 实时目标工作台</div>
|
||||
<div class="brand-sub">REMOTE ID SURVEILLANCE & REGULATORY FORENSICS</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mode Selectors -->
|
||||
<nav class="nav-tabs">
|
||||
<button class="nav-tab" onclick="switchMode('a', this)">A · 地图监控 (日常全域监视)</button>
|
||||
<button class="nav-tab active" onclick="switchMode('b', this)">B · 调度指挥 (事件时间轴响应)</button>
|
||||
<button class="nav-tab" onclick="switchMode('c', this)">C · 目标研判 (档案核验与取证)</button>
|
||||
</nav>
|
||||
|
||||
<div class="top-capsule">
|
||||
<span><span class="pulse-dot green"></span> 接收机: USB串口 (COM3) 接收中</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>空域侦测: <strong style="color:#38bdf8;">3</strong> 架</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>待核验/未备案: <strong style="color:#ff9f0a;">1</strong></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="gate-banner">
|
||||
<div>
|
||||
<strong>UI 方案先选后改门禁(严格遵守 RID 业务边界 · 纯正苹果深色毛玻璃)</strong>
|
||||
:本系统为无人机远程识别 (RID) 侦测、研判与登记平台,非地面站飞控。
|
||||
</div>
|
||||
<div style="font-size:11px; color:#64748b;">
|
||||
依规则展示 A/B/C 三种布局模式,请您确认偏好方案后再行同步至正式界面
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="workspace">
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode A: 地图监控 (对齐 docs/images/实时目标工作台-地图监控.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-a">
|
||||
<!-- Background Map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 900">
|
||||
<!-- Tactical grid & Range rings -->
|
||||
<circle cx="960" cy="450" r="180" fill="none" stroke="rgba(56,140,248,0.18)" stroke-dasharray="3,3"/>
|
||||
<circle cx="960" cy="450" r="360" fill="none" stroke="rgba(56,140,248,0.12)" stroke-dasharray="4,4"/>
|
||||
<line x1="960" y1="50" x2="960" y2="850" stroke="rgba(56,140,248,0.08)"/>
|
||||
<line x1="160" y1="450" x2="1760" y2="450" stroke="rgba(56,140,248,0.08)"/>
|
||||
<!-- River/terrain mock vector -->
|
||||
<path d="M300 700 Q 600 300 960 500 T 1700 200" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="80"/>
|
||||
<!-- Target 1 trail & mark -->
|
||||
<path d="M780 580 L 880 500 L 980 430 L 1060 380" fill="none" stroke="#38bdf8" stroke-width="2" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(1060, 380)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (已备案)</text>
|
||||
</g>
|
||||
<!-- Target 2: Unmatched warning -->
|
||||
<g transform="translate(1280, 480)">
|
||||
<circle cx="0" cy="0" r="24" fill="rgba(255,159,10,0.15)" stroke="#ff9f0a" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#ff9f0a"/>
|
||||
<text x="32" y="5" fill="#fbbf24" font-size="12" font-weight="700">DEMO-002 [未备案预警]</text>
|
||||
</g>
|
||||
<!-- Target 3 -->
|
||||
<g transform="translate(740, 320)">
|
||||
<polygon points="0,-10 7,9 0,5 -7,9" fill="#34d399"/>
|
||||
<text x="18" y="4" fill="#cbd5e1" font-size="11">DEMO-003</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Left Drawer: 监控范围 / 目标列表 -->
|
||||
<aside class="glass-panel mode-a-left">
|
||||
<div class="panel-header">
|
||||
<h3>监控范围 · 目标列表</h3>
|
||||
<span class="tag tag-blue">3 目标在线</span>
|
||||
</div>
|
||||
<div style="padding: 10px 14px 4px;">
|
||||
<input type="text" placeholder="🔍 按 RID / SN 筛选..." style="width:100%;height:32px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="padding: 6px 14px; display:flex; gap:6px; font-size:11px;">
|
||||
<span class="tag tag-blue" style="cursor:pointer;">全部 (3)</span>
|
||||
<span class="tag tag-green" style="cursor:pointer;">已备案 (2)</span>
|
||||
<span class="tag tag-amber" style="cursor:pointer;">未匹配 (1)</span>
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:8px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-001</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 5寸穿越机 · 张伟</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-002</span>
|
||||
<span class="tag tag-amber">待核对 (未备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 未知机型 · 黑飞预警</span>
|
||||
<span style="color:#fbbf24;">● 需核验</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-003</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 行业巡检机 · 李工</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:10px 14px; background:rgba(8,15,28,0.8); border-top:1px solid var(--mc-border); border-radius: 0 0 14px 14px; font-size:11px; color:var(--mc-text-dim);">
|
||||
接收机协议: USB串口 (RAW / JSON / Postcard)<br>
|
||||
空域更新频率: 20ms / 广播帧
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center Toolstrip -->
|
||||
<div class="map-toolstrip">
|
||||
<button class="ts-btn active" title="底图切换">🗺️</button>
|
||||
<button class="ts-btn" title="态势图层">📑</button>
|
||||
<button class="ts-btn" title="视口居中选中目标">🎯</button>
|
||||
<button class="ts-btn" title="2D/3D俯仰视角">🌐</button>
|
||||
<button class="ts-btn" title="复位正北">🧭</button>
|
||||
<div style="height:1px;background:rgba(255,255,255,0.1);margin:2px 0;"></div>
|
||||
<button class="ts-btn" title="放大">+</button>
|
||||
<button class="ts-btn" title="缩小">-</button>
|
||||
</div>
|
||||
|
||||
<!-- Center Alert Bar -->
|
||||
<div class="alert-bar">
|
||||
<span>⚠️ <strong>DEMO-002:</strong> 捕获到未登记 RID 广播信号 · 建议核查本地备案库</span>
|
||||
<a href="#c" style="color:#38bdf8;text-decoration:none;">调取档案研判 ›</a>
|
||||
</div>
|
||||
|
||||
<!-- Right Drawer: 选中目标研判卡 -->
|
||||
<aside class="glass-panel mode-a-right">
|
||||
<div class="panel-header" style="padding:0 0 10px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>选中目标 / DEMO-001</h3>
|
||||
<span class="tag tag-green">已备案登记</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">身份与备案</div>
|
||||
<p class="dossier-val">
|
||||
匹配状态:<strong style="color:#4ade80;">已匹配 (演示备案库)</strong><br>
|
||||
登记 SN:ZEX0RID1202605011000<br>
|
||||
登记机型:5 寸花飞练习机 (穿越机)<br>
|
||||
登记所有人:张伟 (特技飞行组)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">最新空间遥测 (WGS84 椭球高)</div>
|
||||
<p class="dossier-val">
|
||||
经度:120.153820 · 纬度:30.287410<br>
|
||||
相对高度:45.2 m (椭球高 58.6 m)<br>
|
||||
地速:14.2 m/s · 航向角:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">质量与事件</div>
|
||||
<p class="dossier-val">
|
||||
报文采样延迟:16 ms<br>
|
||||
接收物理通道:USB 串口 (COM3)<br>
|
||||
空域防区告警:无违规侵入 (绿码正常)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">🎯 视口居中追踪</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 本地登记核验</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode B: 调度指挥 (对齐 docs/images/实时目标工作台-调度指挥.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout active" id="layout-b">
|
||||
<div class="mode-b-wrap">
|
||||
<div class="mode-b-top">
|
||||
<!-- Top map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 600">
|
||||
<rect width="1920" height="600" fill="none"/>
|
||||
<path d="M200 500 Q 800 200 1600 400" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="70"/>
|
||||
<g transform="translate(850, 240)">
|
||||
<circle cx="0" cy="0" r="26" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="32" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (调度跟踪中)</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<!-- Right floating target brief -->
|
||||
<div class="glass-panel" style="position:absolute; right:16px; top:16px; bottom:16px; width:340px; padding:16px; display:flex; flex-direction:column; gap:10px;">
|
||||
<div class="panel-header" style="padding:0 0 8px;">
|
||||
<h3>调度标的 / DEMO-001</h3>
|
||||
<span class="tag tag-blue">实时追踪</span>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">备案比对</div>
|
||||
<p class="dossier-val">已匹配本地登记档案 (张伟)</p>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">实时航姿</div>
|
||||
<p class="dossier-val">高度 45.2m · 航向 085° · 地速 14.2m/s</p>
|
||||
</div>
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">🎯 锁定追踪</button>
|
||||
<button class="btn btn-secondary">⚠️ 发起协查</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom Event Timeline Dock -->
|
||||
<div class="mode-b-dock">
|
||||
<div class="timeline-pane">
|
||||
<div style="font-size:12px; font-weight:700; color:#fff; margin-bottom:10px; display:flex; justify-content:space-between;">
|
||||
<span>事件时间轴 · 实时调度响应</span>
|
||||
<span style="color:var(--mc-text-dim);font-weight:normal;">突出事件响应与处置流,适合值守调度</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:01</span>
|
||||
<span class="t-badge tag-blue">捕获帧</span>
|
||||
<span class="t-desc">串口捕获新 RID 广播帧:标的 <strong>DEMO-001</strong> (SN: ZEX0RID...)</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:02</span>
|
||||
<span class="t-badge tag-green">匹配成功</span>
|
||||
<span class="t-desc">本地数据库自动匹配成功:机型 5寸穿越机,登记所有人:张伟</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:15</span>
|
||||
<span class="t-badge tag-amber">异常预警</span>
|
||||
<span class="t-desc">捕获未备案目标 <strong>DEMO-002</strong>,未在本地档案中找到匹配记录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:14px; background:rgba(9,18,36,0.6); display:flex; flex-direction:column; justify-content:space-between;">
|
||||
<div>
|
||||
<div style="font-weight:700; font-size:12px; color:#fff; margin-bottom:6px;">处置调度操作台</div>
|
||||
<div style="font-size:11px; color:var(--mc-text-dim); line-height:1.5;">
|
||||
对已标记异常的目标,可一键下发至地面巡查班组或联动外置声光设备。
|
||||
</div>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">📑 导出处置证据</button>
|
||||
<button class="btn btn-secondary">通知值守人</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode C: 目标研判 (对齐 docs/images/实时目标工作台-目标研判.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-c">
|
||||
<div class="mode-c-wrap">
|
||||
<!-- Left: Wide directory & search -->
|
||||
<aside class="glass-panel c-column">
|
||||
<div class="panel-header">
|
||||
<h3>目标目录与研判检索</h3>
|
||||
<span class="tag tag-blue">3 标的</span>
|
||||
</div>
|
||||
<div style="padding:12px 14px 6px;">
|
||||
<input type="text" placeholder="🔍 检索 RID / SN / 登记人..." style="width:100%;height:34px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:6px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-001</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: ZEX0RID1202605011000</span><span>张伟</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-002</span><span class="tag tag-red">黑飞未备案</span></div>
|
||||
<div class="tc-sub"><span>SN: UNKNOWN_SN_8891</span><span>无登记</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-003</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: DJI_M4P_2026_0991</span><span>李工</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center: Forensics Map -->
|
||||
<section class="glass-panel c-column" style="position:relative;">
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1000 800">
|
||||
<path d="M200 650 L 350 500 L 520 450 L 700 320" fill="none" stroke="#38bdf8" stroke-width="3" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(700, 320)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.2)" stroke="#38bdf8" stroke-width="2"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="14" font-weight="700">研判标的: DEMO-001</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div style="position:absolute; bottom:14px; left:16px; background:rgba(8,15,28,0.85); padding:6px 12px; border-radius:6px; font-size:11px; color:#cbd5e1; border:1px solid var(--mc-border);">
|
||||
天地图卫星航拍 · 航迹点位回放累计:24 帧
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Right: Evidence & Forensics Dossier -->
|
||||
<aside class="glass-panel c-column" style="padding:16px; gap:12px; overflow-y:auto;">
|
||||
<div class="panel-header" style="padding:0 0 8px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>研判档案卡 · DEMO-001</h3>
|
||||
<span class="tag tag-green">合规标的</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">空间几何坐标 (WGS84)</div>
|
||||
<p class="dossier-val">
|
||||
经纬度:120.153820 · 30.287410<br>
|
||||
相对高度:45.2 m (离地估算)<br>
|
||||
椭球高:58.6 m · 航向:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">报文时效与物理链路</div>
|
||||
<p class="dossier-val">
|
||||
数据延迟:16 ms<br>
|
||||
输入通道:USB 串口接收解码<br>
|
||||
接收信号强度 (RSSI):-68 dBm
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">研判核验结论</div>
|
||||
<p class="dossier-val" style="color:#4ade80;">
|
||||
✓ 捕获到合规国标 RID 广播数据<br>
|
||||
✓ 模块 SN 与本地数据库登记记录完全匹配<br>
|
||||
✓ 飞手资质与无人机备案照片齐全
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">📑 生成研判报告</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 调取登记照片</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function switchMode(mode, btn) {
|
||||
document.querySelectorAll('.layout').forEach(l => l.classList.remove('active'));
|
||||
document.querySelectorAll('.nav-tab').forEach(b => b.classList.remove('active'));
|
||||
document.getElementById('layout-' + mode).classList.add('active');
|
||||
btn.classList.add('active');
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,787 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>RID 无人机远程识别态势与研判平台 · 苹果半透明风格原型</title>
|
||||
<style>
|
||||
:root {
|
||||
--mc-bg: #060b14;
|
||||
--mc-panel-bg: rgba(9, 18, 36, 0.82);
|
||||
--mc-panel-card: rgba(14, 25, 48, 0.65);
|
||||
--mc-panel-card-hover: rgba(18, 34, 64, 0.8);
|
||||
--mc-panel-card-active: rgba(18, 42, 82, 0.9);
|
||||
--mc-border: rgba(48, 85, 140, 0.38);
|
||||
--mc-border-light: rgba(255, 255, 255, 0.1);
|
||||
--mc-accent: #38bdf8;
|
||||
--mc-accent-blue: #0a84ff;
|
||||
--mc-success: #30d158;
|
||||
--mc-warning: #ff9f0a;
|
||||
--mc-danger: #ff453a;
|
||||
--mc-text: #f8fafc;
|
||||
--mc-text-muted: #94a3b8;
|
||||
--mc-text-dim: #64748b;
|
||||
--mc-radius-lg: 14px;
|
||||
--mc-radius-md: 10px;
|
||||
--mc-radius-sm: 8px;
|
||||
--mc-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", sans-serif;
|
||||
color-scheme: dark;
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--mc-bg);
|
||||
color: var(--mc-text);
|
||||
font-size: 13px;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Topbar */
|
||||
.topbar {
|
||||
height: 56px;
|
||||
background: rgba(8, 15, 28, 0.88);
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
||||
border-bottom: 1px solid var(--mc-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 20px;
|
||||
z-index: 100;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.4);
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.brand-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, rgba(10,132,255,0.7), rgba(56,189,248,0.35));
|
||||
border: 1px solid rgba(56,189,248,0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #38bdf8;
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.brand-title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.brand-sub {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
/* Nav Tabs */
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
.nav-tab {
|
||||
height: 100%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 18px;
|
||||
background: transparent;
|
||||
color: var(--mc-text-muted);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.nav-tab:hover {
|
||||
color: #fff;
|
||||
background: rgba(255,255,255,0.04);
|
||||
}
|
||||
.nav-tab.active {
|
||||
color: #38bdf8;
|
||||
border-bottom-color: #38bdf8;
|
||||
text-shadow: 0 0 10px rgba(56,189,248,0.4);
|
||||
}
|
||||
.top-capsule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
background: rgba(14, 25, 45, 0.75);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
border-radius: 9999px;
|
||||
padding: 6px 14px;
|
||||
font-size: 11px;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.pulse-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.pulse-dot.green { background: var(--mc-success); box-shadow: 0 0 8px var(--mc-success); }
|
||||
.pulse-dot.amber { background: var(--mc-warning); box-shadow: 0 0 8px var(--mc-warning); }
|
||||
|
||||
/* Workspace */
|
||||
.workspace {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.layout {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: none;
|
||||
}
|
||||
.layout.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Common Glass Card */
|
||||
.glass-panel {
|
||||
background: var(--mc-panel-bg);
|
||||
backdrop-filter: blur(28px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(190%);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
box-shadow: var(--mc-shadow);
|
||||
z-index: 10;
|
||||
}
|
||||
.panel-header {
|
||||
padding: 14px 16px 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
.panel-header h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tag {
|
||||
font-size: 10px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.tag-blue { background: rgba(56,189,248,0.2); color: #38bdf8; border: 1px solid rgba(56,189,248,0.4); }
|
||||
.tag-green { background: rgba(48,209,88,0.2); color: #4ade80; border: 1px solid rgba(48,209,88,0.4); }
|
||||
.tag-amber { background: rgba(255,159,10,0.2); color: #fbbf24; border: 1px solid rgba(255,159,10,0.4); }
|
||||
.tag-red { background: rgba(255,69,58,0.2); color: #f87171; border: 1px solid rgba(255,69,58,0.4); }
|
||||
|
||||
/* Map canvas & overlays */
|
||||
.map-container {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #060b14 radial-gradient(circle at 50% 50%, rgba(20,40,75,0.3) 0%, transparent 75%);
|
||||
}
|
||||
.map-canvas-svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Target item in list */
|
||||
.target-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.target-card:hover {
|
||||
background: var(--mc-panel-card-hover);
|
||||
border-color: rgba(56, 140, 248, 0.45);
|
||||
}
|
||||
.target-card.active {
|
||||
background: var(--mc-panel-card-active);
|
||||
border-color: #1a72ff;
|
||||
box-shadow: 0 4px 16px rgba(26,114,255,0.3), inset 0 1px 0 rgba(255,255,255,0.15);
|
||||
}
|
||||
.tc-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.tc-title {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tc-sub {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
/* Mode A Specific */
|
||||
.mode-a-left {
|
||||
position: absolute;
|
||||
left: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.mode-a-right {
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 360px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.map-toolstrip {
|
||||
position: absolute;
|
||||
left: 352px;
|
||||
top: 16px;
|
||||
background: rgba(9, 18, 36, 0.85);
|
||||
backdrop-filter: blur(24px);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: 10px;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
z-index: 20;
|
||||
}
|
||||
.ts-btn {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.ts-btn:hover { background: rgba(255,255,255,0.08); color: #fff; }
|
||||
.ts-btn.active { background: rgba(26,114,255,0.25); color: #38bdf8; }
|
||||
.alert-bar {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
left: 410px;
|
||||
right: 396px;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
height: 36px;
|
||||
background: rgba(30,22,10,0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(245,158,11,0.6);
|
||||
border-radius: 8px;
|
||||
padding: 0 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 12px;
|
||||
color: #fbbf24;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
/* Mode B Specific (Dispatch & Timeline) */
|
||||
.mode-b-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
.mode-b-top {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
}
|
||||
.mode-b-dock {
|
||||
height: 240px;
|
||||
background: rgba(8, 15, 28, 0.92);
|
||||
backdrop-filter: blur(28px);
|
||||
border-top: 1px solid var(--mc-border);
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 340px;
|
||||
z-index: 10;
|
||||
}
|
||||
.timeline-pane {
|
||||
padding: 14px 18px;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid var(--mc-border);
|
||||
}
|
||||
.timeline-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: rgba(14,25,48,0.5);
|
||||
border: 1px solid rgba(38,68,115,0.3);
|
||||
border-radius: 6px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.t-time { color: var(--mc-text-dim); font-size: 11px; min-width: 55px; }
|
||||
.t-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; font-weight: 700; }
|
||||
.t-desc { flex: 1; color: #cbd5e1; }
|
||||
|
||||
/* Mode C Specific (Forensics & Deep Analysis) */
|
||||
.mode-c-wrap {
|
||||
display: grid;
|
||||
grid-template-columns: 340px 1fr 380px;
|
||||
height: 100%;
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
}
|
||||
.c-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Dossier Info Blocks */
|
||||
.dossier-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.dossier-label {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.dossier-val {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: #e2e8f0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.btn-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(180deg, #1d68cf 0%, #1557b0 100%);
|
||||
border: 1px solid rgba(147,197,253,0.35);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: rgba(255,255,255,0.08);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
/* Choice Gate Banner */
|
||||
.gate-banner {
|
||||
background: rgba(14, 25, 48, 0.9);
|
||||
border-bottom: 1px solid rgba(56, 189, 248, 0.3);
|
||||
padding: 8px 20px;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.gate-banner strong { color: #38bdf8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Topbar -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<div class="brand-icon">📡</div>
|
||||
<div>
|
||||
<div class="brand-title">RID / 实时目标工作台</div>
|
||||
<div class="brand-sub">REMOTE ID SURVEILLANCE & REGULATORY FORENSICS</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mode Selectors -->
|
||||
<nav class="nav-tabs">
|
||||
<button class="nav-tab" onclick="switchMode('a', this)">A · 地图监控 (日常全域监视)</button>
|
||||
<button class="nav-tab" onclick="switchMode('b', this)">B · 调度指挥 (事件时间轴响应)</button>
|
||||
<button class="nav-tab active" onclick="switchMode('c', this)">C · 目标研判 (档案核验与取证)</button>
|
||||
</nav>
|
||||
|
||||
<div class="top-capsule">
|
||||
<span><span class="pulse-dot green"></span> 接收机: USB串口 (COM3) 接收中</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>空域侦测: <strong style="color:#38bdf8;">3</strong> 架</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>待核验/未备案: <strong style="color:#ff9f0a;">1</strong></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="gate-banner">
|
||||
<div>
|
||||
<strong>UI 方案先选后改门禁(严格遵守 RID 业务边界 · 纯正苹果深色毛玻璃)</strong>
|
||||
:本系统为无人机远程识别 (RID) 侦测、研判与登记平台,非地面站飞控。
|
||||
</div>
|
||||
<div style="font-size:11px; color:#64748b;">
|
||||
依规则展示 A/B/C 三种布局模式,请您确认偏好方案后再行同步至正式界面
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="workspace">
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode A: 地图监控 (对齐 docs/images/实时目标工作台-地图监控.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-a">
|
||||
<!-- Background Map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 900">
|
||||
<!-- Tactical grid & Range rings -->
|
||||
<circle cx="960" cy="450" r="180" fill="none" stroke="rgba(56,140,248,0.18)" stroke-dasharray="3,3"/>
|
||||
<circle cx="960" cy="450" r="360" fill="none" stroke="rgba(56,140,248,0.12)" stroke-dasharray="4,4"/>
|
||||
<line x1="960" y1="50" x2="960" y2="850" stroke="rgba(56,140,248,0.08)"/>
|
||||
<line x1="160" y1="450" x2="1760" y2="450" stroke="rgba(56,140,248,0.08)"/>
|
||||
<!-- River/terrain mock vector -->
|
||||
<path d="M300 700 Q 600 300 960 500 T 1700 200" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="80"/>
|
||||
<!-- Target 1 trail & mark -->
|
||||
<path d="M780 580 L 880 500 L 980 430 L 1060 380" fill="none" stroke="#38bdf8" stroke-width="2" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(1060, 380)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (已备案)</text>
|
||||
</g>
|
||||
<!-- Target 2: Unmatched warning -->
|
||||
<g transform="translate(1280, 480)">
|
||||
<circle cx="0" cy="0" r="24" fill="rgba(255,159,10,0.15)" stroke="#ff9f0a" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#ff9f0a"/>
|
||||
<text x="32" y="5" fill="#fbbf24" font-size="12" font-weight="700">DEMO-002 [未备案预警]</text>
|
||||
</g>
|
||||
<!-- Target 3 -->
|
||||
<g transform="translate(740, 320)">
|
||||
<polygon points="0,-10 7,9 0,5 -7,9" fill="#34d399"/>
|
||||
<text x="18" y="4" fill="#cbd5e1" font-size="11">DEMO-003</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Left Drawer: 监控范围 / 目标列表 -->
|
||||
<aside class="glass-panel mode-a-left">
|
||||
<div class="panel-header">
|
||||
<h3>监控范围 · 目标列表</h3>
|
||||
<span class="tag tag-blue">3 目标在线</span>
|
||||
</div>
|
||||
<div style="padding: 10px 14px 4px;">
|
||||
<input type="text" placeholder="🔍 按 RID / SN 筛选..." style="width:100%;height:32px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="padding: 6px 14px; display:flex; gap:6px; font-size:11px;">
|
||||
<span class="tag tag-blue" style="cursor:pointer;">全部 (3)</span>
|
||||
<span class="tag tag-green" style="cursor:pointer;">已备案 (2)</span>
|
||||
<span class="tag tag-amber" style="cursor:pointer;">未匹配 (1)</span>
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:8px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-001</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 5寸穿越机 · 张伟</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-002</span>
|
||||
<span class="tag tag-amber">待核对 (未备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 未知机型 · 黑飞预警</span>
|
||||
<span style="color:#fbbf24;">● 需核验</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-003</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 行业巡检机 · 李工</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:10px 14px; background:rgba(8,15,28,0.8); border-top:1px solid var(--mc-border); border-radius: 0 0 14px 14px; font-size:11px; color:var(--mc-text-dim);">
|
||||
接收机协议: USB串口 (RAW / JSON / Postcard)<br>
|
||||
空域更新频率: 20ms / 广播帧
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center Toolstrip -->
|
||||
<div class="map-toolstrip">
|
||||
<button class="ts-btn active" title="底图切换">🗺️</button>
|
||||
<button class="ts-btn" title="态势图层">📑</button>
|
||||
<button class="ts-btn" title="视口居中选中目标">🎯</button>
|
||||
<button class="ts-btn" title="2D/3D俯仰视角">🌐</button>
|
||||
<button class="ts-btn" title="复位正北">🧭</button>
|
||||
<div style="height:1px;background:rgba(255,255,255,0.1);margin:2px 0;"></div>
|
||||
<button class="ts-btn" title="放大">+</button>
|
||||
<button class="ts-btn" title="缩小">-</button>
|
||||
</div>
|
||||
|
||||
<!-- Center Alert Bar -->
|
||||
<div class="alert-bar">
|
||||
<span>⚠️ <strong>DEMO-002:</strong> 捕获到未登记 RID 广播信号 · 建议核查本地备案库</span>
|
||||
<a href="#c" style="color:#38bdf8;text-decoration:none;">调取档案研判 ›</a>
|
||||
</div>
|
||||
|
||||
<!-- Right Drawer: 选中目标研判卡 -->
|
||||
<aside class="glass-panel mode-a-right">
|
||||
<div class="panel-header" style="padding:0 0 10px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>选中目标 / DEMO-001</h3>
|
||||
<span class="tag tag-green">已备案登记</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">身份与备案</div>
|
||||
<p class="dossier-val">
|
||||
匹配状态:<strong style="color:#4ade80;">已匹配 (演示备案库)</strong><br>
|
||||
登记 SN:ZEX0RID1202605011000<br>
|
||||
登记机型:5 寸花飞练习机 (穿越机)<br>
|
||||
登记所有人:张伟 (特技飞行组)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">最新空间遥测 (WGS84 椭球高)</div>
|
||||
<p class="dossier-val">
|
||||
经度:120.153820 · 纬度:30.287410<br>
|
||||
相对高度:45.2 m (椭球高 58.6 m)<br>
|
||||
地速:14.2 m/s · 航向角:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">质量与事件</div>
|
||||
<p class="dossier-val">
|
||||
报文采样延迟:16 ms<br>
|
||||
接收物理通道:USB 串口 (COM3)<br>
|
||||
空域防区告警:无违规侵入 (绿码正常)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">🎯 视口居中追踪</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 本地登记核验</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode B: 调度指挥 (对齐 docs/images/实时目标工作台-调度指挥.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-b">
|
||||
<div class="mode-b-wrap">
|
||||
<div class="mode-b-top">
|
||||
<!-- Top map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 600">
|
||||
<rect width="1920" height="600" fill="none"/>
|
||||
<path d="M200 500 Q 800 200 1600 400" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="70"/>
|
||||
<g transform="translate(850, 240)">
|
||||
<circle cx="0" cy="0" r="26" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="32" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (调度跟踪中)</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<!-- Right floating target brief -->
|
||||
<div class="glass-panel" style="position:absolute; right:16px; top:16px; bottom:16px; width:340px; padding:16px; display:flex; flex-direction:column; gap:10px;">
|
||||
<div class="panel-header" style="padding:0 0 8px;">
|
||||
<h3>调度标的 / DEMO-001</h3>
|
||||
<span class="tag tag-blue">实时追踪</span>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">备案比对</div>
|
||||
<p class="dossier-val">已匹配本地登记档案 (张伟)</p>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">实时航姿</div>
|
||||
<p class="dossier-val">高度 45.2m · 航向 085° · 地速 14.2m/s</p>
|
||||
</div>
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">🎯 锁定追踪</button>
|
||||
<button class="btn btn-secondary">⚠️ 发起协查</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom Event Timeline Dock -->
|
||||
<div class="mode-b-dock">
|
||||
<div class="timeline-pane">
|
||||
<div style="font-size:12px; font-weight:700; color:#fff; margin-bottom:10px; display:flex; justify-content:space-between;">
|
||||
<span>事件时间轴 · 实时调度响应</span>
|
||||
<span style="color:var(--mc-text-dim);font-weight:normal;">突出事件响应与处置流,适合值守调度</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:01</span>
|
||||
<span class="t-badge tag-blue">捕获帧</span>
|
||||
<span class="t-desc">串口捕获新 RID 广播帧:标的 <strong>DEMO-001</strong> (SN: ZEX0RID...)</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:02</span>
|
||||
<span class="t-badge tag-green">匹配成功</span>
|
||||
<span class="t-desc">本地数据库自动匹配成功:机型 5寸穿越机,登记所有人:张伟</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:15</span>
|
||||
<span class="t-badge tag-amber">异常预警</span>
|
||||
<span class="t-desc">捕获未备案目标 <strong>DEMO-002</strong>,未在本地档案中找到匹配记录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:14px; background:rgba(9,18,36,0.6); display:flex; flex-direction:column; justify-content:space-between;">
|
||||
<div>
|
||||
<div style="font-weight:700; font-size:12px; color:#fff; margin-bottom:6px;">处置调度操作台</div>
|
||||
<div style="font-size:11px; color:var(--mc-text-dim); line-height:1.5;">
|
||||
对已标记异常的目标,可一键下发至地面巡查班组或联动外置声光设备。
|
||||
</div>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">📑 导出处置证据</button>
|
||||
<button class="btn btn-secondary">通知值守人</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode C: 目标研判 (对齐 docs/images/实时目标工作台-目标研判.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout active" id="layout-c">
|
||||
<div class="mode-c-wrap">
|
||||
<!-- Left: Wide directory & search -->
|
||||
<aside class="glass-panel c-column">
|
||||
<div class="panel-header">
|
||||
<h3>目标目录与研判检索</h3>
|
||||
<span class="tag tag-blue">3 标的</span>
|
||||
</div>
|
||||
<div style="padding:12px 14px 6px;">
|
||||
<input type="text" placeholder="🔍 检索 RID / SN / 登记人..." style="width:100%;height:34px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:6px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-001</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: ZEX0RID1202605011000</span><span>张伟</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-002</span><span class="tag tag-red">黑飞未备案</span></div>
|
||||
<div class="tc-sub"><span>SN: UNKNOWN_SN_8891</span><span>无登记</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-003</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: DJI_M4P_2026_0991</span><span>李工</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center: Forensics Map -->
|
||||
<section class="glass-panel c-column" style="position:relative;">
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1000 800">
|
||||
<path d="M200 650 L 350 500 L 520 450 L 700 320" fill="none" stroke="#38bdf8" stroke-width="3" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(700, 320)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.2)" stroke="#38bdf8" stroke-width="2"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="14" font-weight="700">研判标的: DEMO-001</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div style="position:absolute; bottom:14px; left:16px; background:rgba(8,15,28,0.85); padding:6px 12px; border-radius:6px; font-size:11px; color:#cbd5e1; border:1px solid var(--mc-border);">
|
||||
天地图卫星航拍 · 航迹点位回放累计:24 帧
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Right: Evidence & Forensics Dossier -->
|
||||
<aside class="glass-panel c-column" style="padding:16px; gap:12px; overflow-y:auto;">
|
||||
<div class="panel-header" style="padding:0 0 8px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>研判档案卡 · DEMO-001</h3>
|
||||
<span class="tag tag-green">合规标的</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">空间几何坐标 (WGS84)</div>
|
||||
<p class="dossier-val">
|
||||
经纬度:120.153820 · 30.287410<br>
|
||||
相对高度:45.2 m (离地估算)<br>
|
||||
椭球高:58.6 m · 航向:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">报文时效与物理链路</div>
|
||||
<p class="dossier-val">
|
||||
数据延迟:16 ms<br>
|
||||
输入通道:USB 串口接收解码<br>
|
||||
接收信号强度 (RSSI):-68 dBm
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">研判核验结论</div>
|
||||
<p class="dossier-val" style="color:#4ade80;">
|
||||
✓ 捕获到合规国标 RID 广播数据<br>
|
||||
✓ 模块 SN 与本地数据库登记记录完全匹配<br>
|
||||
✓ 飞手资质与无人机备案照片齐全
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">📑 生成研判报告</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 调取登记照片</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function switchMode(mode, btn) {
|
||||
document.querySelectorAll('.layout').forEach(l => l.classList.remove('active'));
|
||||
document.querySelectorAll('.nav-tab').forEach(b => b.classList.remove('active'));
|
||||
document.getElementById('layout-' + mode).classList.add('active');
|
||||
btn.classList.add('active');
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,787 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>RID 无人机远程识别态势与研判平台 · 苹果半透明风格原型</title>
|
||||
<style>
|
||||
:root {
|
||||
--mc-bg: #060b14;
|
||||
--mc-panel-bg: rgba(9, 18, 36, 0.82);
|
||||
--mc-panel-card: rgba(14, 25, 48, 0.65);
|
||||
--mc-panel-card-hover: rgba(18, 34, 64, 0.8);
|
||||
--mc-panel-card-active: rgba(18, 42, 82, 0.9);
|
||||
--mc-border: rgba(48, 85, 140, 0.38);
|
||||
--mc-border-light: rgba(255, 255, 255, 0.1);
|
||||
--mc-accent: #38bdf8;
|
||||
--mc-accent-blue: #0a84ff;
|
||||
--mc-success: #30d158;
|
||||
--mc-warning: #ff9f0a;
|
||||
--mc-danger: #ff453a;
|
||||
--mc-text: #f8fafc;
|
||||
--mc-text-muted: #94a3b8;
|
||||
--mc-text-dim: #64748b;
|
||||
--mc-radius-lg: 14px;
|
||||
--mc-radius-md: 10px;
|
||||
--mc-radius-sm: 8px;
|
||||
--mc-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", Roboto, "PingFang SC", sans-serif;
|
||||
color-scheme: dark;
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--mc-bg);
|
||||
color: var(--mc-text);
|
||||
font-size: 13px;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Topbar */
|
||||
.topbar {
|
||||
height: 56px;
|
||||
background: rgba(8, 15, 28, 0.88);
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
||||
border-bottom: 1px solid var(--mc-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 20px;
|
||||
z-index: 100;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.4);
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.brand-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, rgba(10,132,255,0.7), rgba(56,189,248,0.35));
|
||||
border: 1px solid rgba(56,189,248,0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #38bdf8;
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.brand-title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.brand-sub {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
/* Nav Tabs */
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
.nav-tab {
|
||||
height: 100%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 18px;
|
||||
background: transparent;
|
||||
color: var(--mc-text-muted);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.nav-tab:hover {
|
||||
color: #fff;
|
||||
background: rgba(255,255,255,0.04);
|
||||
}
|
||||
.nav-tab.active {
|
||||
color: #38bdf8;
|
||||
border-bottom-color: #38bdf8;
|
||||
text-shadow: 0 0 10px rgba(56,189,248,0.4);
|
||||
}
|
||||
.top-capsule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
background: rgba(14, 25, 45, 0.75);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
border-radius: 9999px;
|
||||
padding: 6px 14px;
|
||||
font-size: 11px;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.pulse-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.pulse-dot.green { background: var(--mc-success); box-shadow: 0 0 8px var(--mc-success); }
|
||||
.pulse-dot.amber { background: var(--mc-warning); box-shadow: 0 0 8px var(--mc-warning); }
|
||||
|
||||
/* Workspace */
|
||||
.workspace {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.layout {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: none;
|
||||
}
|
||||
.layout.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Common Glass Card */
|
||||
.glass-panel {
|
||||
background: var(--mc-panel-bg);
|
||||
backdrop-filter: blur(28px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(190%);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: var(--mc-radius-lg);
|
||||
box-shadow: var(--mc-shadow);
|
||||
z-index: 10;
|
||||
}
|
||||
.panel-header {
|
||||
padding: 14px 16px 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
.panel-header h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tag {
|
||||
font-size: 10px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.tag-blue { background: rgba(56,189,248,0.2); color: #38bdf8; border: 1px solid rgba(56,189,248,0.4); }
|
||||
.tag-green { background: rgba(48,209,88,0.2); color: #4ade80; border: 1px solid rgba(48,209,88,0.4); }
|
||||
.tag-amber { background: rgba(255,159,10,0.2); color: #fbbf24; border: 1px solid rgba(255,159,10,0.4); }
|
||||
.tag-red { background: rgba(255,69,58,0.2); color: #f87171; border: 1px solid rgba(255,69,58,0.4); }
|
||||
|
||||
/* Map canvas & overlays */
|
||||
.map-container {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #060b14 radial-gradient(circle at 50% 50%, rgba(20,40,75,0.3) 0%, transparent 75%);
|
||||
}
|
||||
.map-canvas-svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Target item in list */
|
||||
.target-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-md);
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.target-card:hover {
|
||||
background: var(--mc-panel-card-hover);
|
||||
border-color: rgba(56, 140, 248, 0.45);
|
||||
}
|
||||
.target-card.active {
|
||||
background: var(--mc-panel-card-active);
|
||||
border-color: #1a72ff;
|
||||
box-shadow: 0 4px 16px rgba(26,114,255,0.3), inset 0 1px 0 rgba(255,255,255,0.15);
|
||||
}
|
||||
.tc-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.tc-title {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.tc-sub {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
color: var(--mc-text-dim);
|
||||
}
|
||||
|
||||
/* Mode A Specific */
|
||||
.mode-a-left {
|
||||
position: absolute;
|
||||
left: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.mode-a-right {
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
top: 16px;
|
||||
bottom: 16px;
|
||||
width: 360px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.map-toolstrip {
|
||||
position: absolute;
|
||||
left: 352px;
|
||||
top: 16px;
|
||||
background: rgba(9, 18, 36, 0.85);
|
||||
backdrop-filter: blur(24px);
|
||||
border: 1px solid var(--mc-border);
|
||||
border-radius: 10px;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
z-index: 20;
|
||||
}
|
||||
.ts-btn {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.ts-btn:hover { background: rgba(255,255,255,0.08); color: #fff; }
|
||||
.ts-btn.active { background: rgba(26,114,255,0.25); color: #38bdf8; }
|
||||
.alert-bar {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
left: 410px;
|
||||
right: 396px;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
height: 36px;
|
||||
background: rgba(30,22,10,0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(245,158,11,0.6);
|
||||
border-radius: 8px;
|
||||
padding: 0 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 12px;
|
||||
color: #fbbf24;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
/* Mode B Specific (Dispatch & Timeline) */
|
||||
.mode-b-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
.mode-b-top {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
}
|
||||
.mode-b-dock {
|
||||
height: 240px;
|
||||
background: rgba(8, 15, 28, 0.92);
|
||||
backdrop-filter: blur(28px);
|
||||
border-top: 1px solid var(--mc-border);
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 340px;
|
||||
z-index: 10;
|
||||
}
|
||||
.timeline-pane {
|
||||
padding: 14px 18px;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid var(--mc-border);
|
||||
}
|
||||
.timeline-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: rgba(14,25,48,0.5);
|
||||
border: 1px solid rgba(38,68,115,0.3);
|
||||
border-radius: 6px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.t-time { color: var(--mc-text-dim); font-size: 11px; min-width: 55px; }
|
||||
.t-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; font-weight: 700; }
|
||||
.t-desc { flex: 1; color: #cbd5e1; }
|
||||
|
||||
/* Mode C Specific (Forensics & Deep Analysis) */
|
||||
.mode-c-wrap {
|
||||
display: grid;
|
||||
grid-template-columns: 340px 1fr 380px;
|
||||
height: 100%;
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
}
|
||||
.c-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Dossier Info Blocks */
|
||||
.dossier-card {
|
||||
background: var(--mc-panel-card);
|
||||
border: 1px solid rgba(38, 68, 115, 0.35);
|
||||
border-radius: var(--mc-radius-sm);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.dossier-label {
|
||||
font-size: 10px;
|
||||
color: var(--mc-text-dim);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.dossier-val {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: #e2e8f0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.btn-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--mc-radius-sm);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(180deg, #1d68cf 0%, #1557b0 100%);
|
||||
border: 1px solid rgba(147,197,253,0.35);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: rgba(255,255,255,0.08);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
/* Choice Gate Banner */
|
||||
.gate-banner {
|
||||
background: rgba(14, 25, 48, 0.9);
|
||||
border-bottom: 1px solid rgba(56, 189, 248, 0.3);
|
||||
padding: 8px 20px;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.gate-banner strong { color: #38bdf8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Topbar -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<div class="brand-icon">📡</div>
|
||||
<div>
|
||||
<div class="brand-title">RID / 实时目标工作台</div>
|
||||
<div class="brand-sub">REMOTE ID SURVEILLANCE & REGULATORY FORENSICS</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mode Selectors -->
|
||||
<nav class="nav-tabs">
|
||||
<button class="nav-tab active" onclick="switchMode('a', this)">A · 地图监控 (日常全域监视)</button>
|
||||
<button class="nav-tab" onclick="switchMode('b', this)">B · 调度指挥 (事件时间轴响应)</button>
|
||||
<button class="nav-tab" onclick="switchMode('c', this)">C · 目标研判 (档案核验与取证)</button>
|
||||
</nav>
|
||||
|
||||
<div class="top-capsule">
|
||||
<span><span class="pulse-dot green"></span> 接收机: USB串口 (COM3) 接收中</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>空域侦测: <strong style="color:#38bdf8;">3</strong> 架</span>
|
||||
<span style="color:rgba(255,255,255,0.2);">|</span>
|
||||
<span>待核验/未备案: <strong style="color:#ff9f0a;">1</strong></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="gate-banner">
|
||||
<div>
|
||||
<strong>UI 方案先选后改门禁(严格遵守 RID 业务边界 · 纯正苹果深色毛玻璃)</strong>
|
||||
:本系统为无人机远程识别 (RID) 侦测、研判与登记平台,非地面站飞控。
|
||||
</div>
|
||||
<div style="font-size:11px; color:#64748b;">
|
||||
依规则展示 A/B/C 三种布局模式,请您确认偏好方案后再行同步至正式界面
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="workspace">
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode A: 地图监控 (对齐 docs/images/实时目标工作台-地图监控.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout active" id="layout-a">
|
||||
<!-- Background Map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 900">
|
||||
<!-- Tactical grid & Range rings -->
|
||||
<circle cx="960" cy="450" r="180" fill="none" stroke="rgba(56,140,248,0.18)" stroke-dasharray="3,3"/>
|
||||
<circle cx="960" cy="450" r="360" fill="none" stroke="rgba(56,140,248,0.12)" stroke-dasharray="4,4"/>
|
||||
<line x1="960" y1="50" x2="960" y2="850" stroke="rgba(56,140,248,0.08)"/>
|
||||
<line x1="160" y1="450" x2="1760" y2="450" stroke="rgba(56,140,248,0.08)"/>
|
||||
<!-- River/terrain mock vector -->
|
||||
<path d="M300 700 Q 600 300 960 500 T 1700 200" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="80"/>
|
||||
<!-- Target 1 trail & mark -->
|
||||
<path d="M780 580 L 880 500 L 980 430 L 1060 380" fill="none" stroke="#38bdf8" stroke-width="2" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(1060, 380)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (已备案)</text>
|
||||
</g>
|
||||
<!-- Target 2: Unmatched warning -->
|
||||
<g transform="translate(1280, 480)">
|
||||
<circle cx="0" cy="0" r="24" fill="rgba(255,159,10,0.15)" stroke="#ff9f0a" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#ff9f0a"/>
|
||||
<text x="32" y="5" fill="#fbbf24" font-size="12" font-weight="700">DEMO-002 [未备案预警]</text>
|
||||
</g>
|
||||
<!-- Target 3 -->
|
||||
<g transform="translate(740, 320)">
|
||||
<polygon points="0,-10 7,9 0,5 -7,9" fill="#34d399"/>
|
||||
<text x="18" y="4" fill="#cbd5e1" font-size="11">DEMO-003</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Left Drawer: 监控范围 / 目标列表 -->
|
||||
<aside class="glass-panel mode-a-left">
|
||||
<div class="panel-header">
|
||||
<h3>监控范围 · 目标列表</h3>
|
||||
<span class="tag tag-blue">3 目标在线</span>
|
||||
</div>
|
||||
<div style="padding: 10px 14px 4px;">
|
||||
<input type="text" placeholder="🔍 按 RID / SN 筛选..." style="width:100%;height:32px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="padding: 6px 14px; display:flex; gap:6px; font-size:11px;">
|
||||
<span class="tag tag-blue" style="cursor:pointer;">全部 (3)</span>
|
||||
<span class="tag tag-green" style="cursor:pointer;">已备案 (2)</span>
|
||||
<span class="tag tag-amber" style="cursor:pointer;">未匹配 (1)</span>
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:8px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-001</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 5寸穿越机 · 张伟</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-002</span>
|
||||
<span class="tag tag-amber">待核对 (未备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 未知机型 · 黑飞预警</span>
|
||||
<span style="color:#fbbf24;">● 需核验</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head">
|
||||
<span class="tc-title">DEMO-003</span>
|
||||
<span class="tag tag-green">已匹配 (已备案)</span>
|
||||
</div>
|
||||
<div class="tc-sub">
|
||||
<span>机型: 行业巡检机 · 李工</span>
|
||||
<span style="color:#4ade80;">● 正常跟踪</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:10px 14px; background:rgba(8,15,28,0.8); border-top:1px solid var(--mc-border); border-radius: 0 0 14px 14px; font-size:11px; color:var(--mc-text-dim);">
|
||||
接收机协议: USB串口 (RAW / JSON / Postcard)<br>
|
||||
空域更新频率: 20ms / 广播帧
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center Toolstrip -->
|
||||
<div class="map-toolstrip">
|
||||
<button class="ts-btn active" title="底图切换">🗺️</button>
|
||||
<button class="ts-btn" title="态势图层">📑</button>
|
||||
<button class="ts-btn" title="视口居中选中目标">🎯</button>
|
||||
<button class="ts-btn" title="2D/3D俯仰视角">🌐</button>
|
||||
<button class="ts-btn" title="复位正北">🧭</button>
|
||||
<div style="height:1px;background:rgba(255,255,255,0.1);margin:2px 0;"></div>
|
||||
<button class="ts-btn" title="放大">+</button>
|
||||
<button class="ts-btn" title="缩小">-</button>
|
||||
</div>
|
||||
|
||||
<!-- Center Alert Bar -->
|
||||
<div class="alert-bar">
|
||||
<span>⚠️ <strong>DEMO-002:</strong> 捕获到未登记 RID 广播信号 · 建议核查本地备案库</span>
|
||||
<a href="#c" style="color:#38bdf8;text-decoration:none;">调取档案研判 ›</a>
|
||||
</div>
|
||||
|
||||
<!-- Right Drawer: 选中目标研判卡 -->
|
||||
<aside class="glass-panel mode-a-right">
|
||||
<div class="panel-header" style="padding:0 0 10px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>选中目标 / DEMO-001</h3>
|
||||
<span class="tag tag-green">已备案登记</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">身份与备案</div>
|
||||
<p class="dossier-val">
|
||||
匹配状态:<strong style="color:#4ade80;">已匹配 (演示备案库)</strong><br>
|
||||
登记 SN:ZEX0RID1202605011000<br>
|
||||
登记机型:5 寸花飞练习机 (穿越机)<br>
|
||||
登记所有人:张伟 (特技飞行组)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">最新空间遥测 (WGS84 椭球高)</div>
|
||||
<p class="dossier-val">
|
||||
经度:120.153820 · 纬度:30.287410<br>
|
||||
相对高度:45.2 m (椭球高 58.6 m)<br>
|
||||
地速:14.2 m/s · 航向角:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">质量与事件</div>
|
||||
<p class="dossier-val">
|
||||
报文采样延迟:16 ms<br>
|
||||
接收物理通道:USB 串口 (COM3)<br>
|
||||
空域防区告警:无违规侵入 (绿码正常)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">🎯 视口居中追踪</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 本地登记核验</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode B: 调度指挥 (对齐 docs/images/实时目标工作台-调度指挥.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-b">
|
||||
<div class="mode-b-wrap">
|
||||
<div class="mode-b-top">
|
||||
<!-- Top map -->
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1920 600">
|
||||
<rect width="1920" height="600" fill="none"/>
|
||||
<path d="M200 500 Q 800 200 1600 400" fill="none" stroke="rgba(14,40,75,0.4)" stroke-width="70"/>
|
||||
<g transform="translate(850, 240)">
|
||||
<circle cx="0" cy="0" r="26" fill="rgba(10,132,255,0.15)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="32" y="5" fill="#fff" font-size="13" font-weight="700">DEMO-001 (调度跟踪中)</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<!-- Right floating target brief -->
|
||||
<div class="glass-panel" style="position:absolute; right:16px; top:16px; bottom:16px; width:340px; padding:16px; display:flex; flex-direction:column; gap:10px;">
|
||||
<div class="panel-header" style="padding:0 0 8px;">
|
||||
<h3>调度标的 / DEMO-001</h3>
|
||||
<span class="tag tag-blue">实时追踪</span>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">备案比对</div>
|
||||
<p class="dossier-val">已匹配本地登记档案 (张伟)</p>
|
||||
</div>
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">实时航姿</div>
|
||||
<p class="dossier-val">高度 45.2m · 航向 085° · 地速 14.2m/s</p>
|
||||
</div>
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">🎯 锁定追踪</button>
|
||||
<button class="btn btn-secondary">⚠️ 发起协查</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom Event Timeline Dock -->
|
||||
<div class="mode-b-dock">
|
||||
<div class="timeline-pane">
|
||||
<div style="font-size:12px; font-weight:700; color:#fff; margin-bottom:10px; display:flex; justify-content:space-between;">
|
||||
<span>事件时间轴 · 实时调度响应</span>
|
||||
<span style="color:var(--mc-text-dim);font-weight:normal;">突出事件响应与处置流,适合值守调度</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:01</span>
|
||||
<span class="t-badge tag-blue">捕获帧</span>
|
||||
<span class="t-desc">串口捕获新 RID 广播帧:标的 <strong>DEMO-001</strong> (SN: ZEX0RID...)</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:02</span>
|
||||
<span class="t-badge tag-green">匹配成功</span>
|
||||
<span class="t-desc">本地数据库自动匹配成功:机型 5寸穿越机,登记所有人:张伟</span>
|
||||
</div>
|
||||
<div class="timeline-item">
|
||||
<span class="t-time">15:42:15</span>
|
||||
<span class="t-badge tag-amber">异常预警</span>
|
||||
<span class="t-desc">捕获未备案目标 <strong>DEMO-002</strong>,未在本地档案中找到匹配记录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding:14px; background:rgba(9,18,36,0.6); display:flex; flex-direction:column; justify-content:space-between;">
|
||||
<div>
|
||||
<div style="font-weight:700; font-size:12px; color:#fff; margin-bottom:6px;">处置调度操作台</div>
|
||||
<div style="font-size:11px; color:var(--mc-text-dim); line-height:1.5;">
|
||||
对已标记异常的目标,可一键下发至地面巡查班组或联动外置声光设备。
|
||||
</div>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary">📑 导出处置证据</button>
|
||||
<button class="btn btn-secondary">通知值守人</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- Mode C: 目标研判 (对齐 docs/images/实时目标工作台-目标研判.png) -->
|
||||
<!-- ============================================================ -->
|
||||
<div class="layout" id="layout-c">
|
||||
<div class="mode-c-wrap">
|
||||
<!-- Left: Wide directory & search -->
|
||||
<aside class="glass-panel c-column">
|
||||
<div class="panel-header">
|
||||
<h3>目标目录与研判检索</h3>
|
||||
<span class="tag tag-blue">3 标的</span>
|
||||
</div>
|
||||
<div style="padding:12px 14px 6px;">
|
||||
<input type="text" placeholder="🔍 检索 RID / SN / 登记人..." style="width:100%;height:34px;background:rgba(14,25,48,0.7);border:1px solid var(--mc-border);border-radius:6px;color:#fff;padding:0 10px;font-size:12px;outline:none;">
|
||||
</div>
|
||||
<div style="flex:1; overflow-y:auto; padding:6px 14px;">
|
||||
<div class="target-card active">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-001</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: ZEX0RID1202605011000</span><span>张伟</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-002</span><span class="tag tag-red">黑飞未备案</span></div>
|
||||
<div class="tc-sub"><span>SN: UNKNOWN_SN_8891</span><span>无登记</span></div>
|
||||
</div>
|
||||
<div class="target-card">
|
||||
<div class="tc-head"><span class="tc-title">DEMO-003</span><span class="tag tag-green">已匹配</span></div>
|
||||
<div class="tc-sub"><span>SN: DJI_M4P_2026_0991</span><span>李工</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Center: Forensics Map -->
|
||||
<section class="glass-panel c-column" style="position:relative;">
|
||||
<div class="map-container">
|
||||
<svg class="map-canvas-svg" viewBox="0 0 1000 800">
|
||||
<path d="M200 650 L 350 500 L 520 450 L 700 320" fill="none" stroke="#38bdf8" stroke-width="3" stroke-dasharray="6,4"/>
|
||||
<g transform="translate(700, 320)">
|
||||
<circle cx="0" cy="0" r="28" fill="rgba(10,132,255,0.2)" stroke="#38bdf8" stroke-width="2"/>
|
||||
<polygon points="0,-12 8,10 0,6 -8,10" fill="#38bdf8"/>
|
||||
<text x="36" y="5" fill="#fff" font-size="14" font-weight="700">研判标的: DEMO-001</text>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div style="position:absolute; bottom:14px; left:16px; background:rgba(8,15,28,0.85); padding:6px 12px; border-radius:6px; font-size:11px; color:#cbd5e1; border:1px solid var(--mc-border);">
|
||||
天地图卫星航拍 · 航迹点位回放累计:24 帧
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Right: Evidence & Forensics Dossier -->
|
||||
<aside class="glass-panel c-column" style="padding:16px; gap:12px; overflow-y:auto;">
|
||||
<div class="panel-header" style="padding:0 0 8px; border-bottom:1px solid rgba(255,255,255,0.08);">
|
||||
<h3>研判档案卡 · DEMO-001</h3>
|
||||
<span class="tag tag-green">合规标的</span>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">空间几何坐标 (WGS84)</div>
|
||||
<p class="dossier-val">
|
||||
经纬度:120.153820 · 30.287410<br>
|
||||
相对高度:45.2 m (离地估算)<br>
|
||||
椭球高:58.6 m · 航向:085.0°
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">报文时效与物理链路</div>
|
||||
<p class="dossier-val">
|
||||
数据延迟:16 ms<br>
|
||||
输入通道:USB 串口接收解码<br>
|
||||
接收信号强度 (RSSI):-68 dBm
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dossier-card">
|
||||
<div class="dossier-label">研判核验结论</div>
|
||||
<p class="dossier-val" style="color:#4ade80;">
|
||||
✓ 捕获到合规国标 RID 广播数据<br>
|
||||
✓ 模块 SN 与本地数据库登记记录完全匹配<br>
|
||||
✓ 飞手资质与无人机备案照片齐全
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="margin-top:auto;">
|
||||
<button class="btn btn-primary">📑 生成研判报告</button>
|
||||
<a class="btn btn-secondary" href="/" style="text-decoration:none;">📋 调取登记照片</a>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function switchMode(mode, btn) {
|
||||
document.querySelectorAll('.layout').forEach(l => l.classList.remove('active'));
|
||||
document.querySelectorAll('.nav-tab').forEach(b => b.classList.remove('active'));
|
||||
document.getElementById('layout-' + mode).classList.add('active');
|
||||
btn.classList.add('active');
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,7 +1,66 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>FPV-RID 界面方案 · 独立演示</title><style>
|
||||
*{box-sizing:border-box}body{margin:0;font:15px/1.65 system-ui,'Microsoft YaHei',sans-serif;background:#eef3f7;color:#173047}main{max-width:1200px;margin:auto;padding:32px}h1{font-size:26px}h2{font-size:21px;margin:0 0 8px}h3{margin:8px 0}section{background:white;border:1px solid #dce6ee;border-radius:14px;padding:24px;margin:24px 0}p{color:#61788a}.banner{background:#fff4da;color:#6b5011;padding:12px}.tools,.pages,.actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}button,input{font:inherit;border:1px solid #bdcedb;border-radius:6px;padding:7px 12px;background:white;color:inherit}button{cursor:pointer}button:focus-visible{outline:3px solid #206d9f}button.primary{background:#206d9f;color:white}.muted{font-size:13px;color:#61788a}.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}.record,.editor{border:1px solid #dce6ee;padding:16px;border-radius:10px}.photo{display:grid;place-items:center;min-height:90px;background:#edf2f5;color:#61788a}.pages{justify-content:flex-end;margin-top:18px}label{display:block;margin:10px 0}label input{display:block;width:100%}table{width:100%;border-collapse:collapse}td,th{text-align:left;border-bottom:1px solid #dce6ee;padding:12px}.editor{background:#f7fafc}.notice{padding:10px;background:#fff4da}.drawer{display:grid;grid-template-columns:1.3fr 1fr;gap:20px}dialog{border:1px solid #bdcedb;border-radius:12px;max-width:480px;width:90%}@media(max-width:700px){main{padding:14px}.grid,.drawer{grid-template-columns:1fr}.scroll{overflow:auto}section{padding:16px}}
|
||||
</style><main><h1>FPV-RID · 三种操作布局</h1><p class="banner">独立演示,全部为虚构示例,不连接后端或设备,不保存数据。请选择 A / B / C 或明确组合。</p>
|
||||
<section><h2>A · 保留卡片,弹窗编辑</h2><p>延续现有布局,改动较小。照片和档案并排查看;编辑时打开对话框,适合少量日常备案。</p><div class="notice" role="status">数据已保存,档案备份待同步 <button onclick="this.textContent='演示:已请求重试'">重试同步</button></div><div class="grid"><article class="record"><span class="muted">□ 选择当前档案</span><h3>DEMO-SN-001</h3><strong>FPV00000001</strong><p>演示机型 · 演示登记人</p><div class="grid"><div class="photo">照片 1(演示)</div><div class="photo">照片 2 未上传</div></div><div class="actions"><button onclick="document.querySelector('dialog').showModal()">编辑资料 / 照片</button><button>打开档案卡</button></div></article><article class="record"><h3>DEMO-SN-002</h3><strong>FPV00000002</strong><p>第二条示例档案</p><div class="photo">照片未上传</div></article></div><div class="pages"><span>全选仅当前页 · 共 42 条</span><button>上一页</button><span>1 / 3</span><button>下一页</button></div></section>
|
||||
<section><h2>B · 档案表格,右侧编辑区</h2><p>便于快速扫描和比较记录,选中一行后在右侧编辑;照片空间较小,窄屏需要上下排列。</p><div class="drawer"><div class="scroll"><table><tr><th>选择</th><th>模块 SN</th><th>FPV 编号</th></tr><tr><td>□</td><td>DEMO-SN-001</td><td>FPV00000001</td></tr><tr><td>□</td><td>DEMO-SN-002</td><td>FPV00000002</td></tr></table><div class="pages">42 条 <button>上一页</button>1 / 3<button>下一页</button></div></div><div class="editor"><h3>编辑 DEMO-SN-001</h3><span class="muted">SN、FPV 编号不可更改</span><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div class="photo">照片 1(演示)</div><button onclick="this.textContent='演示:保存时删除照片'">删除照片 1</button><p class="notice">备份待同步 <button>重试</button></p><button class="primary">保存修改(演示)</button></div></div></section>
|
||||
<section><h2>C · 卡片内直接展开编辑</h2><p>在档案上下文内编辑,少一次弹窗切换;展开后卡片高度增加,适合逐条整理档案。</p><article class="record"><h3>DEMO-SN-001 · FPV00000001</h3><details open><summary>编辑机型、登记人与照片</summary><div class="grid"><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div><div class="photo">照片 1(演示)</div><label><input type="checkbox" style="display:inline;width:auto"> 删除照片 1</label></div><div><div class="photo">照片 2 未上传</div><button>选择替换照片(演示)</button></div></div><div class="actions"><button class="primary">保存修改(演示)</button><button>取消</button><span class="muted">空文本表示清空;编号保持不变</span></div></details></article><div class="pages"><span>备份待同步</span><button>重试同步</button><span>共 42 条 · 1 / 3</span><button>下一页</button></div></section>
|
||||
<dialog><h2>编辑档案(A 演示)</h2><p>DEMO-SN-001 · FPV00000001 · 编号只读</p><label>机型<input value="演示机型"></label><label>登记人 / 备注<input value="演示登记人"></label><div class="photo">照片 1(演示)</div><label><input type="checkbox" style="display:inline;width:auto"> 删除照片 1</label><p class="muted">文本清空后保存即删除该字段内容。</p><div class="actions"><button class="primary" onclick="this.closest('dialog').close()">演示保存</button><button onclick="this.closest('dialog').close()">取消</button></div></dialog></main></html>
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mission Control · 设备登记方案</title><style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font:14px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC",sans-serif;background:#070e1a;background-image:radial-gradient(circle at 50% 0%,rgba(32,65,199,0.25) 0%,transparent 60%),radial-gradient(circle at 85% 90%,rgba(16,185,129,0.08) 0%,transparent 50%);color:#f8fafc;min-height:100vh}
|
||||
main{max-width:1200px;margin:auto;padding:36px 24px}
|
||||
h1{font-size:26px;color:#fff;margin-top:0}
|
||||
h2{font-size:18px;margin:0 0 8px;color:#fff}
|
||||
h3{margin:8px 0;color:#30b6f5}
|
||||
section{background:rgba(11,22,39,0.76);backdrop-filter:blur(24px) saturate(180%);border:1px solid rgba(64,150,255,0.22);border-radius:16px;padding:26px;margin:24px 0;box-shadow:0 14px 40px rgba(0,0,0,0.5),inset 0 1px 1px rgba(255,255,255,0.15)}
|
||||
p{color:#94a3b8}
|
||||
.banner{background:rgba(255,159,10,0.15);border:1px solid rgba(255,159,10,0.35);color:#ff9f0a;padding:12px 16px;border-radius:10px}
|
||||
.tools,.pages,.actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
button,input{font:inherit;border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:8px 14px;background:rgba(6,12,22,0.65);color:#fff}
|
||||
button{cursor:pointer;transition:all .2s ease}
|
||||
button:hover{background:rgba(48,182,245,0.2);border-color:#30b6f5}
|
||||
button.primary{background:linear-gradient(135deg,#1d4ed8,#0284c7);border-color:rgba(56,189,248,0.5);color:#fff;box-shadow:0 4px 16px rgba(2,132,199,0.4)}
|
||||
.muted{font-size:12px;color:#64748b}
|
||||
.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||
.record,.editor{border:1px solid rgba(64,150,255,0.2);padding:18px;border-radius:12px;background:rgba(8,16,28,0.6)}
|
||||
.photo{display:grid;place-items:center;min-height:90px;background:rgba(0,0,0,0.4);border-radius:8px;color:#64748b;border:1px solid rgba(255,255,255,0.06)}
|
||||
.pages{justify-content:flex-end;margin-top:18px;font-size:12px;color:#94a3b8}
|
||||
label{display:block;margin:10px 0;color:#e2e8f0;font-size:13px}
|
||||
label input{display:block;width:100%;margin-top:6px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
td,th{text-align:left;border-bottom:1px solid rgba(255,255,255,0.08);padding:12px;color:#e2e8f0}
|
||||
th{color:#94a3b8;font-weight:600}
|
||||
.notice{padding:10px 14px;background:rgba(0,230,118,0.15);border:1px solid rgba(0,230,118,0.3);color:#00e676;border-radius:8px}
|
||||
.drawer{display:grid;grid-template-columns:1.3fr 1fr;gap:20px}
|
||||
dialog{border:1px solid rgba(64,150,255,0.3);border-radius:16px;max-width:480px;width:90%;background:rgba(11,22,39,0.92);backdrop-filter:blur(24px);color:#fff;box-shadow:0 24px 80px rgba(0,0,0,0.8)}
|
||||
dialog::backdrop{background:rgba(4,8,16,0.75)}
|
||||
@media(max-width:700px){main{padding:16px}.grid,.drawer{grid-template-columns:1fr}}
|
||||
</style>
|
||||
<main>
|
||||
<h1>Mission Control · 设备登记与档案方案</h1>
|
||||
<p class="banner">独立演示原型 · 遵循 Mission Control 苹果半透明玻璃视觉标准。</p>
|
||||
<section>
|
||||
<h2>A · 独立卡片与弹窗编辑</h2>
|
||||
<p>卡片展示模块 SN 与 FPV 编号,双照片并排查看;点击编辑弹出半透明毛玻璃对话框。</p>
|
||||
<div class="notice">数据已自动备份并在本地加密隔离 <button onclick="this.textContent='已触发同步'">重试同步</button></div>
|
||||
<div class="grid" style="margin-top:16px;">
|
||||
<article class="record">
|
||||
<span class="muted">□ 选中当前记录</span>
|
||||
<h3>DEMO-SN-001</h3>
|
||||
<strong style="color:#30b6f5">FPV00000001</strong>
|
||||
<p>5寸穿越机 · 飞手演示记录</p>
|
||||
<div class="grid"><div class="photo">照片 1(已上传)</div><div class="photo">照片 2 未上传</div></div>
|
||||
<div class="actions" style="margin-top:14px;"><button onclick="document.querySelector('dialog').showModal()">编辑资料 / 照片</button><button>打开档案卡</button></div>
|
||||
</article>
|
||||
<article class="record">
|
||||
<h3>DEMO-SN-002</h3>
|
||||
<strong style="color:#30b6f5">FPV00000002</strong>
|
||||
<p>第二条测试模块档案</p>
|
||||
<div class="photo">照片未上传</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="pages"><span>全选仅当前页 · 共 42 条</span><button>上一页</button><span>1 / 3</span><button>下一页</button></div>
|
||||
</section>
|
||||
<dialog>
|
||||
<h2 style="margin-top:0">编辑档案 (Mission Control Style)</h2>
|
||||
<p>DEMO-SN-001 · FPV00000001 · 模块 SN 保持只读</p>
|
||||
<label>机型<input value="5寸穿越机"></label>
|
||||
<label>登记人 / 备注<input value="演示飞手"></label>
|
||||
<div class="photo" style="margin:12px 0;">照片 1 预览</div>
|
||||
<div class="actions"><button class="primary" onclick="this.closest('dialog').close()">保存修改</button><button onclick="this.closest('dialog').close()">取消</button></div>
|
||||
</dialog>
|
||||
</main>
|
||||
</html>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,383 +0,0 @@
|
||||
const $ = id => document.getElementById(id);
|
||||
let activeRecord = null;
|
||||
let listedRecords = [];
|
||||
const selectedIds = new Set();
|
||||
let listRequestId = 0;
|
||||
let searchTimer;
|
||||
let currentPage = 1;
|
||||
let totalPages = 0;
|
||||
let editingRecord = null;
|
||||
let editBusy = false;
|
||||
|
||||
function updatePageButtons() {
|
||||
$('previous-page').disabled = currentPage <= 1;
|
||||
$('next-page').disabled = currentPage >= totalPages;
|
||||
}
|
||||
|
||||
function archiveStatus(payload) {
|
||||
if (payload.archiveStatus === 'pending') {
|
||||
$('archive-warning').hidden = false;
|
||||
$('archive-warning-text').textContent = payload.warning || '数据已保存,档案备份待同步。';
|
||||
} else if (payload.archiveStatus === 'synced') $('archive-warning').hidden = true;
|
||||
}
|
||||
|
||||
function setMessage(message, error = false) {
|
||||
$('form-message').textContent = message;
|
||||
$('form-message').classList.toggle('error', error);
|
||||
}
|
||||
|
||||
function setHistoryMessage(message, error = false) {
|
||||
$('history-message').textContent = message;
|
||||
$('history-message').classList.toggle('error', error);
|
||||
}
|
||||
|
||||
function updateSelectionControls() {
|
||||
const count = selectedIds.size;
|
||||
$('selected-count').textContent = `(${count})`;
|
||||
$('select-all').checked = listedRecords.length > 0 && count === listedRecords.length;
|
||||
$('select-all').indeterminate = count > 0 && count < listedRecords.length;
|
||||
$('export-archive').disabled = count === 0;
|
||||
$('export-excel').disabled = count === 0;
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
try { return new Date(iso).toLocaleString('zh-CN', { hour12: false }); }
|
||||
catch { return iso; }
|
||||
}
|
||||
|
||||
async function readPhoto(input, slot) {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return null;
|
||||
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) throw new Error(`照片 ${slot} 仅支持 JPG、PNG 或 WebP`);
|
||||
if (file.size > 5 * 1024 * 1024) throw new Error(`照片 ${slot} 不能超过 5 MB`);
|
||||
return await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () => reject(new Error(`照片 ${slot} 读取失败`));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
function drawRecord(record) {
|
||||
activeRecord = record;
|
||||
$('empty-result').hidden = true;
|
||||
$('record-result').hidden = false;
|
||||
$('display-uas').textContent = record.uasCode;
|
||||
$('display-sn').textContent = record.serialNo;
|
||||
$('display-model').textContent = record.modelName || '—';
|
||||
$('display-owner').textContent = record.ownerName || '—';
|
||||
$('display-url').textContent = record.qrUrl;
|
||||
$('open-card').href = record.archiveUrl;
|
||||
$('download-card').href = record.downloadArchiveUrl;
|
||||
$('saved-photos').hidden = !record.photo1Url && !record.photo2Url;
|
||||
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
|
||||
const link = $(`photo-${slot}-link`);
|
||||
link.hidden = !url;
|
||||
if (url) {
|
||||
link.href = url;
|
||||
$(`photo-${slot}-preview`).src = `${url}?v=${Date.now()}`;
|
||||
}
|
||||
}
|
||||
const qr = qrcode(0, 'M');
|
||||
qr.addData(record.qrUrl);
|
||||
qr.make();
|
||||
$('qr-stage').innerHTML = qr.createSvgTag({ cellSize: 6, margin: 4 });
|
||||
}
|
||||
|
||||
async function loadRecords(requestedPage = currentPage) {
|
||||
const requestId = ++listRequestId;
|
||||
const query = $('history-query').value.trim();
|
||||
$('previous-page').disabled = true; $('next-page').disabled = true;
|
||||
let payload;
|
||||
try {
|
||||
const response = await fetch(`/api/records?q=${encodeURIComponent(query)}&page=${requestedPage}&pageSize=20`);
|
||||
payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '读取记录失败');
|
||||
} catch (error) {
|
||||
if (requestId !== listRequestId) return;
|
||||
updatePageButtons();
|
||||
throw error;
|
||||
}
|
||||
if (requestId !== listRequestId) return;
|
||||
totalPages = payload.totalPages;
|
||||
if (requestedPage > Math.max(1, totalPages)) { selectedIds.clear(); return loadRecords(Math.max(1, totalPages)); }
|
||||
currentPage = requestedPage;
|
||||
$('page-status').textContent = `第 ${currentPage} / ${Math.max(1, totalPages)} 页 · 共 ${payload.total} 条`;
|
||||
$('previous-page').disabled = currentPage === 1;
|
||||
$('next-page').disabled = currentPage >= totalPages;
|
||||
const body = $('history-cards');
|
||||
body.replaceChildren();
|
||||
listedRecords = payload.records;
|
||||
$('search-count').textContent = query ? `${payload.total} 条` : '';
|
||||
const currentIds = new Set(listedRecords.map(record => record.id));
|
||||
for (const id of selectedIds) if (!currentIds.has(id)) selectedIds.delete(id);
|
||||
$('history-empty').hidden = listedRecords.length > 0;
|
||||
$('history-empty').textContent = query ? '没有找到匹配的档案。' : '暂无登记记录。';
|
||||
for (const record of listedRecords) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'archive-card';
|
||||
card.classList.toggle('selected', selectedIds.has(record.id));
|
||||
const select = document.createElement('label');
|
||||
select.className = 'archive-select';
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = selectedIds.has(record.id);
|
||||
checkbox.setAttribute('aria-label', `选择档案 ${record.serialNo}`);
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedIds.add(record.id); else selectedIds.delete(record.id);
|
||||
card.classList.toggle('selected', checkbox.checked);
|
||||
updateSelectionControls();
|
||||
});
|
||||
select.append(checkbox, document.createTextNode('导出'));
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = record.serialNo;
|
||||
const code = document.createElement('strong');
|
||||
code.textContent = record.uasCode;
|
||||
const detail = document.createElement('p');
|
||||
detail.textContent = `${record.modelName || '未填机型'} · ${record.ownerName || '未填登记人'} · ${formatTime(record.createdAt)}`;
|
||||
const images = document.createElement('div');
|
||||
images.className = 'archive-thumbs';
|
||||
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
|
||||
const thumb = document.createElement('div');
|
||||
if (url) {
|
||||
const image = document.createElement('img');
|
||||
image.src = url;
|
||||
image.alt = `登记照片 ${slot}`;
|
||||
image.loading = 'lazy';
|
||||
thumb.append(image);
|
||||
} else {
|
||||
thumb.textContent = `照片 ${slot} 未上传`;
|
||||
}
|
||||
images.append(thumb);
|
||||
}
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'archive-actions';
|
||||
const open = document.createElement('a');
|
||||
open.href = record.archiveUrl;
|
||||
open.target = '_blank';
|
||||
open.rel = 'noopener';
|
||||
open.textContent = '打开档案卡';
|
||||
const download = document.createElement('a');
|
||||
download.href = record.downloadArchiveUrl;
|
||||
download.textContent = '下载离线档案卡';
|
||||
const showQr = document.createElement('button');
|
||||
showQr.type = 'button';
|
||||
showQr.textContent = '查看二维码';
|
||||
showQr.addEventListener('click', () => { drawRecord(record); $('result-title').scrollIntoView({ behavior: 'smooth' }); });
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'delete-record';
|
||||
remove.textContent = '删除档案';
|
||||
remove.addEventListener('click', async () => {
|
||||
if (!confirm(`确定删除 ${record.serialNo} 的登记档案和照片吗?`)) return;
|
||||
remove.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/api/records/${record.id}`, { method: 'DELETE' });
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '删除失败');
|
||||
archiveStatus(payload);
|
||||
selectedIds.delete(record.id);
|
||||
if (activeRecord?.id === record.id) {
|
||||
activeRecord = null;
|
||||
$('record-result').hidden = true;
|
||||
$('empty-result').hidden = false;
|
||||
}
|
||||
await loadRecords();
|
||||
setHistoryMessage(`已删除 ${record.serialNo} 的档案。`);
|
||||
} catch (error) { setHistoryMessage(error.message, true); remove.disabled = false; }
|
||||
});
|
||||
const edit = document.createElement('button');
|
||||
edit.type = 'button'; edit.textContent = '编辑资料 / 照片';
|
||||
edit.addEventListener('click', () => openEditor(record));
|
||||
actions.append(edit, open, download, showQr, remove);
|
||||
card.append(select, title, code, detail, images, actions);
|
||||
body.append(card);
|
||||
}
|
||||
updateSelectionControls();
|
||||
}
|
||||
|
||||
$('register-form').addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const button = $('register-button');
|
||||
button.disabled = true;
|
||||
setMessage('正在保存本地记录…');
|
||||
const uasDigits = $('uas-code').value.trim();
|
||||
try {
|
||||
const [photo1, photo2] = await Promise.all([
|
||||
readPhoto($('photo-1'), 1),
|
||||
readPhoto($('photo-2'), 2),
|
||||
]);
|
||||
const response = await fetch('/api/records', {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
serialNo: $('serial-no').value.trim(),
|
||||
modelName: $('model-name').value.trim(),
|
||||
ownerName: $('owner-name').value.trim(),
|
||||
uasCode: uasDigits ? `FPV${uasDigits}` : '',
|
||||
photo1, photo2,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '保存失败');
|
||||
archiveStatus(payload);
|
||||
drawRecord(payload.record);
|
||||
setMessage(payload.existing ? '该 SN 已登记,照片和填写的信息已保存。' : '登记成功,二维码已生成。');
|
||||
await loadRecords();
|
||||
} catch (error) { setMessage(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
|
||||
$('refresh-list').addEventListener('click', () => loadRecords().catch(error => setMessage(error.message, true)));
|
||||
$('history-query').addEventListener('input', () => {
|
||||
clearTimeout(searchTimer);
|
||||
listRequestId++;
|
||||
selectedIds.clear();
|
||||
document.querySelectorAll('.archive-card').forEach(card => {
|
||||
card.classList.remove('selected');
|
||||
card.querySelector('.archive-select input').checked = false;
|
||||
});
|
||||
updateSelectionControls();
|
||||
searchTimer = setTimeout(() => loadRecords(1).catch(error => setHistoryMessage(error.message, true)), 180);
|
||||
});
|
||||
$('select-all').addEventListener('change', event => {
|
||||
selectedIds.clear();
|
||||
if (event.target.checked) for (const record of listedRecords) selectedIds.add(record.id);
|
||||
document.querySelectorAll('.archive-card').forEach((card, index) => {
|
||||
const checked = selectedIds.has(listedRecords[index].id);
|
||||
card.querySelector('.archive-select input').checked = checked;
|
||||
card.classList.toggle('selected', checked);
|
||||
});
|
||||
updateSelectionControls();
|
||||
});
|
||||
|
||||
async function exportSelected(kind) {
|
||||
const ids = [...selectedIds];
|
||||
if (!ids.length) return;
|
||||
const button = $(kind === 'archive' ? 'export-archive' : 'export-excel');
|
||||
button.disabled = true;
|
||||
setHistoryMessage(`正在导出 ${ids.length} 条档案…`);
|
||||
try {
|
||||
const response = await fetch(`/api/export/${kind}`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ ids }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json();
|
||||
throw new Error(payload.error || '导出失败');
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
link.href = url;
|
||||
link.download = kind === 'archive' ? 'FPV-RID-档案库.zip' : 'FPV-RID-登记记录.xlsx';
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
setHistoryMessage(`已导出 ${ids.length} 条档案。`);
|
||||
} catch (error) { setHistoryMessage(error.message, true); }
|
||||
finally { updateSelectionControls(); }
|
||||
}
|
||||
$('export-archive').addEventListener('click', () => exportSelected('archive'));
|
||||
$('export-excel').addEventListener('click', () => exportSelected('excel'));
|
||||
$('copy-url').addEventListener('click', async () => {
|
||||
if (!activeRecord) return;
|
||||
try { await navigator.clipboard.writeText(activeRecord.qrUrl); setMessage('本地二维码链接已复制。'); }
|
||||
catch { setMessage('复制失败,可从“二维码内容”手动复制。', true); }
|
||||
});
|
||||
$('download-qr').addEventListener('click', async () => {
|
||||
if (!activeRecord) return;
|
||||
const svg = $('qr-stage').querySelector('svg');
|
||||
if (!svg) return;
|
||||
const blob = new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = reject; image.src = url; });
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 640; canvas.height = 640;
|
||||
const context = canvas.getContext('2d');
|
||||
context.fillStyle = '#fff'; context.fillRect(0, 0, 640, 640);
|
||||
context.drawImage(image, 0, 0, 640, 640);
|
||||
const link = document.createElement('a');
|
||||
link.href = canvas.toDataURL('image/png');
|
||||
link.download = `${activeRecord.serialNo}-${activeRecord.uasCode}-LOCAL.png`;
|
||||
link.click();
|
||||
} catch { setMessage('二维码图片下载失败。', true); }
|
||||
finally { URL.revokeObjectURL(url); }
|
||||
});
|
||||
|
||||
loadRecords().catch(error => setMessage(error.message, true));
|
||||
fetch('/api/archive/status').then(response => {
|
||||
if (!response.ok) throw new Error('无法读取备份状态');
|
||||
return response.json();
|
||||
}).then(archiveStatus).catch(error => setHistoryMessage(error.message, true));
|
||||
|
||||
for (const [id, delta] of [['previous-page', -1], ['next-page', 1]]) {
|
||||
$(id).addEventListener('click', () => {
|
||||
selectedIds.clear(); updateSelectionControls();
|
||||
document.querySelectorAll('.archive-select input').forEach(input => { input.checked = false; });
|
||||
document.querySelectorAll('.archive-card.selected').forEach(card => card.classList.remove('selected'));
|
||||
loadRecords(currentPage + delta).catch(error => {
|
||||
setHistoryMessage(error.message, true);
|
||||
updatePageButtons();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function openEditor(record) {
|
||||
editingRecord = record; $('edit-form').reset(); $('edit-message').textContent = '';
|
||||
$('edit-identity').textContent = `${record.serialNo} · ${record.uasCode}`;
|
||||
$('edit-model').value = record.modelName; $('edit-owner').value = record.ownerName;
|
||||
for (const slot of [1, 2]) {
|
||||
const url = record[`photo${slot}Url`]; const preview = $(`edit-preview-${slot}`);
|
||||
preview.hidden = !url; if (url) preview.src = `${url}?v=${Date.now()}`; else preview.removeAttribute('src');
|
||||
$(`edit-delete-${slot}`).disabled = !url;
|
||||
}
|
||||
$('edit-dialog').showModal(); $('edit-model').focus();
|
||||
}
|
||||
$('edit-cancel').addEventListener('click', () => $('edit-dialog').close());
|
||||
$('edit-dialog').addEventListener('cancel', event => { if (editBusy) event.preventDefault(); });
|
||||
for (const slot of [1, 2]) {
|
||||
$(`edit-photo-${slot}`).addEventListener('change', () => { if ($(`edit-photo-${slot}`).files.length) $(`edit-delete-${slot}`).checked = false; });
|
||||
$(`edit-delete-${slot}`).addEventListener('change', () => { if ($(`edit-delete-${slot}`).checked) $(`edit-photo-${slot}`).value = ''; });
|
||||
}
|
||||
async function mutation(url, method, body) {
|
||||
const response = await fetch(url, { method, headers: body ? { 'content-type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
|
||||
const payload = await response.json(); if (!response.ok) throw new Error(payload.error || '操作失败');
|
||||
archiveStatus(payload); return payload;
|
||||
}
|
||||
$('edit-form').addEventListener('submit', async event => {
|
||||
event.preventDefault(); const record = editingRecord; if (!record || editBusy) return;
|
||||
editBusy = true;
|
||||
const controls = Array.from($('edit-form').elements);
|
||||
const disabled = controls.map(control => control.disabled);
|
||||
controls.forEach(control => { control.disabled = true; });
|
||||
const body = { modelName: $('edit-model').value.trim(), ownerName: $('edit-owner').value.trim() };
|
||||
const deletes = [1, 2].map(slot => $(`edit-delete-${slot}`).checked);
|
||||
let saved = false;
|
||||
try {
|
||||
// Validate both photos before committing any edits.
|
||||
const photos = await Promise.all([readPhoto($('edit-photo-1'), 1), readPhoto($('edit-photo-2'), 2)]);
|
||||
$('edit-message').textContent = '正在保存…';
|
||||
for (const slot of [1, 2]) {
|
||||
if (deletes[slot - 1]) body[`photo${slot}`] = null;
|
||||
else if (photos[slot - 1]) body[`photo${slot}`] = photos[slot - 1];
|
||||
}
|
||||
const payload = await mutation(`/api/records/${record.id}`, 'PATCH', body);
|
||||
saved = true;
|
||||
if (activeRecord?.id === record.id) drawRecord(payload.record);
|
||||
$('edit-dialog').close();
|
||||
await loadRecords();
|
||||
setHistoryMessage('档案修改已保存。');
|
||||
} catch (error) {
|
||||
if (saved) setHistoryMessage(`修改已保存,但列表刷新失败:${error.message}`, true);
|
||||
else $('edit-message').textContent = `${error.message}。如连接中断,请刷新核对保存结果。`;
|
||||
}
|
||||
finally { controls.forEach((control, index) => { control.disabled = disabled[index]; }); editBusy = false; }
|
||||
});
|
||||
$('retry-archive').addEventListener('click', async () => {
|
||||
$('retry-archive').disabled = true;
|
||||
try { await mutation('/api/archive/retry', 'POST', {}); setHistoryMessage('档案与备份同步完成。'); }
|
||||
catch (error) { $('archive-warning-text').textContent = error.message; }
|
||||
finally { $('retry-archive').disabled = false; }
|
||||
});
|
||||
Vendored
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2009 Kazuhiko Arase
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
-2297
File diff suppressed because it is too large
Load Diff
@@ -2,3 +2,4 @@
|
||||
channel = "1.99.1"
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = ["wasm32-unknown-unknown"]
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
with open('previews/rid-apple-style.html', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Generate rid-apple-b.html
|
||||
b_content = content.replace('class="layout active" id="layout-a"', 'class="layout" id="layout-a"')
|
||||
b_content = b_content.replace('class="layout" id="layout-b"', 'class="layout active" id="layout-b"')
|
||||
b_content = b_content.replace('button class="nav-tab active" onclick="switchMode(\'a\', this)"', 'button class="nav-tab" onclick="switchMode(\'a\', this)"')
|
||||
b_content = b_content.replace('button class="nav-tab" onclick="switchMode(\'b\', this)"', 'button class="nav-tab active" onclick="switchMode(\'b\', this)"')
|
||||
|
||||
with open('previews/rid-apple-b.html', 'w', encoding='utf-8') as f:
|
||||
f.write(b_content)
|
||||
|
||||
# Generate rid-apple-c.html
|
||||
c_content = content.replace('class="layout active" id="layout-a"', 'class="layout" id="layout-a"')
|
||||
c_content = c_content.replace('class="layout" id="layout-c"', 'class="layout active" id="layout-c"')
|
||||
c_content = c_content.replace('button class="nav-tab active" onclick="switchMode(\'a\', this)"', 'button class="nav-tab" onclick="switchMode(\'a\', this)"')
|
||||
c_content = c_content.replace('button class="nav-tab" onclick="switchMode(\'c\', this)"', 'button class="nav-tab active" onclick="switchMode(\'c\', this)"')
|
||||
|
||||
with open('previews/rid-apple-c.html', 'w', encoding='utf-8') as f:
|
||||
f.write(c_content)
|
||||
|
||||
print('Generated clean UTF-8 rid-apple-b.html and rid-apple-c.html successfully')
|
||||
+37
-5
@@ -6,12 +6,12 @@ $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', '启动Rust版.cmd', '使用说明.md', 'qrcode-LICENSE.txt', 'dependency-licenses.txt', 'SHA256SUMS.txt')
|
||||
$ridWhitelist = @('fpv-rid-registry.exe', '启动Rust版.cmd', '使用说明.md', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
|
||||
|
||||
function Assert-CleanDestination {
|
||||
if (Test-Path -LiteralPath $ridDestination) {
|
||||
foreach ($ridEntry in Get-ChildItem -LiteralPath $ridDestination -Force) {
|
||||
if ($ridEntry.PSIsContainer -or $ridEntry.Name -notin $ridWhitelist -or
|
||||
if ($ridEntry.PSIsContainer -or ($ridEntry.Name -notin $ridWhitelist -and $ridEntry.Name -ne 'qrcode-LICENSE.txt') -or
|
||||
($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw "发布目录含运行数据或非发布文件,已停止打包并保留原内容:$($ridEntry.FullName)。请通过 -OutputRoot 指定单独的输出目录。"
|
||||
}
|
||||
@@ -19,25 +19,53 @@ 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 += @('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} })
|
||||
}
|
||||
|
||||
# Refuse a used deployment folder before building or changing any published files.
|
||||
Assert-CleanDestination
|
||||
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
|
||||
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
|
||||
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
|
||||
Push-Location $ridRepo
|
||||
$ridBuildLock = $null
|
||||
$ridOldBuildOwner = $env:RID_PACKAGE_BUILD
|
||||
try {
|
||||
$ridBuildLock = [IO.File]::Open((Join-Path $ridRepo '.build.lock'), [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
|
||||
$env:RID_PACKAGE_BUILD = '1'
|
||||
$ridInitialManifest = @(Get-RidSourceManifest)
|
||||
$ridInitialManifestJson = ConvertTo-Json -InputObject $ridInitialManifest -Depth 5 -Compress
|
||||
cargo xtask web
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Rust frontend build failed' }
|
||||
cargo build --release --locked
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release build failed' }
|
||||
$ridMetadata = cargo metadata --locked --format-version 1 --no-deps | ConvertFrom-Json
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
|
||||
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry.exe') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
|
||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'registry/web/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'qrcode-LICENSE.txt')
|
||||
$ridLicenses = cargo tree --locked --prefix none --format '{p} {l}'
|
||||
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' }
|
||||
$ridLicenses | Set-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
|
||||
Get-Content -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
|
||||
$ridSourceManifest = @(Get-RidSourceManifest)
|
||||
if ((ConvertTo-Json -InputObject $ridSourceManifest -Depth 5 -Compress) -ne $ridInitialManifestJson) { throw '源码在构建期间发生变化,已停止发布并保留原发布包;请在源码稳定后重新构建。' }
|
||||
$ridBuildInfo = [ordered]@{
|
||||
builtAtUtc=[DateTime]::UtcNow.ToString('o')
|
||||
gitRevision=(git rev-parse HEAD)
|
||||
workingTreeDirty=[bool](git status --porcelain)
|
||||
rust=(rustc --version)
|
||||
trunk='0.22.0'
|
||||
wasmBindgen='0.2.129'
|
||||
executableSha256=(Get-FileHash -LiteralPath (Join-Path $ridStage 'fpv-rid-registry.exe') -Algorithm SHA256).Hash
|
||||
sourceManifest=$ridSourceManifest
|
||||
}
|
||||
$ridBuildInfo | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $ridStage 'build-info.json') -Encoding utf8
|
||||
$ridWhitelist | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
|
||||
'{0} {1}' -f (Get-FileHash -LiteralPath (Join-Path $ridStage $_) -Algorithm SHA256).Hash, $_
|
||||
} | Set-Content -LiteralPath (Join-Path $ridStage 'SHA256SUMS.txt') -Encoding utf8
|
||||
@@ -53,6 +81,8 @@ try {
|
||||
foreach ($ridName in $ridWhitelist) {
|
||||
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination (Join-Path $ridDestination $ridName)
|
||||
}
|
||||
$ridObsoleteLicense = Join-Path $ridDestination 'qrcode-LICENSE.txt'
|
||||
if (Test-Path -LiteralPath $ridObsoleteLicense -PathType Leaf) { Remove-Item -LiteralPath $ridObsoleteLicense }
|
||||
$ridZip = Join-Path $ridOutputRoot 'FPV-RID-Rust-Windows-x64.zip'
|
||||
Move-Item -LiteralPath $ridTemporaryZip -Destination $ridZip -Force
|
||||
'{0} FPV-RID-Rust-Windows-x64.zip' -f (Get-FileHash -LiteralPath $ridZip -Algorithm SHA256).Hash |
|
||||
@@ -60,6 +90,8 @@ try {
|
||||
Write-Output $ridDestination
|
||||
Write-Output $ridZip
|
||||
} finally {
|
||||
$env:RID_PACKAGE_BUILD = $ridOldBuildOwner
|
||||
if ($ridBuildLock) { $ridBuildLock.Dispose() }
|
||||
Pop-Location
|
||||
# Clean only files this invocation created. Never recursively delete an output directory.
|
||||
foreach ($ridName in $ridWhitelist) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import assert from 'node:assert/strict';
|
||||
const require=createRequire(import.meta.url);
|
||||
const {chromium}=require('playwright');
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-浏览器验收-'));
|
||||
const exe=path.resolve(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry.exe');
|
||||
const exe=path.resolve(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe');
|
||||
const base='http://127.0.0.1:8787';
|
||||
try{const r=await fetch(base);if(r)throw Error('8787 已有服务,请先关闭');}catch(e){if(e.message.includes('已有服务'))throw e;}
|
||||
await mkdir(path.join(root,'registry/data'),{recursive:true});
|
||||
|
||||
+20
-17
@@ -1,18 +1,21 @@
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
// Regression tests against the actual Rust/Wasm frontend, not copied JavaScript functions.
|
||||
import {mkdtemp} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {createRequire} from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
const source=fs.readFileSync(new URL('../registry/web/app.js',import.meta.url),'utf8');
|
||||
const elements=new Map();
|
||||
const $=id=>{if(!elements.has(id))elements.set(id,{textContent:'',value:'',disabled:false,checked:false,classList:{toggle(){},remove(){}},replaceChildren(){},append(){}});return elements.get(id);};
|
||||
const context={$,currentPage:1,totalPages:3,listRequestId:0,selectedIds:new Set(),listedRecords:[],document:{createElement(){throw Error('unexpected record rendering');}},updateSelectionControls(){},fetch:async()=>{throw Error('network failure');}};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(source.slice(source.indexOf('function updatePageButtons'),source.indexOf('function archiveStatus')),context);
|
||||
vm.runInContext(source.slice(source.indexOf('async function loadRecords'),source.indexOf("$('register-form')")),context);
|
||||
await assert.rejects(context.loadRecords(2),/network failure/);assert.equal(context.currentPage,1);assert.equal($('next-page').disabled,false);
|
||||
let calls=[];
|
||||
context.fetch=async url=>{calls.push(url);return{ok:true,json:async()=>({records:[],page:2,pageSize:20,total:45,totalPages:3})};};
|
||||
await context.loadRecords(2);assert.equal(context.currentPage,2);assert.match(calls[0],/page=2&/);
|
||||
let releaseOld;context.fetch=()=>new Promise(resolve=>releaseOld=resolve);const older=context.loadRecords(1);
|
||||
context.fetch=async()=>({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await context.loadRecords(3);
|
||||
releaseOld({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await older;assert.equal(context.currentPage,3);
|
||||
console.log('PASS: failed pagination retains page, successful page commits, stale response ignored');
|
||||
const require=createRequire(import.meta.url);const {chromium}=require('playwright');
|
||||
const base='http://127.0.0.1:8787';let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}if(occupied)throw Error('8787 occupied');
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-pagination-'));
|
||||
const child=spawn(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe',['--data-root',root],{windowsHide:true,stdio:['ignore','pipe','pipe']});let output='',failure;child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>failure=e);let browser;
|
||||
try{
|
||||
let ready=false;for(let i=0;i<150;i++){if(failure||child.exitCode!==null)throw Error(output||String(failure));try{if((await fetch(base)).ok){ready=true;break;}}catch{}await new Promise(r=>setTimeout(r,100));}assert.ok(ready);
|
||||
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files/Google/Chrome/Application/chrome.exe'});const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));let fail=false;
|
||||
await page.route('**/api/records?**',async route=>{const u=new URL(route.request().url());if(u.searchParams.get('q')==='old')await new Promise(r=>setTimeout(r,800));if(fail){fail=false;await route.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'network failure'})});return;}await route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({records:[],page:Number(u.searchParams.get('page')),pageSize:20,total:u.searchParams.get('q')==='old'?999:45,totalPages:3})});});
|
||||
await page.goto(base);await page.locator('#page-status').filter({hasText:'第 1 / 3 页'}).waitFor();
|
||||
fail=true;await page.click('#next-page');await page.locator('#history-message').filter({hasText:'network failure'}).waitFor();assert.match(await page.locator('#page-status').textContent(),/第 1/);assert.equal(await page.locator('#next-page').isEnabled(),true);
|
||||
await page.click('#next-page');await page.locator('#page-status').filter({hasText:'第 2 / 3 页'}).waitFor();
|
||||
await page.fill('#history-query','old');await page.waitForRequest(r=>r.url().includes('q=old'));await page.fill('#history-query','new');await page.locator('#page-status').filter({hasText:'共 45 条'}).waitFor();await page.waitForTimeout(1000);assert.ok(!(await page.locator('#page-status').textContent()).includes('999'));assert.deepEqual(errors,[]);
|
||||
console.log(JSON.stringify({status:'PASS',root,scenarios:['failed page retains index','successful page commits','old search response ignored','actual Rust/Wasm frontend']}));
|
||||
}finally{if(browser)await browser.close();if(child.exitCode===null&&!failure){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Offline resources use an isolated data root; no TianDiTu key or Internet is needed.
|
||||
import {mkdtemp,mkdir,writeFile} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {DatabaseSync} from 'node:sqlite';
|
||||
import assert from 'node:assert/strict';
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-maps-'));
|
||||
const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=','base64');
|
||||
await mkdir(path.join(root,'maps/offline/vec_w/2/1'),{recursive:true});await writeFile(path.join(root,'maps/offline/vec_w/2/1/2.png'),png);
|
||||
const db=new DatabaseSync(path.join(root,'maps/offline/cva_w.mbtiles'));db.exec('CREATE TABLE tiles(zoom_level INTEGER,tile_column INTEGER,tile_row INTEGER,tile_data BLOB)');db.prepare('INSERT INTO tiles VALUES(2,1,1,?)').run(png);db.close();
|
||||
const base='http://127.0.0.1:8787';let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}if(occupied)throw Error('8787 occupied');
|
||||
const env={...process.env};delete env.TIANDITU_TOKEN;
|
||||
const child=spawn(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe',['--data-root',root],{env,windowsHide:true,stdio:['ignore','pipe','pipe']});let output='',failure;child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>failure=e);
|
||||
try{
|
||||
let ready=false;for(let i=0;i<150;i++){if(failure||child.exitCode!==null)throw Error(output||String(failure));try{if((await fetch(base+'/api/maps/status')).ok){ready=true;break;}}catch{}await new Promise(r=>setTimeout(r,100));}assert.ok(ready);
|
||||
const status=await(await fetch(base+'/api/maps/status')).json();assert.equal(status.keyConfigured,false);assert.equal(status.mode,'offline');
|
||||
for(const layer of ['vec_w','cva_w']){const r=await fetch(base+`/api/maps/tile/${layer}/2/1/2`);assert.equal(r.status,200);assert.equal(r.headers.get('content-type'),'image/png');assert.equal(r.headers.get('x-map-source'),'offline');assert.deepEqual(Buffer.from(await r.arrayBuffer()),png);}
|
||||
assert.equal((await fetch(base+'/api/maps/tile/vec_w/19/0/0')).status,400);assert.equal((await fetch(base+'/api/maps/tile/unknown/2/1/2')).status,400);
|
||||
assert.equal((await fetch(base+'/api/maps/tile/vec_w/2/1/2',{headers:{origin:'https://foreign.example'}})).status,403);assert.equal((await fetch(base+'/api/maps/tile/vec_w/2/1/2',{headers:{'sec-fetch-site':'cross-site'}})).status,403);
|
||||
const missing=await fetch(base+'/api/maps/tile/vec_w/2/0/0');assert.equal(missing.status,404);assert.equal(missing.headers.get('cache-control'),'no-store');
|
||||
console.log(JSON.stringify({status:'PASS',root,scenarios:['offline XYZ raster bytes','MBTiles TMS row inversion','no-key offline mode','coordinate bounds','origin restriction','missing tiles not faked']}));
|
||||
}finally{if(child.exitCode===null&&!failure){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -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','启动Rust版.cmd','使用说明.md','qrcode-LICENSE.txt','dependency-licenses.txt','SHA256SUMS.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
|
||||
$ridExpected = @('fpv-rid-registry.exe','启动Rust版.cmd','使用说明.md','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() }
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// Isolated real server + browser/Worker/GPU integration. Never uses production data.
|
||||
import {mkdtemp,writeFile} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawn,execFileSync} from 'node:child_process';
|
||||
import {createRequire} from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
const require=createRequire(import.meta.url);const {chromium}=require('playwright');
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-realtime-'));
|
||||
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||||
const count=Number(process.env.RID_TARGETS||1000);const duration=Number(process.env.RID_SOAK_SECONDS||10);
|
||||
assert.ok(count>0&&count<=10000&&duration>0&&duration<=7200);
|
||||
const base='http://127.0.0.1:8787';
|
||||
let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
|
||||
if(occupied)throw Error('8787 occupied; refusing to attach to another server');
|
||||
const child=spawn(exe,['--data-root',root,'--simulation-api'],{windowsHide:true,stdio:['ignore','pipe','pipe']});let output='';let failure;
|
||||
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>failure=e);let browser;let monitorHandle;let simulatorProcess;
|
||||
try{
|
||||
let ready=false;for(let i=0;i<150;i++){if(failure||child.exitCode!==null)throw Error(output||String(failure));try{if((await fetch(base+'/api/realtime/status')).ok){ready=true;break;}}catch{}await new Promise(r=>setTimeout(r,100));}assert.ok(ready);
|
||||
const bad=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json',origin:'https://foreign.example'},body:'[]'});assert.equal(bad.status,403);
|
||||
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files/Google/Chrome/Application/chrome.exe'});
|
||||
const page=await browser.newPage({viewport:{width:1440,height:940}});const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
|
||||
let accepted=0,sequence=0;const started=performance.now();const latency=[];
|
||||
const samples=[];let lastProgress=0;
|
||||
if(duration>=60)console.log(JSON.stringify({started:{root,targets:count,durationSeconds:duration,inputFormat:process.env.RID_INPUT_FORMAT||'json'}}));
|
||||
let simulationReport=null;
|
||||
const performanceSession=await page.context().newCDPSession(page);await performanceSession.send('Performance.enable');
|
||||
let sampling=false;const monitor=monitorHandle=setInterval(async()=>{if(sampling)return;sampling=true;try{const m=await performanceSession.send('Performance.getMetrics');const status=await(await fetch(base+'/api/realtime/status')).json();const env={...process.env};delete env.PSModulePath;const privateBytes=Number(execFileSync('powershell',['-NoProfile','-Command',`(Get-Process -Id ${child.pid}).PrivateMemorySize64`],{encoding:'utf8',windowsHide:true,env}).trim());const sample={elapsedMs:performance.now()-started,serverPrivateBytes:privateBytes,browserJsHeapBytes:m.metrics.find(x=>x.name==='JSHeapUsedSize')?.value,activeTargets:status.metrics.active_targets,accepted:status.metrics.accepted};sample.map=await page.evaluate(()=>window.ridMap.metrics());samples.push(sample);if(duration>=60){await writeFile(path.join(root,'progress.json'),JSON.stringify(sample));if(sample.elapsedMs-lastProgress>=60000){lastProgress=sample.elapsedMs;console.log(JSON.stringify({progress:sample}));}}}catch(e){samples.push({samplingError:String(e)});}finally{sampling=false;}},10000);
|
||||
|
||||
if(process.env.RID_INPUT_FORMAT==='binary'){
|
||||
const simulator=simulatorProcess=spawn(path.join(path.dirname(exe),'rid-simulator.exe'),['--targets',String(count),'--interval-ms',process.env.RID_INTERVAL_MS||'10','--seconds',String(duration)],{windowsHide:true,stdio:['ignore','pipe','pipe']});let result='',errors='';simulator.stdout.on('data',b=>result+=b);simulator.stderr.on('data',b=>errors+=b);const finished=new Promise((resolve,reject)=>{simulator.once('exit',resolve);simulator.once('error',reject)});await page.getByRole('button',{name:'SIM-00000',exact:true}).waitFor();await page.getByRole('button',{name:'SIM-00000',exact:true}).click();const code=await finished;assert.equal(code,0,errors);simulationReport=JSON.parse(result.trim());sequence=simulationReport.ticks;accepted=(await(await fetch(base+'/api/realtime/status')).json()).metrics.accepted;
|
||||
}
|
||||
while(!simulationReport&&performance.now()-started<duration*1000){
|
||||
sequence++;const t=performance.now();
|
||||
for(let offset=0;offset<count;offset+=1000){
|
||||
const batch=Array.from({length:Math.min(1000,count-offset)},(_,j)=>{const i=offset+j;return {target_id:`SIM-${String(i).padStart(5,'0')}`,receiver_id:'SIM',source_epoch:1,sequence,longitude:120+Math.cos(i)*.1+Math.sin(sequence*.01)*.005,latitude:30+Math.sin(i)*.1,altitude_m:100,heading_deg:i%360};});
|
||||
const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(batch)});assert.equal(r.status,200);accepted+=(await r.json()).accepted;
|
||||
}
|
||||
latency.push(performance.now()-t);
|
||||
if(sequence%10===0)samples.push({elapsedMs:performance.now()-started,generatorRssBytes:process.memoryUsage().rss});
|
||||
await new Promise(r=>setTimeout(r,10));
|
||||
}
|
||||
clearInterval(monitor);while(sampling)await new Promise(r=>setTimeout(r,50));
|
||||
await page.getByText(`在线目标 ${count} ·`,{exact:false}).waitFor();
|
||||
assert.equal(await page.locator('.rt-target').count(),Math.min(count,100));
|
||||
if(count>100){await page.getByRole('button',{name:'下一组',exact:true}).click();await page.getByRole('button',{name:'SIM-00100',exact:true}).waitFor();}
|
||||
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('SIM-00000');await page.getByRole('button',{name:'SIM-00000',exact:true}).click();
|
||||
await page.locator('.rt-details').filter({hasText:'120.'}).waitFor();
|
||||
const snapshot=await(await fetch(base+'/api/realtime/snapshot')).json();assert.equal(snapshot.targets.length,count);assert.ok(snapshot.targets[0].observation.source_epoch>=1);
|
||||
const duplicate=snapshot.targets[0].observation;const dup=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify([duplicate])});assert.equal((await dup.json()).accepted,0);
|
||||
await page.screenshot({path:path.join(root,'realtime-C.png'),fullPage:true});
|
||||
const map=await page.evaluate(()=>window.ridMap.metrics());assert.equal(map.targets,count);const canvas=await page.locator('.maplibregl-canvas').boundingBox();assert.ok(canvas.width>500&&canvas.height>300,JSON.stringify(canvas));
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
const status=await(await fetch(base+'/api/realtime/status')).json();assert.equal(status.metrics.active_targets,count);
|
||||
assert.deepEqual(errors,[]);
|
||||
latency.sort((a,b)=>a-b);
|
||||
const memorySamples=samples.filter(s=>Number.isFinite(s.serverPrivateBytes));
|
||||
const memory={samples:memorySamples.length,maxServerPrivateBytes:Math.max(0,...memorySamples.map(s=>s.serverPrivateBytes)),maxBrowserJsHeapBytes:Math.max(0,...memorySamples.map(s=>s.browserJsHeapBytes||0)),maxWorkerWasmBytes:Math.max(0,...memorySamples.map(s=>s.map?.workerWasmBytes||0))};
|
||||
if(duration>=600){assert.ok(memorySamples.length>=duration/15);assert.ok(memory.maxServerPrivateBytes<512*1024*1024);assert.ok(memory.maxBrowserJsHeapBytes<256*1024*1024);assert.ok(memory.maxWorkerWasmBytes<128*1024*1024);const warm=memorySamples.filter(s=>s.elapsedMs>=Math.min(300000,duration*500));memory.afterWarmServerSpreadBytes=Math.max(...warm.map(s=>s.serverPrivateBytes))-Math.min(...warm.map(s=>s.serverPrivateBytes));assert.ok(memory.afterWarmServerSpreadBytes<64*1024*1024);}
|
||||
const report={status:'PASS',root,kind:simulationReport?'synthetic-Postcard-ingest-and-real-Rust-worker-map':'synthetic-JSON-ingest-and-real-Rust-worker-map',targets:count,accepted,batches:sequence,durationSeconds:(performance.now()-started)/1000,inputRoundP95Ms:latency[Math.floor(latency.length*.95)]??null,simulationReport,map,memory,metrics:status.metrics,samples,note:'Not a device-to-screen latency certification. Input is synthetic HTTP JSON or Postcard; generator shares this machine. Draw submission intervals are not GPU frame time.'};
|
||||
await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({...report,samples:samples.length}));
|
||||
}finally{clearInterval(monitorHandle);if(simulatorProcess&&simulatorProcess.exitCode===null)simulatorProcess.kill();if(browser)await browser.close();if(child.exitCode===null&&!failure){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -0,0 +1,33 @@
|
||||
// End-to-end transport configuration, without opening any physical serial port.
|
||||
import {mkdtemp,readFile,writeFile} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import dgram from 'node:dgram';
|
||||
import net from 'node:net';
|
||||
import assert from 'node:assert/strict';
|
||||
const root=await mkdtemp(path.join(tmpdir(),'RID-receiver-'));const base='http://127.0.0.1:8787';
|
||||
let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}if(occupied)throw Error('8787 occupied');
|
||||
const child=spawn(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe',['--data-root',root],{windowsHide:true,stdio:['ignore','pipe','pipe']});let output='',failure;child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>failure=e);
|
||||
const packet={target_id:'TEST-NET-001',receiver_id:'TEST-RECEIVER',source_epoch:1,sequence:1,longitude:120.1,latitude:30,altitude_m:100,heading_deg:90};
|
||||
async function poll(test){for(let i=0;i<100;i++){if(await test())return;await new Promise(r=>setTimeout(r,30));}throw Error('receiver state timeout '+output);}
|
||||
async function save(config,expected=200){const r=await fetch(base+'/api/receiver/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(config)});assert.equal(r.status,expected);return r;}
|
||||
try{
|
||||
await poll(async()=>{if(failure||child.exitCode!==null)throw Error(output||String(failure));try{return(await fetch(base+'/api/receiver/status')).ok;}catch{return false;}});
|
||||
const initial=await(await fetch(base+'/api/receiver/config')).json();assert.equal(initial.enabled,false);assert.equal(initial.format,'raw');
|
||||
await save({...initial,enabled:true,serialPort:'../../invalid-file'},400);
|
||||
const probe=dgram.createSocket('udp4');await new Promise(r=>probe.bind(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));
|
||||
const config={...initial,enabled:true,transport:'udp',format:'json-lines',bindIp:'127.0.0.1',port};await save(config);
|
||||
await poll(async()=>(await(await fetch(base+'/api/receiver/status')).json()).state==='udp-listening');
|
||||
const udp=dgram.createSocket('udp4');await new Promise((resolve,reject)=>udp.send(Buffer.from(JSON.stringify(packet)),port,'127.0.0.1',e=>e?reject(e):resolve()));udp.close();
|
||||
await poll(async()=>(await(await fetch(base+'/api/realtime/snapshot')).json()).targets.some(t=>t.observation.target_id===packet.target_id));
|
||||
await save({...config,transport:'tcp-listen'});await poll(async()=>(await(await fetch(base+'/api/receiver/status')).json()).state==='tcp-listening');
|
||||
const released=dgram.createSocket('udp4');await new Promise((resolve,reject)=>{released.once('error',reject);released.bind(port,'127.0.0.1',resolve)});released.close();
|
||||
const tcp=net.createConnection({host:'127.0.0.1',port});await new Promise((resolve,reject)=>{tcp.once('connect',resolve);tcp.once('error',reject)});const bytes=JSON.stringify({...packet,sequence:2,longitude:120.2})+'\n';tcp.write(bytes.slice(0,10));await new Promise(r=>setTimeout(r,5));tcp.end(bytes.slice(10));
|
||||
await poll(async()=>(await(await fetch(base+'/api/realtime/snapshot')).json()).targets.some(t=>t.observation.sequence===2));
|
||||
await save({...config,transport:'tcp-listen',enabled:false});assert.equal((await(await fetch(base+'/api/receiver/status')).json()).state,'stopped');
|
||||
const capture=await(await fetch(base+'/api/receiver/capture')).json();assert.ok(capture.bytes>0&&capture.bytes<=4096);assert.ok(capture.data.length>0);
|
||||
const persisted=JSON.parse(await readFile(path.join(root,'receiver-config.json'),'utf8'));assert.equal(persisted.enabled,false);assert.equal(persisted.transport,'tcp-listen');
|
||||
const foreign=await fetch(base+'/api/receiver/config',{method:'POST',headers:{'content-type':'application/json',origin:'https://foreign.example'},body:JSON.stringify(config)});assert.equal(foreign.status,403);
|
||||
console.log(JSON.stringify({status:'PASS',root,scenarios:['disabled and raw defaults','invalid serial path rejected without device access','UDP JSON input','TCP fragmented JSON input','switch releases UDP socket','disable stops listener','bounded capture retained on stop','configuration persisted','origin restriction']}));
|
||||
}finally{if(child.exitCode===null&&!failure){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}await writeFile(path.join(root,'server.log'),output);}
|
||||
@@ -11,7 +11,7 @@ const child=spawn(exe,[],{cwd:root,windowsHide:true,env:{...process.env,PATH:'C:
|
||||
try{
|
||||
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch('http://127.0.0.1:8787/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
|
||||
await access(path.join(app,'registry/data/registry.sqlite'));await assert.rejects(access(path.join(root,'registry/data/registry.sqlite')));
|
||||
const page=await fetch('http://127.0.0.1:8787/');assert.equal(page.status,200);assert.match(await page.text(),/edit-dialog/);
|
||||
const page=await fetch('http://127.0.0.1:8787/');assert.equal(page.status,200);assert.match(await page.text(),/bootstrap|rid-web-ui|wasm/);
|
||||
const second=spawn(exe,['--data-root',path.join(root,'第二实例')],{windowsHide:true,stdio:['ignore','pipe','pipe']});let stderr='';second.stderr.on('data',b=>stderr+=b);const code=await new Promise((resolve,reject)=>{second.on('exit',resolve);second.on('error',reject);});assert.notEqual(code,0);assert.match(stderr,/8787/);await assert.rejects(access(path.join(root,'第二实例/registry/data/registry.sqlite')));
|
||||
console.log(JSON.stringify({status:'PASS',root,scenarios:['published exe','Chinese install path','different working directory','no Node PATH','embedded webpage','port conflict without new database']}));
|
||||
}finally{if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}}
|
||||
|
||||
+2
-4
@@ -2,7 +2,7 @@
|
||||
import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawn,execFileSync} from 'node:child_process';
|
||||
import {spawn} from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
import {DatabaseSync} from 'node:sqlite';
|
||||
import {inflateRawSync} from 'node:zlib';
|
||||
@@ -55,9 +55,7 @@ async function exports(id,label){
|
||||
const r=await fetch(base+`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('<测试>'));
|
||||
}
|
||||
try{
|
||||
const cargo=process.env.CARGO_HOME?path.join(process.env.CARGO_HOME,'bin/cargo.exe'):'D:/Rust_Contact/util/cargo/bin/cargo.exe';
|
||||
const metadata=process.argv[2]?null:JSON.parse(execFileSync(cargo,['metadata','--format-version','1','--no-deps'],{cwd:repo,encoding:'utf8',windowsHide:true}));
|
||||
const exe=path.resolve(process.argv[2]||path.join(metadata.target_directory,'release/fpv-rid-registry.exe'));
|
||||
const exe=path.resolve(process.argv[2]||path.join(repo,'dist/FPV-RID-Rust/fpv-rid-registry.exe'));
|
||||
await start(exe,['--data-root',root]);
|
||||
const a=await api('/api/records','POST',{serialNo:'TEST-SN-001',uasCode:'FPV00000001',modelName:'<测试>',ownerName:'原登记人',photo1:png});
|
||||
const id=a.record.id;assert.match(id,/^[0-9a-f]{36}$/);assert.equal(a.existing,false);
|
||||
|
||||
+23
-17
@@ -1,18 +1,24 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{serialNo}} · 本地档案卡</title><style>
|
||||
*{box-sizing:border-box}body{font-family:system-ui,"Microsoft YaHei",sans-serif;background:#edf2f7;color:#173047;margin:0;padding:36px 18px}
|
||||
main{max-width:760px;margin:auto;background:#fff;border:1px solid #dce6f0;border-radius:20px;padding:36px;box-shadow:0 12px 40px #1a385015}
|
||||
.tag{display:inline-block;background:#e7f4ec;color:#25734a;border-radius:999px;padding:7px 13px;font-size:12px;font-weight:700}
|
||||
h1{font-size:26px;margin:22px 0 6px}.code{font-size:19px;color:#1c6595;font-weight:800;letter-spacing:.04em}
|
||||
.note{color:#7a8c9b;font-size:12px;line-height:1.6;margin:12px 0 24px}
|
||||
dl{display:grid;grid-template-columns:125px 1fr;gap:15px;border-top:1px solid #e5ebf0;padding-top:22px;margin:0}
|
||||
dt{color:#63768a}dd{margin:0;font-weight:700;overflow-wrap:anywhere}
|
||||
h2{font-size:16px;margin:30px 0 14px}.photos{display:grid;grid-template-columns:1fr 1fr;gap:14px}
|
||||
figure{margin:0;border:1px solid #e1e8ee;border-radius:11px;overflow:hidden}figure img,.no-photo{width:100%;height:245px;object-fit:contain;background:#f4f7fa}
|
||||
.no-photo{display:grid;place-items:center;color:#9aabb8;font-size:13px}figcaption{padding:10px 12px;font-size:12px;color:#63768a}
|
||||
footer{border-top:1px solid #e5ebf0;margin-top:26px;padding-top:15px;color:#98a7b3;font-size:11px;overflow-wrap:anywhere}
|
||||
@media(max-width:540px){main{padding:22px}.photos{grid-template-columns:1fr}dl{grid-template-columns:90px 1fr}}
|
||||
@media print{body{background:#fff;padding:0}main{box-shadow:none;border:0;max-width:none}}
|
||||
</style></head><body><main><span class="tag">本地备案档案卡</span><h1>{{serialNo}}</h1><div class="code">{{uasCode}}</div>
|
||||
<p class="note">本档案卡由 FPV-RID 本地登记软件保存,可离线打开。</p>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{serialNo}} · 本地档案卡 · Mission Control</title><style>
|
||||
*{box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;background:#070e1a;background-image:radial-gradient(circle at 50% 0%,rgba(32,65,199,0.3) 0%,transparent 60%),radial-gradient(circle at 85% 90%,rgba(16,185,129,0.1) 0%,transparent 50%);color:#f8fafc;margin:0;padding:40px 20px;min-height:100vh}
|
||||
main{max-width:780px;margin:auto;background:rgba(11,22,39,0.85);backdrop-filter:blur(24px) saturate(180%);-webkit-backdrop-filter:blur(24px) saturate(180%);border:1px solid rgba(64,150,255,0.25);border-radius:20px;padding:40px;box-shadow:0 20px 60px rgba(0,0,0,0.6),inset 0 1px 1px rgba(255,255,255,0.15)}
|
||||
.tag{display:inline-flex;align-items:center;gap:6px;background:rgba(0,230,118,0.15);color:#00e676;border:1px solid rgba(0,230,118,0.35);border-radius:9999px;padding:6px 14px;font-size:12px;font-weight:700;box-shadow:0 0 12px rgba(0,230,118,0.2)}
|
||||
.tag i{display:inline-block;width:6px;height:6px;border-radius:50%;background:#00e676;box-shadow:0 0 6px #00e676}
|
||||
h1{font-size:28px;margin:20px 0 6px;color:#fff;font-weight:800;letter-spacing:-0.02em}
|
||||
.code{font-size:20px;color:#30b6f5;font-weight:800;letter-spacing:.04em;font-family:monospace;text-shadow:0 0 10px rgba(48,182,245,0.35)}
|
||||
.note{color:#94a3b8;font-size:12px;line-height:1.6;margin:12px 0 24px}
|
||||
dl{display:grid;grid-template-columns:130px 1fr;gap:14px;border-top:1px solid rgba(255,255,255,0.08);padding-top:22px;margin:0}
|
||||
dt{color:#94a3b8;font-size:13px}dd{margin:0;font-weight:700;overflow-wrap:anywhere;color:#fff;font-size:13px}
|
||||
h2{font-size:16px;margin:32px 0 14px;color:#30b6f5;font-weight:700;letter-spacing:0.02em}
|
||||
.photos{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||
figure{margin:0;border:1px solid rgba(64,150,255,0.2);border-radius:12px;overflow:hidden;background:rgba(6,12,22,0.6)}
|
||||
figure img,.no-photo{width:100%;height:250px;object-fit:contain;background:rgba(0,0,0,0.5);display:block}
|
||||
.no-photo{display:grid;place-items:center;color:#64748b;font-size:13px}
|
||||
figcaption{padding:10px 14px;font-size:12px;color:#94a3b8;border-top:1px solid rgba(255,255,255,0.06);background:rgba(14,26,46,0.4)}
|
||||
footer{border-top:1px solid rgba(255,255,255,0.08);margin-top:28px;padding-top:16px;color:#64748b;font-size:11px;overflow-wrap:anywhere}
|
||||
@media(max-width:560px){main{padding:24px}.photos{grid-template-columns:1fr}dl{grid-template-columns:95px 1fr}}
|
||||
@media print{body{background:#fff;color:#000;padding:0}main{box-shadow:none;border:0;max-width:none;background:#fff;color:#000}h1,dd{color:#000}.code{color:#0066cc}.tag{background:#e7f4ec;color:#25734a;border-color:#b8e2cb}figure{border-color:#ccc}figure img,.no-photo{background:#f4f7fa}}
|
||||
</style></head><body><main><span class="tag"><i></i> 本地备案档案卡</span><h1>{{serialNo}}</h1><div class="code">{{uasCode}}</div>
|
||||
<p class="note">本档案卡由 FPV-RID 本地登记软件导出保存,支持离线打开与真伪核查。</p>
|
||||
<dl><dt>模块 SN</dt><dd>{{serialNo}}</dd><dt>FPV 编号</dt><dd>{{uasCode}}</dd><dt>机型</dt><dd>{{modelName}}</dd><dt>登记人 / 备注</dt><dd>{{ownerName}}</dd><dt>登记时间</dt><dd>{{createdAt}}</dd></dl>
|
||||
<h2>登记照片</h2><div class="photos">{{photos}}</div><footer>档案 ID:{{id}}</footer></main></body></html>
|
||||
<h2>登记照片</h2><div class="photos">{{photos}}</div><footer>档案 ID:{{id}}</footer></main></body></html>
|
||||
|
||||
+7
-2
@@ -36,7 +36,7 @@ async fn headers(req: Request, next: Next) -> Response {
|
||||
r.headers_mut().insert(key, HeaderValue::from_static(value));
|
||||
}
|
||||
if !r.headers().contains_key("content-security-policy") {
|
||||
r.headers_mut().insert("content-security-policy",HeaderValue::from_static("default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"));
|
||||
r.headers_mut().insert("content-security-policy",HeaderValue::from_static("default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"));
|
||||
}
|
||||
r
|
||||
}
|
||||
@@ -129,6 +129,11 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
if method == "GET"
|
||||
&& let Some((bytes, mime)) = crate::web_assets::resource(&path)
|
||||
{
|
||||
return binary(bytes.to_vec(), mime, None, None);
|
||||
}
|
||||
let result=worker.run(move|s|{
|
||||
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"{
|
||||
@@ -160,7 +165,7 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
if parts.len()==4&&parts[3]=="archive"&&method=="GET"{let r=s.get(id)?;let name=format!("FPV-RID-{}.html",r["serialNo"].as_str().unwrap_or("record"));return Ok(binary(archive::card(s,&r,true)?.into_bytes(),"text/html; charset=utf-8",Some(&name),Some("default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
|
||||
}
|
||||
if method=="GET"&&parts.len()==2&&parts[0]=="r"&&valid_id(parts[1]){return Ok(binary(archive::card(s,&s.get(parts[1])?,false)?.into_bytes(),"text/html; charset=utf-8",None,Some("default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
|
||||
if method=="GET"{let resource:Option<(&[u8],&str)>=match path.as_str(){"/"=>Some((include_bytes!("../registry/web/index.html"),"text/html; charset=utf-8")),"/app.js"=>Some((include_bytes!("../registry/web/app.js"),"text/javascript; charset=utf-8")),"/app.css"=>Some((include_bytes!("../registry/web/app.css"),"text/css; charset=utf-8")),"/vendor/qrcode.js"=>Some((include_bytes!("../registry/web/vendor/qrcode.js"),"text/javascript; charset=utf-8")),"/fpv-rid-icon.png"=>Some((include_bytes!("../registry/web/fpv-rid-icon.png"),"image/png")),_=>None};if let Some((bytes,mime))=resource{return Ok(binary(bytes.to_vec(),mime,None,None))}}
|
||||
|
||||
Ok(json_response(StatusCode::NOT_FOUND,json!({"error":"页面不存在"})))
|
||||
}).await;
|
||||
match result {
|
||||
|
||||
+48
-19
@@ -1,13 +1,23 @@
|
||||
mod archive;
|
||||
mod error;
|
||||
mod http;
|
||||
mod maps;
|
||||
mod realtime;
|
||||
mod receiver;
|
||||
mod store;
|
||||
mod web_assets {
|
||||
include!(concat!(env!("OUT_DIR"), "/web_assets.rs"));
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::{path::PathBuf, sync::mpsc};
|
||||
use std::path::PathBuf;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
type Job = Box<dyn FnOnce(&mut store::Store) + Send>;
|
||||
enum Job {
|
||||
Execute(Box<dyn FnOnce(&mut store::Store) + Send>),
|
||||
Shutdown,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Worker(mpsc::Sender<Job>);
|
||||
impl Worker {
|
||||
@@ -17,9 +27,10 @@ impl Worker {
|
||||
) -> error::Result<T> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
self.0
|
||||
.send(Box::new(move |s| {
|
||||
.send(Job::Execute(Box::new(move |s| {
|
||||
let _ = tx.send(f(s));
|
||||
}))
|
||||
})))
|
||||
.await
|
||||
.map_err(|_| "数据库线程已停止".to_string())?;
|
||||
rx.await
|
||||
.map_err(|_| error::AppError::Internal("数据库线程已停止".into()))?
|
||||
@@ -29,16 +40,21 @@ impl Worker {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let root = match args.next().as_deref() {
|
||||
Some("--data-root") => PathBuf::from(args.next().ok_or("缺少数据目录")?),
|
||||
None => std::env::current_exe()?
|
||||
.parent()
|
||||
.ok_or("无法确定程序目录")?
|
||||
.to_owned(),
|
||||
_ => return Err("用法: fpv-rid-registry.exe [--data-root DIRECTORY]".into()),
|
||||
};
|
||||
if args.next().is_some() {
|
||||
return Err("未知启动参数".into());
|
||||
let mut root = std::env::current_exe()?
|
||||
.parent()
|
||||
.ok_or("无法确定程序目录")?
|
||||
.to_owned();
|
||||
let mut simulation_api = false;
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--data-root" => root = PathBuf::from(args.next().ok_or("缺少数据目录")?),
|
||||
"--simulation-api" => simulation_api = true,
|
||||
_ => {
|
||||
return Err(
|
||||
"用法: fpv-rid-registry.exe [--data-root DIRECTORY] [--simulation-api]".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:8787")
|
||||
.await
|
||||
@@ -51,24 +67,37 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.write(true)
|
||||
.open(root.join("registry/data/rust.lock"))?;
|
||||
fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| "该数据目录已被另一个 Rust 实例使用")?;
|
||||
let map_root = root.clone();
|
||||
let store = store::Store::open(root)?;
|
||||
let (tx, rx) = mpsc::channel::<Job>();
|
||||
let (tx, mut rx) = mpsc::channel::<Job>(64);
|
||||
let shutdown = tx.clone();
|
||||
let worker_thread = std::thread::spawn(move || {
|
||||
let mut store = store;
|
||||
if let Err(e) = archive::sync(&mut store) {
|
||||
eprintln!("档案待同步:{e}");
|
||||
}
|
||||
for job in rx {
|
||||
job(&mut store);
|
||||
while let Some(job) = rx.blocking_recv() {
|
||||
match job {
|
||||
Job::Execute(job) => job(&mut store),
|
||||
Job::Shutdown => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
println!("FPV-RID Rust 登记站:http://127.0.0.1:8787");
|
||||
axum::serve(listener, http::router(Worker(tx)))
|
||||
let live_store = realtime::new_store();
|
||||
let receivers = receiver::router(map_root.clone(), live_store.clone()).await;
|
||||
let app = http::router(Worker(tx))
|
||||
.merge(realtime::with_store(simulation_api, live_store))
|
||||
.merge(receivers)
|
||||
.merge(maps::router(map_root)?);
|
||||
let served = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
})
|
||||
.await?;
|
||||
.await;
|
||||
let _ = shutdown.send(Job::Shutdown).await;
|
||||
worker_thread.join().map_err(|_| "数据库线程异常退出")?;
|
||||
served?;
|
||||
drop(lock);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
//! TianDiTu proxy and raster XYZ / MBTiles offline fallback. Keys stay server-side.
|
||||
use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
path::{Path as FsPath, PathBuf},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const MAX_TILE_BYTES: usize = 2 * 1024 * 1024;
|
||||
const LAYERS: &[&str] = &["vec_w", "cva_w", "img_w", "cia_w"];
|
||||
#[derive(Clone)]
|
||||
struct Maps {
|
||||
root: PathBuf,
|
||||
upstream: String,
|
||||
key: Option<String>,
|
||||
client: reqwest::Client,
|
||||
slots: Arc<Semaphore>,
|
||||
retry_after: Arc<AtomicU64>,
|
||||
online: Arc<AtomicU64>,
|
||||
offline: Arc<AtomicU64>,
|
||||
missing: Arc<AtomicU64>,
|
||||
cache_used: Arc<Mutex<Option<u64>>>,
|
||||
cache_limit: u64,
|
||||
}
|
||||
|
||||
pub fn router(root: PathBuf) -> Result<Router, reqwest::Error> {
|
||||
let key = std::env::var("TIANDITU_TOKEN")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty());
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_millis(800))
|
||||
.timeout(Duration::from_secs(2))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()?;
|
||||
let maps = Maps {
|
||||
root: root.join("maps"),
|
||||
upstream: "https://t0.tianditu.gov.cn".into(),
|
||||
key,
|
||||
client,
|
||||
slots: Arc::new(Semaphore::new(4)),
|
||||
retry_after: Arc::new(AtomicU64::new(0)),
|
||||
online: Arc::new(AtomicU64::new(0)),
|
||||
offline: Arc::new(AtomicU64::new(0)),
|
||||
missing: Arc::new(AtomicU64::new(0)),
|
||||
cache_used: Arc::new(Mutex::new(None)),
|
||||
cache_limit: 512 * 1024 * 1024,
|
||||
};
|
||||
Ok(Router::new()
|
||||
.route("/api/maps/status", get(status))
|
||||
.route("/api/maps/tile/{layer}/{z}/{x}/{y}", get(tile))
|
||||
.with_state(maps))
|
||||
}
|
||||
|
||||
fn local_request(headers: &HeaderMap) -> bool {
|
||||
headers.get("origin").is_none_or(|v| {
|
||||
matches!(
|
||||
v.to_str(),
|
||||
Ok("http://127.0.0.1:8787" | "http://localhost:8787")
|
||||
)
|
||||
}) && headers
|
||||
.get("sec-fetch-site")
|
||||
.is_none_or(|v| matches!(v.to_str(), Ok("same-origin" | "none")))
|
||||
}
|
||||
|
||||
async fn status(State(maps): State<Maps>, headers: HeaderMap) -> Response {
|
||||
if !local_request(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let retry = maps.retry_after.load(Ordering::Relaxed);
|
||||
let response = axum::Json(
|
||||
json!({"provider":"tianditu","keyConfigured":maps.key.is_some(),"mode":if maps.key.is_none()||retry>crate::realtime::now_ms(){"offline"}else{"online-preferred"},"retryAfterMs":retry,"servedOnline":maps.online.load(Ordering::Relaxed),"servedOffline":maps.offline.load(Ordering::Relaxed),"missingTiles":maps.missing.load(Ordering::Relaxed),"cacheLimitBytes":maps.cache_limit,"offlineLayout":"maps/offline/{layer}/{z}/{x}/{y}.png or maps/offline/{layer}.mbtiles"}),
|
||||
);
|
||||
let mut response = response.into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", "no-store".parse().unwrap());
|
||||
response
|
||||
}
|
||||
|
||||
fn mime(bytes: &[u8]) -> Option<&'static str> {
|
||||
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
Some("image/png")
|
||||
} else if bytes.starts_with(&[255, 216, 255]) {
|
||||
Some("image/jpeg")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn tile_response(bytes: Vec<u8>, source: &str) -> Response {
|
||||
let Some(kind) = mime(&bytes) else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
let mut response = Response::new(Body::from(bytes));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", kind.parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", "public, max-age=300".parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-map-source", source.parse().unwrap());
|
||||
response
|
||||
}
|
||||
fn allowed(root: &FsPath, path: &FsPath) -> bool {
|
||||
let Ok(relative) = path.strip_prefix(root) else {
|
||||
return false;
|
||||
};
|
||||
let mut current = root.to_path_buf();
|
||||
if current.is_symlink() {
|
||||
return false;
|
||||
}
|
||||
for part in relative.components() {
|
||||
current.push(part);
|
||||
if current.is_symlink() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
fn read_tile(root: &FsPath, path: &FsPath) -> Option<Vec<u8>> {
|
||||
if !allowed(root, path) {
|
||||
return None;
|
||||
}
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
if meta.len() > MAX_TILE_BYTES as u64 || !meta.is_file() {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
mime(&bytes)?;
|
||||
Some(bytes)
|
||||
}
|
||||
fn offline(maps: &Maps, layer: &str, z: u8, x: u32, y: u32) -> Option<Vec<u8>> {
|
||||
for extension in ["png", "jpg", "jpeg", "tile"] {
|
||||
let path = maps
|
||||
.root
|
||||
.join("offline")
|
||||
.join(layer)
|
||||
.join(z.to_string())
|
||||
.join(x.to_string())
|
||||
.join(format!("{y}.{extension}"));
|
||||
if let Some(bytes) = read_tile(&maps.root, &path) {
|
||||
return Some(bytes);
|
||||
}
|
||||
}
|
||||
let path = maps.root.join("offline").join(format!("{layer}.mbtiles"));
|
||||
if path.exists() && allowed(&maps.root, &path) {
|
||||
let db =
|
||||
rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
|
||||
.ok()?;
|
||||
let scheme: String = db
|
||||
.query_row("SELECT value FROM metadata WHERE name='scheme'", [], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap_or_else(|_| "tms".into());
|
||||
let row = if scheme == "xyz" {
|
||||
y
|
||||
} else {
|
||||
(1u32 << z) - 1 - y
|
||||
};
|
||||
let bytes:Vec<u8>=db.query_row("SELECT tile_data FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=? AND length(tile_data)<=?",rusqlite::params![z,x,row,MAX_TILE_BYTES as i64],|r|r.get(0)).ok()?;
|
||||
mime(&bytes)?;
|
||||
return Some(bytes);
|
||||
}
|
||||
let cached = maps
|
||||
.root
|
||||
.join("cache")
|
||||
.join(layer)
|
||||
.join(z.to_string())
|
||||
.join(x.to_string())
|
||||
.join(format!("{y}.tile"));
|
||||
read_tile(&maps.root, &cached)
|
||||
}
|
||||
|
||||
fn directory_size(root: &FsPath) -> u64 {
|
||||
let Ok(entries) = std::fs::read_dir(root) else {
|
||||
return 0;
|
||||
};
|
||||
let mut size = 0;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
size += directory_size(&path)
|
||||
} else {
|
||||
size += entry.metadata().map(|m| m.len()).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
size
|
||||
}
|
||||
fn cache(maps: &Maps, layer: &str, z: u8, x: u32, y: u32, bytes: &[u8]) {
|
||||
let root = maps.root.join("cache");
|
||||
let path = root
|
||||
.join(layer)
|
||||
.join(z.to_string())
|
||||
.join(x.to_string())
|
||||
.join(format!("{y}.tile"));
|
||||
if !allowed(&maps.root, &path) {
|
||||
return;
|
||||
}
|
||||
let Ok(mut budget) = maps.cache_used.lock() else {
|
||||
return;
|
||||
};
|
||||
let used = budget.get_or_insert_with(|| directory_size(&root));
|
||||
if *used + bytes.len() as u64 > maps.cache_limit || path.exists() {
|
||||
return;
|
||||
}
|
||||
if std::fs::create_dir_all(path.parent().unwrap()).is_ok()
|
||||
&& crate::archive::atomic(&path, bytes).is_ok()
|
||||
{
|
||||
*used += bytes.len() as u64;
|
||||
}
|
||||
}
|
||||
|
||||
async fn tile(
|
||||
State(maps): State<Maps>,
|
||||
Path((layer, z, x, y)): Path<(String, u8, u32, u32)>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if !LAYERS.contains(&layer.as_str()) || z > 18 || x >= (1u32 << z) || y >= (1u32 << z) {
|
||||
return StatusCode::BAD_REQUEST.into_response();
|
||||
}
|
||||
if !local_request(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let saved = {
|
||||
let maps = maps.clone();
|
||||
let layer = layer.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
read_tile(
|
||||
&maps.root,
|
||||
&maps
|
||||
.root
|
||||
.join("cache")
|
||||
.join(layer)
|
||||
.join(z.to_string())
|
||||
.join(x.to_string())
|
||||
.join(format!("{y}.tile")),
|
||||
)
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
// A healthy cache serves immediately; failures use the same immutable tile coordinates.
|
||||
if let Some(bytes) = saved {
|
||||
maps.offline.fetch_add(1, Ordering::Relaxed);
|
||||
return tile_response(bytes, "offline-or-cache");
|
||||
}
|
||||
if let Some(key) = &maps.key
|
||||
&& maps.retry_after.load(Ordering::Relaxed) <= crate::realtime::now_ms()
|
||||
&& let Ok(Ok(_permit)) =
|
||||
tokio::time::timeout(Duration::from_millis(100), maps.slots.acquire()).await
|
||||
{
|
||||
let service = layer.strip_suffix("_w").unwrap();
|
||||
let query = [
|
||||
("SERVICE", "WMTS".to_owned()),
|
||||
("REQUEST", "GetTile".into()),
|
||||
("VERSION", "1.0.0".into()),
|
||||
("LAYER", service.to_owned()),
|
||||
("STYLE", "default".into()),
|
||||
("TILEMATRIXSET", "w".into()),
|
||||
("FORMAT", "tiles".into()),
|
||||
("TILEMATRIX", z.to_string()),
|
||||
("TILEROW", y.to_string()),
|
||||
("TILECOL", x.to_string()),
|
||||
("tk", key.clone()),
|
||||
];
|
||||
let request = maps
|
||||
.client
|
||||
.get(format!("{}/{layer}/wmts", maps.upstream))
|
||||
.query(&query)
|
||||
.send()
|
||||
.await;
|
||||
if let Ok(mut response) = request
|
||||
&& response.status().is_success()
|
||||
&& response
|
||||
.content_length()
|
||||
.is_none_or(|n| n <= MAX_TILE_BYTES as u64)
|
||||
{
|
||||
let mut bytes = Vec::new();
|
||||
let mut complete = true;
|
||||
loop {
|
||||
match response.chunk().await {
|
||||
Ok(Some(chunk)) if bytes.len() + chunk.len() <= MAX_TILE_BYTES => {
|
||||
bytes.extend_from_slice(&chunk)
|
||||
}
|
||||
Ok(None) => break,
|
||||
_ => {
|
||||
complete = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if complete && mime(&bytes).is_some() {
|
||||
maps.online.fetch_add(1, Ordering::Relaxed);
|
||||
let copy = bytes.clone();
|
||||
let layer = layer.clone();
|
||||
let maps = maps.clone();
|
||||
tokio::task::spawn_blocking(move || cache(&maps, &layer, z, x, y, ©));
|
||||
return tile_response(bytes, "tianditu");
|
||||
}
|
||||
}
|
||||
// Do not log reqwest URLs/errors: they may contain the key.
|
||||
maps.retry_after
|
||||
.store(crate::realtime::now_ms() + 30000, Ordering::Relaxed);
|
||||
}
|
||||
let saved = {
|
||||
let maps = maps.clone();
|
||||
let layer = layer.clone();
|
||||
tokio::task::spawn_blocking(move || offline(&maps, &layer, z, x, y))
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
if let Some(bytes) = saved {
|
||||
maps.offline.fetch_add(1, Ordering::Relaxed);
|
||||
return tile_response(bytes, "offline");
|
||||
}
|
||||
maps.missing.fetch_add(1, Ordering::Relaxed);
|
||||
let mut response = StatusCode::NOT_FOUND.into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("cache-control", "no-store".parse().unwrap());
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn state(root: PathBuf) -> Maps {
|
||||
Maps {
|
||||
root,
|
||||
upstream: "https://t0.tianditu.gov.cn".into(),
|
||||
key: None,
|
||||
client: reqwest::Client::new(),
|
||||
slots: Arc::new(Semaphore::new(4)),
|
||||
retry_after: Arc::new(AtomicU64::new(0)),
|
||||
online: Arc::new(AtomicU64::new(0)),
|
||||
offline: Arc::new(AtomicU64::new(0)),
|
||||
missing: Arc::new(AtomicU64::new(0)),
|
||||
cache_used: Arc::new(Mutex::new(None)),
|
||||
cache_limit: 512 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn offline_xyz_and_cache_are_bounded() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut maps = state(tmp.path().join("maps"));
|
||||
let png = b"\x89PNG\r\n\x1a\ntest";
|
||||
cache(&maps, "vec_w", 2, 1, 2, png);
|
||||
assert_eq!(offline(&maps, "vec_w", 2, 1, 2).unwrap(), png);
|
||||
maps.cache_limit = 1;
|
||||
cache(&maps, "vec_w", 2, 2, 2, png);
|
||||
assert!(offline(&maps, "vec_w", 2, 2, 2).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn mbtiles_uses_tms_rows() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let maps = state(tmp.path().join("maps"));
|
||||
let folder = maps.root.join("offline");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let db = rusqlite::Connection::open(folder.join("vec_w.mbtiles")).unwrap();
|
||||
db.execute_batch("CREATE TABLE tiles(zoom_level INTEGER,tile_column INTEGER,tile_row INTEGER,tile_data BLOB)").unwrap();
|
||||
let png = b"\x89PNG\r\n\x1a\ntest";
|
||||
db.execute("INSERT INTO tiles VALUES(2,1,1,?)", [png.as_slice()])
|
||||
.unwrap();
|
||||
drop(db);
|
||||
assert_eq!(offline(&maps, "vec_w", 2, 1, 2).unwrap(), png);
|
||||
assert!(offline(&maps, "vec_w", 2, 1, 1).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn online_failure_switches_to_offline_and_recovers() {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
let failing = Arc::new(AtomicBool::new(false));
|
||||
let flag = failing.clone();
|
||||
let upstream = Router::new().fallback(move || {
|
||||
let flag = flag.clone();
|
||||
async move {
|
||||
if flag.load(Ordering::Relaxed) {
|
||||
StatusCode::SERVICE_UNAVAILABLE.into_response()
|
||||
} else {
|
||||
Response::new(Body::from(b"\x89PNG\r\n\x1a\nonline".to_vec()))
|
||||
}
|
||||
}
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(axum::serve(listener, upstream).into_future());
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut maps = state(temp.path().join("maps"));
|
||||
maps.upstream = format!("http://{address}");
|
||||
maps.key = Some("test-key-not-secret".into());
|
||||
let response = tile(
|
||||
State(maps.clone()),
|
||||
Path(("vec_w".into(), 2, 1, 1)),
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-map-source"], "tianditu");
|
||||
let offline_path = maps.root.join("offline/vec_w/2/1/2.png");
|
||||
std::fs::create_dir_all(offline_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(offline_path, b"\x89PNG\r\n\x1a\noffline").unwrap();
|
||||
failing.store(true, Ordering::Relaxed);
|
||||
let response = tile(
|
||||
State(maps.clone()),
|
||||
Path(("vec_w".into(), 2, 1, 2)),
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-map-source"], "offline");
|
||||
assert!(maps.retry_after.load(Ordering::Relaxed) > crate::realtime::now_ms());
|
||||
failing.store(false, Ordering::Relaxed);
|
||||
maps.retry_after.store(0, Ordering::Relaxed);
|
||||
let response = tile(
|
||||
State(maps.clone()),
|
||||
Path(("vec_w".into(), 2, 2, 2)),
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-map-source"], "tianditu");
|
||||
let response = tile(
|
||||
State(maps),
|
||||
Path(("vec_w".into(), 19, 0, 0)),
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 400);
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
//! Read-only real-time streaming and an explicitly enabled synthetic input API.
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{
|
||||
DefaultBodyLimit, State, WebSocketUpgrade,
|
||||
ws::{Message, WebSocket},
|
||||
},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use realtime_core::Store;
|
||||
use rid_shared::{MAX_BATCH, Observation};
|
||||
use serde_json::json;
|
||||
use std::sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Live {
|
||||
store: Arc<Mutex<Store>>,
|
||||
clients: Arc<AtomicUsize>,
|
||||
simulation_api: bool,
|
||||
}
|
||||
|
||||
pub fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64
|
||||
}
|
||||
|
||||
fn local_origin(headers: &HeaderMap) -> bool {
|
||||
headers.get("origin").is_none_or(|v| {
|
||||
matches!(
|
||||
v.to_str(),
|
||||
Ok("http://127.0.0.1:8787" | "http://localhost:8787")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn router(simulation_api: bool) -> Router {
|
||||
with_store(simulation_api, new_store())
|
||||
}
|
||||
|
||||
pub(crate) type TargetStore = Arc<Mutex<Store>>;
|
||||
|
||||
pub(crate) fn new_store() -> TargetStore {
|
||||
Arc::new(Mutex::new(Store::new(10000, 40000, 30000, rand::random())))
|
||||
}
|
||||
|
||||
pub(crate) fn with_store(simulation_api: bool, store: TargetStore) -> Router {
|
||||
let live = Live {
|
||||
store,
|
||||
clients: Arc::new(AtomicUsize::new(0)),
|
||||
simulation_api,
|
||||
};
|
||||
let expiration = live.store.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
||||
loop {
|
||||
tick.tick().await;
|
||||
if let Ok(mut store) = expiration.lock() {
|
||||
store.expire(now_ms());
|
||||
}
|
||||
}
|
||||
});
|
||||
Router::new()
|
||||
.route("/api/realtime/ws", get(upgrade))
|
||||
.route("/api/realtime/status", get(status))
|
||||
.route("/api/realtime/snapshot", get(snapshot))
|
||||
.route("/api/realtime/ingest", post(ingest))
|
||||
.layer(DefaultBodyLimit::max(2 * 1024 * 1024))
|
||||
.with_state(live)
|
||||
}
|
||||
|
||||
async fn status(State(live): State<Live>, headers: HeaderMap) -> Response {
|
||||
if !local_origin(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let Ok(store) = live.store.lock() else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
Json(json!({"mode":if live.simulation_api {"synthetic-input-enabled"} else {"receiver-input"},"metrics":store.metrics(),"clients":live.clients.load(Ordering::Relaxed),"maxClients":4,"ttlMs":30000,"pushIntervalMs":20,"ackTimeoutMs":1000})).into_response()
|
||||
}
|
||||
|
||||
async fn snapshot(State(live): State<Live>, headers: HeaderMap) -> Response {
|
||||
if !local_origin(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let Ok(store) = live.store.lock() else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
Json(store.frame(None, now_ms())).into_response()
|
||||
}
|
||||
|
||||
async fn ingest(
|
||||
State(live): State<Live>,
|
||||
headers: HeaderMap,
|
||||
request: axum::extract::Request,
|
||||
) -> Response {
|
||||
if !local_origin(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if !live.simulation_api {
|
||||
return (StatusCode::FORBIDDEN, Json(json!({"error":"synthetic input disabled; start with --simulation-api for isolated tests"}))).into_response();
|
||||
}
|
||||
let binary = match headers
|
||||
.get("content-type")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
{
|
||||
"application/json" => false,
|
||||
"application/octet-stream" => true,
|
||||
_ => return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(),
|
||||
};
|
||||
let Ok(bytes) = axum::body::to_bytes(request.into_body(), 2 * 1024 * 1024).await else {
|
||||
return StatusCode::PAYLOAD_TOO_LARGE.into_response();
|
||||
};
|
||||
let batch: Vec<Observation> = if binary {
|
||||
match postcard::from_bytes(&bytes) {
|
||||
Ok(batch) => batch,
|
||||
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
}
|
||||
} else {
|
||||
match serde_json::from_slice(&bytes) {
|
||||
Ok(batch) => batch,
|
||||
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
}
|
||||
};
|
||||
if batch.is_empty() || batch.len() > MAX_BATCH || batch.iter().any(|o| !o.validate()) {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(json!({"error":"invalid synthetic batch; maximum 4096 observations"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let Ok(mut store) = live.store.lock() else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
let now = now_ms();
|
||||
let mut accepted = 0;
|
||||
for observation in batch {
|
||||
accepted += usize::from(store.apply(observation, now));
|
||||
}
|
||||
Json(json!({"accepted":accepted,"metrics":store.metrics()})).into_response()
|
||||
}
|
||||
|
||||
async fn upgrade(State(live): State<Live>, headers: HeaderMap, ws: WebSocketUpgrade) -> Response {
|
||||
if !local_origin(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if live
|
||||
.clients
|
||||
.try_update(Ordering::AcqRel, Ordering::Acquire, |n| {
|
||||
(n < 4).then_some(n + 1)
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
}
|
||||
let permit = ClientPermit(live.clients.clone());
|
||||
ws.max_message_size(1024)
|
||||
.max_frame_size(1024)
|
||||
.on_upgrade(move |socket| stream(socket, live, permit))
|
||||
}
|
||||
|
||||
struct ClientPermit(Arc<AtomicUsize>);
|
||||
impl Drop for ClientPermit {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream(mut socket: WebSocket, live: Live, _permit: ClientPermit) {
|
||||
let mut since = None;
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tick.tick().await;
|
||||
let frame = {
|
||||
let Ok(store) = live.store.lock() else {
|
||||
break;
|
||||
};
|
||||
store.frame(since, now_ms())
|
||||
};
|
||||
let Ok(bytes) = postcard::to_allocvec(&frame) else {
|
||||
break;
|
||||
};
|
||||
let sequence = frame.sequence;
|
||||
if !matches!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(200),
|
||||
socket.send(Message::Binary(bytes.into()))
|
||||
)
|
||||
.await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
// Exactly one unacknowledged batch per client: bound receiver-side backlog too.
|
||||
let ack = tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
match socket.recv().await {
|
||||
Some(Ok(Message::Text(text))) if text.as_str() == sequence.to_string() => {
|
||||
return true;
|
||||
}
|
||||
Some(Ok(Message::Ping(bytes))) => {
|
||||
if socket.send(Message::Pong(bytes)).await.is_err() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if !matches!(ack, Ok(true)) {
|
||||
break;
|
||||
}
|
||||
since = Some(sequence);
|
||||
}
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_millis(100),
|
||||
socket.send(Message::Close(None)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::{body::Body, http::Request};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use rid_shared::Frame;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn synthetic_input_requires_opt_in_and_rejects_foreign_origin() {
|
||||
let request = || {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/realtime/ingest")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from("[]"))
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
router(false).oneshot(request()).await.unwrap().status(),
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
let response = router(true)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/realtime/status")
|
||||
.header("origin", "https://foreign.example")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_snapshot_delta_and_ack_timeout() {
|
||||
let app = router(true);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(axum::serve(listener, app.clone()).into_future());
|
||||
let (mut socket, _) =
|
||||
tokio_tungstenite::connect_async(format!("ws://{addr}/api/realtime/ws"))
|
||||
.await
|
||||
.unwrap();
|
||||
let first = socket.next().await.unwrap().unwrap().into_data();
|
||||
let snapshot: Frame = postcard::from_bytes(&first).unwrap();
|
||||
assert!(snapshot.snapshot);
|
||||
assert!(snapshot.targets.is_empty());
|
||||
socket
|
||||
.send(tokio_tungstenite::tungstenite::Message::Text(
|
||||
snapshot.sequence.to_string().into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let observation = Observation {
|
||||
target_id: "SIM-1".into(),
|
||||
receiver_id: "SIM".into(),
|
||||
source_epoch: 1,
|
||||
sequence: 1,
|
||||
longitude: 120.0,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
};
|
||||
let request = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/realtime/ingest")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(serde_json::to_vec(&vec![observation]).unwrap()))
|
||||
.unwrap();
|
||||
assert_eq!(app.oneshot(request).await.unwrap().status(), 200);
|
||||
loop {
|
||||
let bytes = socket.next().await.unwrap().unwrap().into_data();
|
||||
let delta: Frame = postcard::from_bytes(&bytes).unwrap();
|
||||
if !delta.targets.is_empty() {
|
||||
assert!(!delta.snapshot);
|
||||
assert_eq!(delta.targets[0].observation.target_id, "SIM-1");
|
||||
break;
|
||||
}
|
||||
socket
|
||||
.send(tokio_tungstenite::tungstenite::Message::Text(
|
||||
delta.sequence.to_string().into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// Stop acknowledging: the server must close rather than accumulate updates.
|
||||
let closed = tokio::time::timeout(Duration::from_secs(3), socket.next())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
closed,
|
||||
Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) | None
|
||||
));
|
||||
server.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_client_limit_and_foreign_origin() {
|
||||
use tokio_tungstenite::tungstenite::{Error, client::IntoClientRequest};
|
||||
let app = router(false);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(axum::serve(listener, app).into_future());
|
||||
let url = format!("ws://{addr}/api/realtime/ws");
|
||||
let mut foreign = url.clone().into_client_request().unwrap();
|
||||
foreign
|
||||
.headers_mut()
|
||||
.insert("origin", "https://foreign.example".parse().unwrap());
|
||||
let Err(Error::Http(response)) = tokio_tungstenite::connect_async(foreign).await else {
|
||||
panic!("foreign origin was accepted");
|
||||
};
|
||||
assert_eq!(response.status(), 403);
|
||||
let mut sockets = Vec::new();
|
||||
for _ in 0..4 {
|
||||
sockets.push(tokio_tungstenite::connect_async(&url).await.unwrap().0);
|
||||
}
|
||||
let Err(Error::Http(response)) = tokio_tungstenite::connect_async(&url).await else {
|
||||
panic!("client limit was not enforced");
|
||||
};
|
||||
assert_eq!(response.status(), 429);
|
||||
drop(sockets);
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
+636
@@ -0,0 +1,636 @@
|
||||
//! Receive-only transports. Unknown vendor formats remain raw bytes, never guessed positions.
|
||||
use crate::realtime::{TargetStore, now_ms};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::State,
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use rid_shared::{MAX_BATCH, Observation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
net::{IpAddr, SocketAddr},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt},
|
||||
net::{TcpListener, UdpSocket},
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
use tokio_serial::SerialPortBuilderExt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum Transport {
|
||||
#[default]
|
||||
Serial,
|
||||
Udp,
|
||||
TcpListen,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum Format {
|
||||
#[default]
|
||||
Raw,
|
||||
JsonLines,
|
||||
Postcard,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct Config {
|
||||
enabled: bool,
|
||||
transport: Transport,
|
||||
format: Format,
|
||||
serial_port: String,
|
||||
baud_rate: u32,
|
||||
bind_ip: String,
|
||||
port: u16,
|
||||
}
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
transport: Transport::Serial,
|
||||
format: Format::Raw,
|
||||
serial_port: String::new(),
|
||||
baud_rate: 115200,
|
||||
bind_ip: "127.0.0.1".into(),
|
||||
port: 8788,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Config {
|
||||
fn validate(&self) -> Result<(), &'static str> {
|
||||
if !self.enabled {
|
||||
return Ok(());
|
||||
}
|
||||
match self.transport {
|
||||
Transport::Serial => {
|
||||
let port = self
|
||||
.serial_port
|
||||
.strip_prefix("COM")
|
||||
.and_then(|n| n.parse::<u16>().ok());
|
||||
if !port.is_some_and(|n| n > 0) || !(1200..=4_000_000).contains(&self.baud_rate) {
|
||||
return Err("请选择有效 COM 串口及波特率(1200–4000000)");
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if self.bind_ip.parse::<IpAddr>().is_err() || self.port == 0 {
|
||||
return Err("接收监听 IP 或端口无效");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn address(&self) -> SocketAddr {
|
||||
SocketAddr::new(self.bind_ip.parse().unwrap(), self.port)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Status {
|
||||
state: String,
|
||||
endpoint: String,
|
||||
received_bytes: u64,
|
||||
decoded_frames: u64,
|
||||
rejected_frames: u64,
|
||||
accepted_observations: u64,
|
||||
last_data_ms: Option<u64>,
|
||||
last_error: Option<String>,
|
||||
capture_hex: String,
|
||||
}
|
||||
struct Monitor {
|
||||
status: Status,
|
||||
capture: VecDeque<u8>,
|
||||
}
|
||||
impl Default for Monitor {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: Status {
|
||||
state: "stopped".into(),
|
||||
..Status::default()
|
||||
},
|
||||
capture: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Receiver {
|
||||
root: PathBuf,
|
||||
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 {
|
||||
headers.get("origin").is_none_or(|v| {
|
||||
matches!(
|
||||
v.to_str(),
|
||||
Ok("http://127.0.0.1:8787" | "http://localhost:8787")
|
||||
)
|
||||
}) && headers
|
||||
.get("sec-fetch-site")
|
||||
.is_none_or(|v| matches!(v.to_str(), Ok("same-origin" | "none")))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
async fn start(&self, config: Config) {
|
||||
let mut task = self.task.lock().await;
|
||||
if let Some(old) = task.take() {
|
||||
old.abort();
|
||||
let _ = old.await;
|
||||
}
|
||||
*self.config.lock().unwrap() = config.clone();
|
||||
if !config.enabled {
|
||||
self.monitor.lock().unwrap().status.state = "stopped".into();
|
||||
return;
|
||||
}
|
||||
*self.monitor.lock().unwrap() = Monitor::default();
|
||||
let receiver = self.clone();
|
||||
*task = Some(tokio::spawn(async move {
|
||||
loop {
|
||||
receiver.monitor.lock().unwrap().status.state = "connecting".into();
|
||||
let result = receiver.run(&config).await;
|
||||
{
|
||||
let mut monitor = receiver.monitor.lock().unwrap();
|
||||
monitor.status.state = "disconnected".into();
|
||||
monitor.status.last_error = result.err().map(|e| e.to_string());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
}));
|
||||
}
|
||||
fn received(&self, bytes: &[u8]) {
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.received_bytes += bytes.len() as u64;
|
||||
monitor.status.last_data_ms = Some(now_ms());
|
||||
let tail = &bytes[bytes.len().saturating_sub(4096)..];
|
||||
let excess = (monitor.capture.len() + tail.len()).saturating_sub(4096);
|
||||
monitor.capture.drain(..excess);
|
||||
monitor.capture.extend(tail.iter().copied());
|
||||
}
|
||||
fn decode(&self, format: Format, bytes: &[u8]) {
|
||||
let result: Result<Vec<Observation>, ()> = match format {
|
||||
Format::Raw => return,
|
||||
Format::JsonLines => serde_json::from_slice(bytes)
|
||||
.or_else(|_| serde_json::from_slice::<Observation>(bytes).map(|o| vec![o]))
|
||||
.map_err(|_| ()),
|
||||
Format::Postcard => postcard::from_bytes(bytes).map_err(|_| ()),
|
||||
};
|
||||
let batch = match result {
|
||||
Ok(batch)
|
||||
if !batch.is_empty()
|
||||
&& batch.len() <= MAX_BATCH
|
||||
&& batch.iter().all(Observation::validate) =>
|
||||
{
|
||||
batch
|
||||
}
|
||||
_ => {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let now = now_ms();
|
||||
let accepted = {
|
||||
let mut store = self.targets.lock().unwrap();
|
||||
let mut accepted = 0;
|
||||
for observation in batch {
|
||||
accepted += usize::from(store.apply(observation, now));
|
||||
}
|
||||
accepted
|
||||
};
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.decoded_frames += 1;
|
||||
monitor.status.accepted_observations += accepted as u64;
|
||||
}
|
||||
async fn stream<R: AsyncRead + Unpin>(
|
||||
&self,
|
||||
mut reader: R,
|
||||
format: Format,
|
||||
idle_timeout: Option<Duration>,
|
||||
) -> std::io::Result<()> {
|
||||
let mut chunk = [0u8; 8192];
|
||||
let mut buffer = Vec::new();
|
||||
let mut discarding_json = false;
|
||||
loop {
|
||||
let n = if let Some(timeout) = idle_timeout {
|
||||
tokio::time::timeout(timeout, reader.read(&mut chunk))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, "receiver idle timeout")
|
||||
})??
|
||||
} else {
|
||||
reader.read(&mut chunk).await?
|
||||
};
|
||||
if n == 0 {
|
||||
if !buffer.is_empty() {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.received(&chunk[..n]);
|
||||
if matches!(format, Format::Raw) {
|
||||
continue;
|
||||
}
|
||||
if discarding_json && matches!(format, Format::JsonLines) {
|
||||
if let Some(end) = chunk[..n].iter().position(|b| *b == b'\n') {
|
||||
discarding_json = false;
|
||||
buffer.extend_from_slice(&chunk[end + 1..n]);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
buffer.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
match format {
|
||||
Format::JsonLines => {
|
||||
while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
|
||||
if end <= 65536 {
|
||||
self.decode(format, &buffer[..end]);
|
||||
} else {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
}
|
||||
buffer.drain(..=end);
|
||||
}
|
||||
if buffer.len() > 65536 {
|
||||
buffer.clear();
|
||||
discarding_json = true;
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
}
|
||||
}
|
||||
Format::Postcard => {
|
||||
while buffer.len() >= 4 {
|
||||
let length = u32::from_be_bytes(buffer[..4].try_into().unwrap()) as usize;
|
||||
if length == 0 || length > 2 * 1024 * 1024 {
|
||||
self.monitor.lock().unwrap().status.rejected_frames += 1;
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"binary frame length exceeds limit",
|
||||
));
|
||||
}
|
||||
if buffer.len() < length + 4 {
|
||||
break;
|
||||
}
|
||||
self.decode(format, &buffer[4..length + 4]);
|
||||
buffer.drain(..length + 4);
|
||||
}
|
||||
}
|
||||
Format::Raw => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn run(&self, config: &Config) -> std::io::Result<()> {
|
||||
match config.transport {
|
||||
Transport::Serial => {
|
||||
let serial =
|
||||
tokio_serial::new(&config.serial_port, config.baud_rate).open_native_async()?;
|
||||
{
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.state = "serial-open".into();
|
||||
monitor.status.endpoint = config.serial_port.clone();
|
||||
}
|
||||
self.stream(serial, config.format, None).await
|
||||
}
|
||||
Transport::Udp => {
|
||||
let socket = UdpSocket::bind(config.address()).await?;
|
||||
{
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.state = "udp-listening".into();
|
||||
monitor.status.endpoint = socket.local_addr()?.to_string();
|
||||
}
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let (n, _) = socket.recv_from(&mut buffer).await?;
|
||||
self.received(&buffer[..n]);
|
||||
self.decode(config.format, &buffer[..n]);
|
||||
}
|
||||
}
|
||||
Transport::TcpListen => {
|
||||
let listener = TcpListener::bind(config.address()).await?;
|
||||
{
|
||||
let mut monitor = self.monitor.lock().unwrap();
|
||||
monitor.status.state = "tcp-listening".into();
|
||||
monitor.status.endpoint = listener.local_addr()?.to_string();
|
||||
}
|
||||
let mut clients = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
incoming=listener.accept()=>{let(socket,_)=incoming?;if clients.len()<8{let receiver=self.clone();let format=config.format;clients.spawn(async move{let _=receiver.stream(socket,format,Some(Duration::from_secs(30))).await;});}},
|
||||
_=clients.join_next(),if !clients.is_empty()=>{}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn status(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
let mut status = monitor.status.clone();
|
||||
status.capture_hex = monitor
|
||||
.capture
|
||||
.iter()
|
||||
.rev()
|
||||
.take(64)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
Json(status).into_response()
|
||||
}
|
||||
async fn capture(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let monitor = receiver.monitor.lock().unwrap();
|
||||
let hex = monitor
|
||||
.capture
|
||||
.iter()
|
||||
.map(|b| format!("{b:02X}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
Json(json!({"encoding":"hex","bytes":monitor.capture.len(),"data":hex,"lastDataMs":monitor.status.last_data_ms})).into_response()
|
||||
}
|
||||
async fn config(State(receiver): State<Receiver>, headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
Json(receiver.config.lock().unwrap().clone()).into_response()
|
||||
}
|
||||
async fn ports(headers: HeaderMap) -> Response {
|
||||
if !local(&headers) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let names = tokio::task::spawn_blocking(|| {
|
||||
tokio_serial::available_ports()
|
||||
.map(|ports| ports.into_iter().map(|p| p.port_name).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.await
|
||||
.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(),
|
||||
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 {
|
||||
Observation {
|
||||
target_id: "TEST-USB".into(),
|
||||
receiver_id: "TEST".into(),
|
||||
source_epoch: 1,
|
||||
sequence: 1,
|
||||
longitude: 120.0,
|
||||
latitude: 30.0,
|
||||
altitude_m: 100.0,
|
||||
heading_deg: 90.0,
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn fragmented_serial_like_json_is_decoded_without_hardware() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let receiver = receiver();
|
||||
let (worker, mut producer) = tokio::io::duplex(8192);
|
||||
let reader = receiver.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
reader
|
||||
.stream(worker, Format::JsonLines, None)
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
let bytes = serde_json::to_vec(&observation()).unwrap();
|
||||
producer.write_all(&bytes[..10]).await.unwrap();
|
||||
producer.write_all(&bytes[10..]).await.unwrap();
|
||||
producer.write_all(b"\n").await.unwrap();
|
||||
drop(producer);
|
||||
task.await.unwrap();
|
||||
assert_eq!(receiver.targets.lock().unwrap().metrics().active_targets, 1);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn udp_and_tcp_listeners_accept_known_formats() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
for transport in [Transport::Udp, Transport::TcpListen] {
|
||||
let receiver = receiver();
|
||||
let listener = receiver.clone();
|
||||
let config = Config {
|
||||
transport,
|
||||
format: Format::Postcard,
|
||||
port: 0,
|
||||
..Config::default()
|
||||
};
|
||||
let task = tokio::spawn(async move { listener.run(&config).await.unwrap() });
|
||||
let mut endpoint = String::new();
|
||||
for _ in 0..100 {
|
||||
endpoint = receiver.monitor.lock().unwrap().status.endpoint.clone();
|
||||
if !endpoint.is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(!endpoint.is_empty());
|
||||
let bytes = postcard::to_allocvec(&vec![observation()]).unwrap();
|
||||
match transport {
|
||||
Transport::Udp => {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
socket.send_to(&bytes, &endpoint).await.unwrap();
|
||||
}
|
||||
_ => {
|
||||
let mut socket = tokio::net::TcpStream::connect(&endpoint).await.unwrap();
|
||||
socket
|
||||
.write_all(&(bytes.len() as u32).to_be_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
socket.write_all(&bytes).await.unwrap();
|
||||
}
|
||||
}
|
||||
for _ in 0..100 {
|
||||
if receiver.targets.lock().unwrap().metrics().active_targets == 1 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert_eq!(receiver.targets.lock().unwrap().metrics().active_targets, 1);
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn raw_capture_never_fabricates_targets() {
|
||||
let receiver = receiver();
|
||||
receiver.received(&vec![0xAA; 10000]);
|
||||
receiver.decode(Format::Raw, b"unknown vendor bytes");
|
||||
assert_eq!(receiver.monitor.lock().unwrap().capture.len(), 4096);
|
||||
assert_eq!(receiver.targets.lock().unwrap().metrics().active_targets, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_api_persists_and_stops_network_listener() {
|
||||
use axum::{body::Body, http::Request};
|
||||
use tower::ServiceExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let app = router(temp.path().to_owned(), crate::realtime::new_store()).await;
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = socket.local_addr().unwrap().port();
|
||||
drop(socket);
|
||||
let body = json!({"enabled":true,"transport":"udp","format":"raw","bindIp":"127.0.0.1","port":port});
|
||||
let request = |value: &serde_json::Value| {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/receiver/config")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(value.to_string()))
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
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(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(saved.enabled);
|
||||
assert_eq!(saved.port, port);
|
||||
let mut listening = false;
|
||||
for _ in 0..100 {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/receiver/status")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(
|
||||
&axum::body::to_bytes(response.into_body(), 8192)
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
if value["state"] == "udp-listening" {
|
||||
listening = true;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert!(listening);
|
||||
let mut disabled = body;
|
||||
disabled["enabled"] = json!(false);
|
||||
assert_eq!(app.oneshot(request(&disabled)).await.unwrap().status(), 200);
|
||||
let probe = UdpSocket::bind(("127.0.0.1", port)).await.unwrap();
|
||||
drop(probe);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_saved_settings_are_preserved_without_opening_devices() {
|
||||
use axum::{body::Body, http::Request};
|
||||
use tower::ServiceExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("receiver-config.json");
|
||||
std::fs::write(&path, b"not-json").unwrap();
|
||||
let app = router(temp.path().to_owned(), crate::realtime::new_store()).await;
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/receiver/status")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(
|
||||
&axum::body::to_bytes(response.into_body(), 8192)
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(value["state"], "stopped");
|
||||
assert!(value["lastError"].as_str().unwrap().contains("配置无效"));
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"not-json");
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -277,11 +277,14 @@ async fn http_status_codes_and_error_redaction() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let s = Store::open(tmp.path().to_owned()).unwrap();
|
||||
s.db.execute_batch("DROP TABLE photos").unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel::<crate::Job>();
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel::<crate::Job>(64);
|
||||
std::thread::spawn(move || {
|
||||
let mut s = s;
|
||||
for job in rx {
|
||||
job(&mut s);
|
||||
while let Some(job) = rx.blocking_recv() {
|
||||
match job {
|
||||
crate::Job::Execute(job) => job(&mut s),
|
||||
crate::Job::Shutdown => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
let app = crate::http::router(crate::Worker(tx));
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "xtask"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,177 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, ExitCode},
|
||||
};
|
||||
fn run(command: &mut Command) -> Result<(), String> {
|
||||
let status = command.status().map_err(|e| e.to_string())?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("command failed: {command:?}"))
|
||||
}
|
||||
}
|
||||
fn tool(env: &str, binary: &str, local: &str) -> PathBuf {
|
||||
std::env::var_os(env).map(PathBuf::from).unwrap_or_else(|| {
|
||||
let fallback = PathBuf::from(local);
|
||||
if fallback.is_file() {
|
||||
fallback
|
||||
} else {
|
||||
PathBuf::from(binary)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn web(root: &Path) -> Result<(), String> {
|
||||
let _build_guard = if std::env::var_os("RID_PACKAGE_BUILD").is_none() {
|
||||
let file = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(root.join(".build.lock"))
|
||||
.map_err(|e| format!("build lock unavailable: {e}"))?;
|
||||
file.try_lock()
|
||||
.map_err(|e| format!("another build is running: {e}"))?;
|
||||
Some(file)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let trunk = tool(
|
||||
"RID_TRUNK",
|
||||
"trunk",
|
||||
"D:/Rust_Contact/util/tools/trunk-0.22.0/trunk.exe",
|
||||
);
|
||||
let bindgen = tool(
|
||||
"RID_WASM_BINDGEN",
|
||||
"wasm-bindgen",
|
||||
"D:/Rust_Contact/util/tools/wasm-bindgen-0.2.129/wasm-bindgen-0.2.129-x86_64-pc-windows-msvc/wasm-bindgen.exe",
|
||||
);
|
||||
for (tool, expected) in [(&trunk, "0.22.0"), (&bindgen, "0.2.129")] {
|
||||
let output = Command::new(tool)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !output.status.success() || !String::from_utf8_lossy(&output.stdout).contains(expected) {
|
||||
return Err(format!(
|
||||
"expected tool version {expected}: {}",
|
||||
tool.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut path = vec![bindgen.parent().unwrap().to_owned()];
|
||||
path.extend(std::env::split_paths(
|
||||
&std::env::var_os("PATH").unwrap_or_default(),
|
||||
));
|
||||
run(Command::new(trunk)
|
||||
.args([
|
||||
"build",
|
||||
"--release",
|
||||
"--locked",
|
||||
"--dist",
|
||||
"../../dist/web-ui",
|
||||
])
|
||||
.env(
|
||||
"PATH",
|
||||
std::env::join_paths(path).map_err(|e| e.to_string())?,
|
||||
)
|
||||
.current_dir(root.join("crates/web-ui")))?;
|
||||
// Externalize Trunk's inline module initializer to preserve a strict CSP.
|
||||
let index = root.join("dist/web-ui/index.html");
|
||||
let mut html = fs::read_to_string(&index).map_err(|e| e.to_string())?;
|
||||
let mut n = 0;
|
||||
let mut cursor = 0;
|
||||
while let Some(offset) = html[cursor..].find("<script") {
|
||||
let start = cursor + offset;
|
||||
let tag_end = start + html[start..].find('>').ok_or("invalid script tag")?;
|
||||
let end = tag_end
|
||||
+ 1
|
||||
+ html[tag_end + 1..]
|
||||
.find("</script>")
|
||||
.ok_or("invalid script close")?;
|
||||
if !html[start..tag_end].contains("src=") {
|
||||
let filename = format!("bootstrap-{n}.js");
|
||||
fs::write(
|
||||
root.join("dist/web-ui").join(&filename),
|
||||
&html[tag_end + 1..end],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let replacement = format!("<script type=\"module\" src=\"/{filename}\"></script>");
|
||||
html.replace_range(start..end + 9, &replacement);
|
||||
cursor = start + replacement.len();
|
||||
n += 1;
|
||||
} else {
|
||||
cursor = end + 9;
|
||||
}
|
||||
}
|
||||
fs::write(index, html).map_err(|e| e.to_string())?;
|
||||
run(Command::new("cargo")
|
||||
.args([
|
||||
"build",
|
||||
"--release",
|
||||
"--locked",
|
||||
"--target",
|
||||
"wasm32-unknown-unknown",
|
||||
"-p",
|
||||
"rid-web-worker",
|
||||
])
|
||||
.current_dir(root))?;
|
||||
let metadata = Command::new("cargo")
|
||||
.args(["metadata", "--format-version", "1", "--no-deps"])
|
||||
.current_dir(root)
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !metadata.status.success() {
|
||||
return Err("cargo metadata failed".into());
|
||||
}
|
||||
let metadata: serde_json::Value =
|
||||
serde_json::from_slice(&metadata.stdout).map_err(|e| e.to_string())?;
|
||||
let wasm = PathBuf::from(
|
||||
metadata["target_directory"]
|
||||
.as_str()
|
||||
.ok_or("target_directory missing")?,
|
||||
)
|
||||
.join("wasm32-unknown-unknown/release/rid_web_worker.wasm");
|
||||
let workers = root.join("dist/web-ui/workers");
|
||||
fs::create_dir_all(&workers).map_err(|e| e.to_string())?;
|
||||
run(Command::new(bindgen)
|
||||
.arg(wasm)
|
||||
.args(["--target", "web", "--out-dir"])
|
||||
.arg(&workers))?;
|
||||
fs::copy(
|
||||
root.join("crates/web-worker/entry.js"),
|
||||
workers.join("entry.js"),
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> ExitCode {
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let command = std::env::args().nth(1).unwrap_or("check".into());
|
||||
let result = match command.as_str() {
|
||||
"web" => web(&root),
|
||||
"check" => run(Command::new("cargo")
|
||||
.args(["test", "--workspace", "--exclude", "rid-web-ui", "--locked"])
|
||||
.current_dir(&root)),
|
||||
"package" => run(Command::new("powershell")
|
||||
.env_remove("PSModulePath")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"scripts/package.ps1",
|
||||
])
|
||||
.current_dir(&root)),
|
||||
_ => Err("usage: cargo xtask [web|check|package]".into()),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -2,9 +2,9 @@
|
||||
cd /d "%~dp0"
|
||||
if exist "%~dp0fpv-rid-registry.exe" (
|
||||
"%~dp0fpv-rid-registry.exe"
|
||||
) else if exist "D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry.exe" (
|
||||
"D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry.exe" --data-root "%~dp0."
|
||||
) else if exist "D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry-fullstack.exe" (
|
||||
"D:\Rust_Contact\util\target\Rid_Drone_Receivev\release\fpv-rid-registry-fullstack.exe" --data-root "%~dp0."
|
||||
) else (
|
||||
echo Build first: cargo build --release --locked
|
||||
echo Build first: cargo xtask package
|
||||
)
|
||||
pause
|
||||
|
||||
Reference in New Issue
Block a user