feat(receiver): 持久化接收机发现端点并支持位置备注信息

This commit is contained in:
zyp
2026-11-30 09:29:33 +08:00
parent 1d6d7a277e
commit 5e761fc064
95 changed files with 15744 additions and 701 deletions
+72 -10
View File
@@ -20,20 +20,37 @@ pub struct Store {
metrics: Metrics,
}
fn refresh(track: &mut Track) {
const SOURCE_HOLD_MS: u64 = 4_000;
fn refresh(track: &mut Track, now_ms: u64) {
let mut sources: Vec<_> = track.sources.values().cloned().collect();
sources.sort_by(|a, b| {
a.received_at_ms
.cmp(&b.received_at_ms)
.then_with(|| a.observation.receiver_id.cmp(&b.observation.receiver_id))
});
let selected = sources
.iter()
.rev()
.find(|s| s.observation.coordinates().is_some())
let old = &track.target.observation;
let primary = track.sources.get(&old.receiver_id);
let fresh_primary = primary.filter(|s| {
s.observation.coordinates().is_some()
&& now_ms.saturating_sub(s.received_at_ms) < SOURCE_HOLD_MS
});
let selected = fresh_primary
.or_else(|| {
sources.iter().rev().find(|s| {
s.observation.coordinates().is_some()
&& now_ms.saturating_sub(s.received_at_ms) < SOURCE_HOLD_MS
})
})
.or_else(|| primary.filter(|s| s.observation.coordinates().is_some()))
.or_else(|| {
sources
.iter()
.rev()
.find(|s| s.observation.coordinates().is_some())
})
.or_else(|| sources.last())
.expect("nonempty source set");
let old = &track.target.observation;
if old.coordinates().is_some() != selected.observation.coordinates().is_some()
|| old.receiver_id != selected.observation.receiver_id
{
@@ -74,7 +91,7 @@ impl Store {
self.changes.push_back((self.metrics.sequence, id));
}
/// Select the latest still-valid position, retaining independent source observations.
/// Keep a healthy position source, retaining independent observations for failover.
pub fn apply(&mut self, observation: Observation, now_ms: u64) -> bool {
if !observation.validate() {
self.metrics.rejected += 1;
@@ -125,7 +142,7 @@ impl Store {
track
.sources
.retain(|_, s| now_ms.saturating_sub(s.received_at_ms) < self.ttl_ms);
refresh(track);
refresh(track, now_ms);
track.target.received_count = track.target.received_count.saturating_add(1);
track.suppressed = false;
if let Some(observer) = &self.observer {
@@ -141,6 +158,22 @@ impl Store {
self.tracks.get(id).map(|track| &track.target.observation)
}
/// Withdraw an alias from the receiver that supplied the confirmed identity.
pub fn remove_source(&mut self, id: &str, receiver_id: &str, now_ms: u64) {
let Some(track) = self.tracks.get_mut(id) else {
return;
};
if track.sources.remove(receiver_id).is_none() {
return;
}
if track.sources.is_empty() {
self.tracks.remove(id);
} else {
refresh(track, now_ms);
}
self.changed(id.to_owned());
}
pub fn expire(&mut self, now_ms: u64) {
let _ = self.expire_with_changes(now_ms);
}
@@ -191,7 +224,7 @@ impl Store {
if track.sources.is_empty() {
removed.push(id.clone());
} else if track.sources.len() != count || track.suppressed {
refresh(track);
refresh(track, now_ms);
track.suppressed = false;
if let Some(observer) = &self.observer {
observer(&track.target.observation, now_ms);
@@ -291,7 +324,7 @@ mod tests {
let frame = store.frame(None, 5);
assert_eq!(frame.targets.len(), 1);
assert_eq!(frame.targets[0].sources.len(), 2);
assert_eq!(frame.targets[0].observation.receiver_id, "b");
assert_eq!(frame.targets[0].observation.receiver_id, "a");
let generation = frame.targets[0].position_generation;
a.sequence = 2;
a.longitude = None;
@@ -321,6 +354,35 @@ mod tests {
store.expire(45);
assert!(store.frame(None, 45).targets.is_empty());
}
#[test]
fn lagging_receivers_do_not_replace_a_healthy_source_and_failover_is_sticky() {
let mut store = Store::new(10, 100, 30_000, 1);
let mut primary = sample("one-aircraft", 1);
primary.receiver_id = "primary".into();
let mut standby = primary.clone();
standby.receiver_id = "standby".into();
standby.longitude = Some(119.);
assert!(store.apply(primary.clone(), 100));
assert!(store.apply(standby.clone(), 200));
primary.sequence += 1;
primary.longitude = Some(120.01);
assert!(store.apply(primary.clone(), 1_000));
standby.sequence += 1;
assert!(store.apply(standby.clone(), 1_500));
let live = store.frame(None, 1_500);
assert_eq!(live.targets.len(), 1);
assert_eq!(live.targets[0].sources.len(), 2);
assert_eq!(live.targets[0].observation, primary);
let generation = live.targets[0].position_generation;
standby.sequence += 1;
assert!(store.apply(standby.clone(), 5_000));
primary.sequence += 1;
assert!(store.apply(primary, 5_100));
let live = store.frame(None, 5_100);
assert_eq!(live.targets[0].observation, standby);
assert_eq!(live.targets[0].position_generation, generation + 1);
}
fn sample(id: &str, sequence: u64) -> Observation {
Observation {
target_id: id.into(),
+3
View File
@@ -118,6 +118,9 @@ pub struct DeviceTelemetry {
pub geometric_altitude_m: Option<f64>,
pub height_agl_m: Option<f64>,
pub pilot_position: Option<[f64; 2]>,
/// Server assessment captured when writing history; never trusted from receiver input.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flight_status: Option<String>,
pub utc_raw: Option<String>,
}
+1 -1
View File
@@ -1,2 +1,2 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"><link data-trunk rel="copy-file" href="public/map-tile-buffer.js"><link data-trunk rel="copy-file" href="public/geofences.css"><link rel="stylesheet" href="/geofences.css"><link data-trunk rel="copy-file" href="public/geofence-map-adapter.js"><link data-trunk rel="copy-file" href="public/appearance.css"><link rel="stylesheet" href="/appearance.css"><link data-trunk rel="copy-file" href="public/receivers.css"><link rel="stylesheet" href="/receivers.css"><link data-trunk rel="copy-file" href="public/receivers.js"><script type="module" src="/receivers.js"></script><link data-trunk rel="copy-file" href="public/history.css"><link rel="stylesheet" href="/history.css"><link data-trunk rel="copy-file" href="public/history-map-adapter.js"></head><body></body></html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"><link data-trunk rel="copy-file" href="public/map-tile-buffer.js"><link data-trunk rel="copy-file" href="public/geofences.css"><link rel="stylesheet" href="/geofences.css"><link data-trunk rel="copy-file" href="public/geofence-map-adapter.js"><link data-trunk rel="copy-file" href="public/appearance.css"><link rel="stylesheet" href="/appearance.css"><link data-trunk rel="copy-file" href="public/receivers.css"><link rel="stylesheet" href="/receivers.css"><link data-trunk rel="copy-file" href="public/receivers.js"><script type="module" src="/receivers.js"></script><link data-trunk rel="copy-file" href="public/history.css"><link rel="stylesheet" href="/history.css"><link data-trunk rel="copy-file" href="public/history-map-adapter.js"><link rel="stylesheet" href="/workbench/embedded.css"><script type="module" src="/workbench/embedded.js"></script><link rel="stylesheet" href="/workbench/drone-marker.css"></head><body></body></html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 11 KiB

+93 -10
View File
@@ -3,7 +3,8 @@ import * as ml from './vendor/maplibre-gl.mjs';
import {attachTileBuffer} from './map-tile-buffer.js';
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
let map,buffer,observer,marker,points=[],index=0,fitPending=false,kind='imagery';
let map,buffer,observer,marker,points=[],projected=[],index=0,progress=0,fitPending=false,kind='imagery';
let labels = true, registered, registrationGeneration = 0;
const layers={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
const url=i=>`/api/maps/tile/${layers[kind][i]}/{z}/{x}/{y}`;
function coordinate(point){
@@ -30,19 +31,70 @@ function paint(){
fitPending=false;
}
}
function paintMarker(){
const position=coordinate(points[index]);
if(!map||!position){marker?.remove();marker=null;return;}
if(!marker)marker=new ml.Marker({color:'#82c5ff',anchor:'center'}).setLngLat(position).addTo(map);
else marker.setLngLat(position);
const angleDelta = (from, to) => ((to - from + 540) % 360) - 180;
function makeDroneMarker() {
const element = window.ridDroneMap.createMarker(window.ridDroneMap.registrationColors(registered));
return new ml.Marker({element, anchor:'center', rotationAlignment:'map', pitchAlignment:'map', subpixelPositioning:true});
}
function pointAlongEdge(from, to, fraction) {
const east = to.x - from.x;
const dx = Math.abs(east) > 0.5 ? east - Math.sign(east) : east;
return new ml.MercatorCoordinate(from.x + dx * fraction, from.y + (to.y - from.y) * fraction, 0)
.toLngLat().toArray();
}
function paintMarker() {
const current = points[index];
const from = coordinate(current);
if (!map || !from) {
marker?.remove();
marker = null;
return;
}
const next = points[index + 1];
const to = !next?.segmentStart && next?.timeMs > current.timeMs ? coordinate(next) : null;
const previous = !current.segmentStart ? coordinate(points[index - 1]) : null;
const direction = (a, b) => window.ridDroneMap.trackHeading(a[1], a[0], b[1], b[0]);
const course = to ? direction(from, to) : previous ? direction(previous, from) : undefined;
const heading = Number.isFinite(current.headingDeg) ? current.headingDeg : course ?? 0;
const destinationHeading = to && Number.isFinite(next.headingDeg) ? next.headingDeg : heading;
const angle = heading + angleDelta(heading, destinationHeading) * progress;
const position = to && progress > 0
? pointAlongEdge(projected[index], projected[index + 1], progress)
: from;
if (!marker) marker = makeDroneMarker().setLngLat(position).setRotation(angle).addTo(map);
else {
if (marker.getRotation() !== angle) marker.setRotation(angle);
const previousPosition = marker.getLngLat();
if (previousPosition.lng !== position[0] || previousPosition.lat !== position[1]) {
marker.setLngLat(position);
}
}
}
export function setMapOptions(options) {
const next = options.basemap === 'road' ? 'road' : 'imagery';
if (next !== kind) {
kind = next;
map?.getSource('base')?.setTiles([url(0)]);
map?.getSource('labels')?.setTiles([url(1)]);
buffer?.schedule();
}
labels = options.labels !== false;
if (map?.getLayer('labels')) map.setLayoutProperty('labels', 'visibility', labels ? 'visible' : 'none');
}
export function open(p){
setMapOptions(p);
if(map){map.resize();return;}
kind=p.basemap==='road'?'road':'imagery';
try{
map=new ml.Map({container:'history-map',center:[p.longitude,p.latitude],zoom:p.zoom??15,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,attributionControl:false,
style:{version:8,sources:{base:{type:'raster',tiles:[url(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[url(1)],tileSize:256,maxzoom:18}},
layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'}]}});
layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels',layout:{visibility:labels?'visible':'none'}}]}});
buffer=attachTileBuffer(map,()=>kind);observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('history-map'));
map.addControl(new ml.NavigationControl({showCompass:false}),'bottom-right');
map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 历史轨迹',compact:true}),'bottom-right');
@@ -51,7 +103,38 @@ export function open(p){
map.on('error',e=>{if(!['base','labels'].includes(e.sourceId))window.dispatchEvent(new Event('rid-history-map-error'));});
}catch{close();window.dispatchEvent(new Event('rid-history-map-error'));}
}
export function setPoints(value){points=Array.isArray(value)?value:[];index=0;fitPending=true;paint();}
export function setIndex(value){index=Math.max(0,Math.min(points.length-1,Number(value)||0));paintMarker();}
export function setPoints(value, target) {
points = Array.isArray(value) ? value : [];
registered = undefined;
marker?.remove();
marker = null;
const generation = ++registrationGeneration;
if (target && points.length) {
fetch('/api/target-registration-status?' + new URLSearchParams({ids:target}), {cache:'no-store'})
.then(response => response.ok ? response.json() : null).then(result => {
if (generation !== registrationGeneration || !result?.entries?.length) return;
registered = result.entries[0].registered;
const element = marker?.getElement();
if (element) {
const {fill, glow} = window.ridDroneMap.registrationColors(registered);
element.style.setProperty('--rid-drone-fill', fill);
element.style.setProperty('--rid-drone-glow', glow);
}
}).catch(() => {});
}
projected = points.map(point => {
const position = coordinate(point);
return position ? ml.MercatorCoordinate.fromLngLat(position) : null;
});
index = 0;
progress = 0;
fitPending = true;
paint();
}
export function setCursor(value, fraction) {
index = Math.max(0, Math.min(points.length - 1, Number(value) || 0));
progress = Math.max(0, Math.min(1, Number(fraction) || 0));
paintMarker();
}
export function close(){buffer?.destroy();buffer=null;observer?.disconnect();observer=null;marker?.remove();marker=null;map?.remove();map=null;}
export function metrics(){return {ready:!!map?.getSource('history-track'),points:points.length,index};}
+6
View File
@@ -30,3 +30,9 @@ body.b.theme-white .history-list button[aria-pressed=true]{background:#dcebf7;bo
body.b.theme-white .history-warning{color:var(--mc-warning)!important}
body.b.theme-white .history-divider{background:var(--work-line)}
body.b.theme-white :is(.track-playback-controls button,.history-sidebar button,.history-sidebar input,.history-playback input):focus-visible{outline-color:var(--mc-accent)}
.history-query:not([hidden]){display:contents}
.history-record-details{display:grid;gap:5px;margin:0;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}
.history-record-details dt{color:var(--work-muted);font-size:12px}
.history-record-details dd{margin:0 0 7px}
.history-osd:not([hidden]){display:flex;flex-wrap:wrap;gap:6px 16px;padding:8px 0;line-height:1.5;font-size:12px;font-variant-numeric:tabular-nums}
+62 -7
View File
@@ -1,4 +1,5 @@
// Load the map engine only for the approved realtime workspace.
import '/workbench/drone-map.js';
// A separate, lazy map keeps configuration independent of the live receiver map.
let settings, generation=0;
@@ -15,13 +16,67 @@ window.ridGeofences={
close(){fenceGeneration++;fences?.close();},render(p){fences?.render(p);},targets(p){fences?.targets(p);},tool(v){fences?.tool(v);},locate(){fences?.locate();},setBasemap(v){fences?.setBasemap(v);},metrics(){return fences?.metrics();}
};
let history,historyGeneration=0,historyPoints=[],historyIndex=0;
window.ridHistory={
async open(p){const token=++historyGeneration;try{history??=await import('./history-map-adapter.js');if(token===historyGeneration){history.open(p);history.setPoints(historyPoints);history.setIndex(historyIndex);}}catch{window.dispatchEvent(new Event('rid-history-map-error'));}},
close(){historyGeneration++;history?.close();},
setPoints(value){historyPoints=Array.isArray(value)?value:[];historyIndex=0;history?.setPoints(historyPoints);},
setIndex(value){historyIndex=value;history?.setIndex(value);},
metrics(){return history?.metrics();}
let history, historyGeneration = 0, historyPoints = [], historyIndex = 0, historyProgress = 0;
let historyTarget, historyMapOptions;
let playbackFrame, playbackTimestamp, playbackGeneration = 0;
document.addEventListener('visibilitychange', () => { playbackTimestamp = undefined; });
function stopHistoryClock() {
playbackGeneration += 1;
if (playbackFrame !== undefined) cancelAnimationFrame(playbackFrame);
playbackFrame = undefined;
playbackTimestamp = undefined;
}
window.ridHistory = {
async open(p) {
const token = ++historyGeneration;
try {
history ??= await import('./history-map-adapter.js');
if (token === historyGeneration) {
history.open({...p, ...historyMapOptions});
history.setPoints(historyPoints, historyTarget);
history.setCursor(historyIndex, historyProgress);
}
} catch {
window.dispatchEvent(new Event('rid-history-map-error'));
}
},
close() {
historyGeneration += 1;
stopHistoryClock();
history?.close();
},
prepareTrack(value) { return window.ridDroneMap.prepareTrack(value); },
setPoints(value, target) {
historyPoints = Array.isArray(value) ? value : [];
historyTarget = target;
historyIndex = 0;
historyProgress = 0;
history?.setPoints(historyPoints, historyTarget);
},
setMapOptions(value) {
historyMapOptions = value;
if (value) history?.setMapOptions(value);
},
setCursor(index, progress) {
historyIndex = index;
historyProgress = progress;
history?.setCursor(index, progress);
},
startClock(tick) {
stopHistoryClock();
const token = playbackGeneration;
function frame(timestamp) {
if (token !== playbackGeneration) return;
const elapsed = playbackTimestamp === undefined ? 0 : Math.max(0, timestamp - playbackTimestamp);
playbackTimestamp = timestamp;
if (tick(elapsed) && token === playbackGeneration) {
playbackFrame = requestAnimationFrame(frame);
}
}
playbackFrame = requestAnimationFrame(frame);
},
stopClock: stopHistoryClock,
metrics() { return history?.metrics(); }
};
if (location.pathname === '/realtime') await import('./map-adapter.js');
-10
View File
@@ -8,7 +8,6 @@
.rx-page{display:flex;flex-direction:column;box-sizing:border-box}
.rx-surface{flex:1;min-height:calc(100dvh - 280px);padding:20px;border:1px solid var(--work-line,#bdd8ff22);border-radius:16px;background:color-mix(in srgb,var(--work-panel,#1a2a3bc9) 72%,transparent);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}
.rx-surface .rx-cards{align-items:start}
.rx-surface>.rx-footnote{margin-bottom:0}
@media(max-width:650px){.rx-surface{padding:16px;min-height:360px}}
/* Compact receiver toolbar and single-screen connection form. */
@@ -45,12 +44,6 @@
.rx-page .rx-card .rx-actions button{background:color-mix(in srgb,var(--work-text) 8%,var(--glass-solid,#102235))}
/* Equal-height cards: seven fixed rows, so extra notices cannot change the height. */
.rx-legend{display:flex;flex-wrap:wrap;gap:6px 14px;margin:0 0 12px;color:var(--work-muted,#9eb3c8);font-size:12px;line-height:1.4}
.rx-legend span{display:inline-flex;align-items:center;min-width:0}
.rx-dot{width:8px;height:8px;margin-right:5px;border-radius:99px;background:var(--work-muted,#9eb3c8);flex:none}
.rx-dot.ok{background:var(--mc-success,#81d8af)}
.rx-dot.info{background:var(--mc-accent,#8bbdff)}
.rx-dot.warn{background:var(--mc-warning,#ffd08a)}
.rx-cards{grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}
.rx-card{display:grid;grid-template-rows:22px 16px 24px 20px 22px auto auto;gap:6px;align-content:start;padding:14px;border-left-width:3px;overflow:hidden}
.rx-card>*{min-width:0;min-height:0}
@@ -91,6 +84,3 @@
.theme-white .rx-card.rx-warn{border-left-color:#875013}
.theme-white .rx-pill.rx-info{color:#286299;background:#28629916}
.theme-white .rx-card.rx-info{border-left-color:#286299}
.theme-white .rx-dot.ok{background:#236647}
.theme-white .rx-dot.warn{background:#875013}
.theme-white .rx-dot.info{background:#286299}
+55 -24
View File
@@ -1,19 +1,22 @@
// Device management is a view of server-owned receiver tasks, never their lifecycle owner.
const $ = id => document.getElementById(id);
let rows = [], selected = null, busy = false, pending = false, dirty = false, initialized = false;
const defaults = {enabled:false,transport:'serial',format:'raw',uidIdentity:'source-scoped',serialPort:'',baudRate:115200,bindIp:'127.0.0.1',port:8788};
const protocols = {'raw':'原始诊断','uid-json':'UID JSON','rid-device-json':'RID / uav','json-lines':'约定 JSON','postcard':'Postcard'};
const pageSize = 8;
let page = 0;
const defaults = {enabled:false,transport:'serial',uidIdentity:'source-scoped',serialPort:'',baudRate:115200,bindIp:'127.0.0.1',port:8788,peerIp:''};
const receiverFormat = format => !format || format === 'raw' ? 'rid-device-json' : format;
function state(row) {
const s=row.status||{};
if(!row.config?.enabled)return !row.detector&&row.deviceKind?'其他串口 · 未当作侦测机':'未启用';
if(s.state==='disconnected')return '连接失败 · 自动重试';
if(s.state==='disconnected')return row.config.transport==='tcp-listen'?'监听失败 · 自动重试':'连接失败 · 自动重试';
if(s.state==='connecting'||s.state==='stopped')return '正在连接';
if(s.notice)return s.notice;
if(!s.receivedBytes)return row.detector?'侦测串口已连接 · 还没有数据':'已连接 · 等待数据';
if(s.state==='tcp-listening'&&(!s.lastDataMs||Date.now()-s.lastDataMs>15000))return '监听中 · 等待数据';
if(!s.receivedBytes)return '已连接 · 等待数据';
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return '连接中 · 暂无新数据';
if(row.config.format==='raw')return '接收中 · 原始诊断';
if(s.rejectedFrames&&!s.decodedFrames)return '收到数据 · 协议不匹配';
if(!s.acceptedObservations)return '正在接收 · 暂无有效目标';
if(!s.acceptedObservations)return s.heartbeatFrames?'正在接收 · 已收到设备心跳':'正在接收 · 暂无有效目标';
return '正在接收 · 已解析目标';
}
const GB_NOTE='这台设备收到了报文,但帧头不符合它自己的 GB46750 要求,所以不会生成目标。';
@@ -30,11 +33,15 @@ function tone(row){
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return 'info';
if(row.config.format==='raw')return 'ok';
if(s.rejectedFrames&&!s.decodedFrames)return 'warn';
if(!s.acceptedObservations)return 'info';
if(!s.acceptedObservations)return s.heartbeatFrames?'ok':'info';
return 'ok';
}
function cardStatus(row){return row.config?.enabled?state(row):'未启用';}
function roleLabel(row){if(row.config.transport!=='serial')return '网络';if(row.detector)return '侦测机';if(row.deviceKind)return '其他串口';return '接收机';}
function roleLabel(row){
if(row.config.transport!=='serial')return '网络';
if(row.status?.lastValidFrameMs != null)return '侦测机';
return row.config.serialPort ? 'USB 串口' : '接收机';
}
function identity(row){
const name=row.name||'未命名接收机',socket=row.devicePlace||'';
if(socket&&(name===socket||name.endsWith(` · ${socket}`))){
@@ -46,7 +53,7 @@ function identity(row){
return {head:row.deviceKind,place:socket||rest||'—'};
}
if(socket)return {head:name,place:socket};
if(row.config.transport!=='serial')return {head:name,place:'网络 · 手动添加'};
if(row.config.transport!=='serial')return {head:name,place:row.networkDiscovered?'网络 · 自动登记':'网络 · 手动添加'};
const cut=name.indexOf(' · ');
return cut<0?{head:name,place:'—'}:{head:name.slice(0,cut),place:name.slice(cut+3)};
}
@@ -86,9 +93,16 @@ function render(){
const focused=document.activeElement?.dataset.rxFocus;
const query=$('rx-search').value.trim().toLowerCase();
const list=rows.filter(r=>`${r.name} ${r.deviceKind||''} ${r.devicePlace||''} ${r.id} ${r.hardwareId||''} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
const watching=rows.filter(r=>r.detector&&r.config.enabled).length;
$('rx-summary').textContent=`${rows.length} 个串口 · ${watching} 台侦测机已启用`;
$('rx-cards').replaceChildren(...list.map(row=>{
const pageCount = Math.max(1, Math.ceil(list.length / pageSize));
page = Math.min(page, pageCount - 1);
const displayed = list.slice(page * pageSize, (page + 1) * pageSize);
$('rx-page-summary').textContent = `共 ${list.length} 台 · 每页 ${pageSize} 台`;
$('rx-page-number').textContent = `第 ${page + 1} / ${pageCount} 页`;
$('rx-page-prev').disabled = page === 0;
$('rx-page-next').disabled = page + 1 >= pageCount;
const watching=rows.filter(r=>r.config.enabled).length;
$('rx-summary').textContent=`${rows.length} 台接收器 · ${watching} 台已启用`;
$('rx-cards').replaceChildren(...displayed.map(row=>{
const idn=identity(row),toneName=tone(row),lines=faults(row);
const c=el('article',undefined,`rx-card rx-${toneName}`);
const title=el('h2',idn.head);title.title=row.name||idn.head;
@@ -96,32 +110,49 @@ function render(){
const pills=el('div',undefined,'rx-pills'),statusText=cardStatus(row);
const status=el('span',statusText,`rx-pill rx-${toneName}`);status.title=statusText;
pills.append(status,el('span',roleLabel(row),'rx-pill rx-role'));
const meta=el('p',undefined,'rx-meta'),portText=endpoint(row),protocolText=protocols[row.config.format]||row.config.format;
const port=el('span',portText);port.title=portText;meta.append(port,el('span',protocolText,'rx-protocol'));
const meta=el('p',undefined,'rx-meta'),portText=endpoint(row);
const port=el('span',portText);port.title=portText;meta.append(port);
const alert=el('div',undefined,lines.length?'rx-alert':'rx-alert quiet');
const alertText=el('span',lines.length?lines[0]:'—','rx-alert-text');alertText.title=lines.length?lines[0]:'没有额外提示';alert.append(alertText);
if(lines.length>1){const more=el('button',`另 ${lines.length-1} 条`,'rx-more');more.type='button';more.dataset.rxFocus=row.id+'-alerts';more.dataset.rxAlerts=row.id;more.setAttribute('aria-label',`另 ${lines.length-1} 条提示`);more.onclick=event=>{event.stopPropagation();if(popFor===row.id&&!$('rx-pop').hidden)closePop();else openPop(row,more);};alert.append(more);}
const metrics=el('div',undefined,'rx-metrics');for(const [label,value] of [['接收字节',row.status?.receivedBytes||0],['接受更新',row.status?.acceptedObservations||0]]){const m=el('div');m.append(el('strong',Number(value).toLocaleString()),el('span',label));metrics.append(m);}
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');manage.type='button';toggle.type='button';manage.dataset.rxFocus=row.id+'-manage';toggle.dataset.rxFocus=row.id+'-toggle';manage.onclick=()=>open(row);toggle.disabled=busy;toggle.onclick=async()=>{await mutate(async()=>{await api(`/api/receivers/${row.id}`,'PUT',{name:row.name,config:{...row.config,enabled:!row.config.enabled}});});};actions.append(manage,toggle);c.append(title,place,pills,meta,alert,metrics,actions);return c;
}));$('rx-empty').hidden=!!list.length;syncPop(list);
const metrics = el('div', undefined, 'rx-metrics');
const s = row.status || {};
for (const [label, value] of [['接收字节', s.receivedBytes], ['有效目标更新', s.acceptedObservations]]) {
const metric = el('div');
metric.append(el('strong', Number(value ?? 0).toLocaleString()), el('span', label));
metrics.append(metric);
}
const last = el('p', `最近接收 ${s.lastDataMs ? new Date(s.lastDataMs).toLocaleTimeString() : '—'}`, 'rx-place');
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');manage.type='button';toggle.type='button';manage.dataset.rxFocus=row.id+'-manage';toggle.dataset.rxFocus=row.id+'-toggle';manage.onclick=()=>open(row);toggle.disabled=busy;toggle.onclick=async()=>{await mutate(async()=>{const config={...row.config,enabled:!row.config.enabled};if(config.enabled)config.format=receiverFormat(config.format);await api(`/api/receivers/${row.id}`,'PUT',{name:row.name,config});});};actions.append(manage,toggle);c.append(title,place,pills,meta,alert,metrics,last,actions);return c;
}));$('rx-empty').hidden=!!list.length;syncPop(displayed);
if(focused){for(const button of $('rx-cards').querySelectorAll('button')){if(button.dataset.rxFocus===focused){button.focus({preventScroll:true});break;}}}
if(selected)diagnostics();
}
async function refresh(){if(pending||!$('rx-cards'))return;pending=true;try{const v=await api('/api/receivers');rows=v.receivers||[];$('rx-error').textContent=v.error||'';$('rx-error').hidden=!v.error;render();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;}finally{pending=false;}}
async function mutate(action){if(busy)return;busy=true;render();try{await action();await refresh();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;if($('rx-drawer').open)$('rx-message').textContent=e.message;}finally{busy=false;render();}}
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-uid-fields').hidden=f.elements.format.value!=='uid-json';$('rx-protocol-note').textContent=f.elements.format.value==='uid-json'?'UID 报文中的坐标系代码尚未核实:选中目标可查看原始位置,不参与围栏。':f.elements.format.value==='raw'?'原始诊断只接收字节,不生成无人机目标。':'协议必须与设备实际输出一致;未知报文不会猜测为位置。';}
function selectedFormat() { return receiverFormat(rows.find(row => row.id === selected)?.config.format); }
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-peer-fields').hidden=f.elements.transport.value!=='tcp-listen';$('rx-uid-fields').hidden=selectedFormat()!=='uid-json';}
function tab(diagnostic){$('rx-form').hidden=diagnostic;$('rx-diagnostic').hidden=!diagnostic;$('rx-config-tab').setAttribute('aria-pressed',String(!diagnostic));$('rx-diagnostic-tab').setAttribute('aria-pressed',String(diagnostic));diagnostics();}
function diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['设备种类',row.deviceKind||'—'],['插口位置',row.devicePlace||'—'],['设备 ID',row.hardwareId||row.id],['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无'],...(s.notice?[['帧头提示',s.notice]]:[])]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
function open(row){closePop();selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config={...defaults,...row?.config};f.elements.name.value=row?.name||'';for(const [key,value] of Object.entries(config)){if(key==='enabled')f.elements[key].checked=value;else f.elements[key].value=value;}$('rx-delete').hidden=!selected||selected==='default';fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
function diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['设备种类',row.deviceKind||'—'],['插口位置',row.devicePlace||'—'],['设备 ID',row.hardwareId||row.id],['来源 IP',s.lastPeerIp||'—'],['心跳帧',s.heartbeatFrames ?? 0],['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无'],...(s.notice?[['帧头提示',s.notice]]:[])]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
function open(row){closePop();selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config={...defaults,...row?.config};f.elements.name.value=row?.name||'';for(const key of Object.keys(defaults)){if(key==='enabled')f.elements[key].checked=config[key];else f.elements[key].value=config[key] ?? '';}$('rx-delete').hidden=!selected;fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
function close(){if(dirty&&!confirm('尚有未保存的配置,放弃修改并关闭?'))return;$('rx-drawer').close();selected=null;dirty=false;}
function init(){if(initialized||!$('rx-cards'))return;initialized=true;$('rx-add').onclick=()=>open(null);$('rx-refresh').onclick=refresh;$('rx-search').oninput=render;$('rx-close').onclick=close;$('rx-drawer').addEventListener('cancel',e=>{e.preventDefault();close();});$('rx-form').oninput=()=>{dirty=true;fields();};$('rx-form').onchange=()=>{dirty=true;fields();};$('rx-config-tab').onclick=()=>tab(false);$('rx-diagnostic-tab').onclick=()=>tab(true);
$('rx-form').onsubmit=async e=>{e.preventDefault();if(busy)return;const f=e.target,config={};for(const key of Object.keys(defaults))config[key]=key==='enabled'?f.elements[key].checked:['baudRate','port'].includes(key)?Number(f.elements[key].value):f.elements[key].value;await mutate(async()=>{const v=await api(selected?`/api/receivers/${selected}`:'/api/receivers',selected?'PUT':'POST',{name:f.elements.name.value,config});selected=v.receiver.id;dirty=false;$('rx-message').textContent='配置已保存。接收状态以实时诊断为准。';$('rx-title').textContent=v.receiver.name;$('rx-delete').hidden=selected==='default';});};
$('rx-delete').onclick=()=>{if(!selected||!confirm('删除此接收机配置并停止该接收任务?其他接收机不受影响。'))return;mutate(async()=>{await api(`/api/receivers/${selected}`,'DELETE');dirty=false;close();});};
$('rx-capture').onclick=async()=>{if(!selected)return;try{const v=await api(`/api/receivers/${selected}/capture`);const bytes=Uint8Array.from((v.data.match(/[0-9a-f]{2}/ig)||[]).map(x=>parseInt(x,16)));$('rx-raw').textContent=`UTF-8(损坏字节以替代符显示)\n${new TextDecoder().decode(bytes)}\n\nHEX\n${v.data||'尚无数据'}`;}catch(e){$('rx-message').textContent=e.message;}};
function init(){if(initialized||!$('rx-cards'))return;initialized=true;$('rx-add').onclick=()=>open(null);$('rx-refresh').onclick=refresh;$('rx-close').onclick=close;$('rx-drawer').addEventListener('cancel',e=>{e.preventDefault();close();});$('rx-form').oninput=()=>{dirty=true;fields();};$('rx-form').onchange=()=>{dirty=true;fields();};$('rx-config-tab').onclick=()=>tab(false);$('rx-diagnostic-tab').onclick=()=>tab(true);
$('rx-search').oninput = () => { page = 0; render(); };
for (const [id, step] of [['rx-page-prev', -1], ['rx-page-next', 1]]) {
const button = $(id);
button.onclick = () => {
page += step;
render();
if (button.disabled) $('rx-page-number').focus();
};
}
$('rx-form').onsubmit=async e=>{e.preventDefault();if(busy)return;const f=e.target,config={format:selectedFormat()};for(const key of Object.keys(defaults))config[key]=key==='enabled'?f.elements[key].checked:['baudRate','port'].includes(key)?Number(f.elements[key].value):f.elements[key].value;config.peerIp=config.transport==='tcp-listen'?(config.peerIp.trim()||null):null;await mutate(async()=>{const v=await api(selected?`/api/receivers/${selected}`:'/api/receivers',selected?'PUT':'POST',{name:f.elements.name.value,config});selected=v.receiver.id;dirty=false;$('rx-message').textContent='配置已保存。接收状态以实时诊断为准。';$('rx-title').textContent=v.receiver.name;$('rx-delete').hidden=false;});};
$('rx-delete').onclick=()=>{if(!selected||!confirm('删除此接收机配置?正常运行的 RID TCP 入口会继续接收,有效数据会触发重新登记。'))return;mutate(async()=>{await api(`/api/receivers/${selected}`,'DELETE');dirty=false;close();});};
$('rx-capture').onclick=async()=>{if(!selected)return;try{const v=await api(`/api/receivers/${selected}/capture`);const bytes=Uint8Array.from((v.data.match(/[0-9a-f]{2}/ig)||[]).map(x=>parseInt(x,16)));const identities=(v.identitySamples||[]).map(sample=>`${sample.targetId} · ${sample.peerIp||sample.receiverId} · ${new Date(sample.receivedAtMs).toLocaleString()}\n协议 ${sample.format} · serial=${sample.telemetry?.serial||'—'} · ssid=${sample.telemetry?.ssid||'—'} · MAC=${sample.telemetry?.mac||'—'}\n${sample.raw}${sample.truncated?'\n(报文已截断)':''}`).join('\n\n');$('rx-raw').textContent=`UTF-8(损坏字节以替代符显示)\n${new TextDecoder().decode(bytes)}\n\nHEX\n${v.data||'尚无数据'}${identities?'\n\n本次接收的目标来源(最近 64 个身份的首帧)\n'+identities:''}`;}catch(e){$('rx-message').textContent=e.message;}};
document.addEventListener('click',event=>{if(!popFor||event.target.closest('#rx-pop, [data-rx-alerts]'))return;closePop();});
document.addEventListener('keydown',event=>{if(event.key==='Escape')closePop();});
const movePop=()=>{if(!popFor)return;const anchor=document.querySelector(`[data-rx-alerts="${CSS.escape(popFor)}"]`);if(anchor)placePop(anchor);};
window.addEventListener('resize',movePop);document.addEventListener('scroll',movePop,true);
refresh();setInterval(()=>{if(document.body.dataset.screen==='receivers')refresh();},1500);
refresh();setInterval(()=>{if(!document.hidden && $('rx-cards')?.getClientRects().length)refresh();},1000);
}
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
+1
View File
@@ -19,6 +19,7 @@
.registry-workspace #search-count{display:block;color:var(--work-muted);font-size:12px}.registry-workspace #search-count:empty{display:none}
.registry-workspace #new-registration{margin:0;width:100%;min-height:42px}
.registry-workspace .history-toolbar{display:flex;justify-content:space-between;gap:10px;align-items:center}
.registry-workspace .archiveTools{display:flex;flex-direction:column;gap:12px}
.registry-workspace #selection-toggle,.registry-workspace #export-toggle{font-size:12px;padding:7px 11px;min-height:34px}
.registry-workspace .select-all{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--work-muted)}
.registry-workspace .history-message,.registry-workspace .history-empty,.registry-workspace .archive-warning{margin:0;color:var(--work-muted);font-size:12px;line-height:1.8;overflow-wrap:anywhere}
+296 -86
View File
@@ -5,9 +5,9 @@ use leptos::prelude::*;
use serde_json::Value;
use std::sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
atomic::{AtomicU64, Ordering},
};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_futures::spawn_local;
#[derive(Clone, Copy)]
@@ -28,6 +28,31 @@ struct State {
speed: RwSignal<u32>,
busy: RwSignal<bool>,
status: RwSignal<String>,
record: RwSignal<Option<ReplayRecord>>,
}
#[derive(Clone)]
struct ReplayRecord {
flight_key: String,
target_id: String,
start_ms: u64,
end_ms: Option<u64>,
}
impl ReplayRecord {
fn from_event(event: &web_sys::CustomEvent) -> Option<Self> {
let value: Value = serde_json::from_str(&event.detail().as_string()?).ok()?;
let flight_key = value["flightKey"].as_str()?;
if flight_key.len() != 32 || !flight_key.bytes().all(|c| c.is_ascii_hexdigit()) {
return None;
}
Some(Self {
flight_key: flight_key.to_owned(),
target_id: value["targetId"].as_str()?.to_owned(),
start_ms: value["timeMs"].as_u64()?,
end_ms: value["endMs"].as_u64(),
})
}
}
#[derive(Clone, Default)]
@@ -47,14 +72,40 @@ fn map_call(method: &str, args: &[JsValue]) -> Result<JsValue, JsValue> {
function.apply(&api, &array)
}
fn send_points(points: &[Value]) {
fn send_points(points: &[Value], target: Option<&str>) {
if let Ok(text) = serde_json::to_string(points)
&& let Ok(value) = js_sys::JSON::parse(&text)
{
let _ = map_call("setPoints", &[value]);
let _ = map_call(
"setPoints",
&[
value,
target.map(JsValue::from_str).unwrap_or(JsValue::UNDEFINED),
],
);
}
}
fn prepare_points(points: &[Value]) -> Result<(Vec<Value>, u64, u64), String> {
let invalid = || "无法处理轨迹数据".to_owned();
let text = serde_json::to_string(points).map_err(|_| invalid())?;
let samples = js_sys::JSON::parse(&text).map_err(|_| invalid())?;
let prepared = map_call("prepareTrack", &[samples]).map_err(|_| invalid())?;
let text: String = js_sys::JSON::stringify(&prepared)
.map_err(|_| invalid())?
.into();
let mut value: Value = serde_json::from_str(&text).map_err(|_| invalid())?;
let points = value["points"]
.as_array_mut()
.map(std::mem::take)
.ok_or_else(invalid)?;
Ok((
points,
value["skipped"].as_u64().unwrap_or(0),
value["newSegments"].as_u64().unwrap_or(0),
))
}
fn visible() -> bool {
web_sys::window()
.and_then(|w| w.document())
@@ -171,7 +222,7 @@ fn list(state: State, requests: Requests, append: bool) {
state.index.set(0);
state.next_offset.set(None);
requests.points.fetch_add(1, Ordering::Relaxed);
send_points(&[]);
send_points(&[], None);
(from, to, query, 0)
};
let generation = requests.targets.fetch_add(1, Ordering::Relaxed) + 1;
@@ -214,7 +265,7 @@ fn list(state: State, requests: Requests, append: bool) {
});
}
fn load_points(state: State, requests: Requests, id: String) {
fn load_points(state: State, requests: Requests, id: String, flight_key: Option<String>) {
let (from, to) = state.range.get_untracked();
let generation = requests.points.fetch_add(1, Ordering::Relaxed) + 1;
state.selected.set(id.clone());
@@ -223,15 +274,20 @@ fn load_points(state: State, requests: Requests, id: String) {
state.playing.set(false);
state.busy.set(true);
state.status.set("正在读取轨迹…".into());
send_points(&[]);
send_points(&[], None);
spawn_local(async move {
let mut all = Vec::new();
let mut after = 0u64;
let result = loop {
let url = format!(
"/api/history/points?targetId={}&fromMs={from}&toMs={to}&limit=5000&after={after}",
js_sys::encode_uri_component(&id)
);
let url = match &flight_key {
Some(key) => {
format!("/api/history/flight-points?flightKey={key}&limit=5000&after={after}")
}
None => format!(
"/api/history/points?targetId={}&fromMs={from}&toMs={to}&limit=5000&after={after}",
js_sys::encode_uri_component(&id)
),
};
let value = match fetch(&url).await {
Ok(value) => value,
Err(error) => break Err(error),
@@ -256,18 +312,27 @@ fn load_points(state: State, requests: Requests, id: String) {
return;
}
state.busy.set(false);
match result {
Ok(()) => {
if let Some(time) = all.first().and_then(|p| p["timeMs"].as_u64()) {
match result.and_then(|()| prepare_points(&all)) {
Ok((points, skipped, new_segments)) => {
if let Some(time) = points.first().and_then(|p| p["timeMs"].as_u64()) {
state.play_time.set(time as f64);
}
send_points(&all);
let count = all.len();
state.points.set(all);
send_points(&points, Some(&id));
let count = points.len();
state.points.set(points);
state
.playing
.set(flight_key.is_some() && count > 1 && visible());
state.status.set(if count == 0 {
"该时段没有轨迹点。".into()
if flight_key.is_some() {
"这条记录暂无有效定位,当前无法回放。".into()
} else {
"该时段没有轨迹点。".into()
}
} else if skipped > 0 || new_segments > 0 {
format!("已加载 {count} 个采样点。已略过 {skipped} 个异常点,另有 {new_segments} 处采样间隔或定位跳变已断开。")
} else {
format!("已加载 {count} 个采样点;位置丢失和接收来源切换处会断开轨迹。")
format!("已加载 {count} 个采样点。定位中断和接收来源切换处会断开轨迹。")
});
}
Err(error) => state.status.set(error),
@@ -275,6 +340,79 @@ fn load_points(state: State, requests: Requests, id: String) {
});
}
fn playback_number(value: &Value, precision: usize, unit: &str) -> String {
value
.as_f64()
.map(|number| format!("{number:.precision$} {unit}"))
.unwrap_or_else(|| "—".into())
}
fn point_progress(points: &[Value], index: usize, time: f64) -> f64 {
let Some(from) = points.get(index).and_then(|point| point["timeMs"].as_f64()) else {
return 0.0;
};
match points
.get(index + 1)
.and_then(|point| point["timeMs"].as_f64())
{
Some(to) if to > from => ((time - from) / (to - from)).clamp(0.0, 1.0),
_ => 0.0,
}
}
fn advance_playback(state: State, elapsed: f64) -> bool {
let current = state.index.get_untracked();
let next = state.play_time.get_untracked() + elapsed * f64::from(state.speed.get_untracked());
let (index, time, finished) = state.points.with_untracked(|points| {
let Some(last) = points.last() else {
return (0, 0.0, true);
};
let mut index = current.min(points.len() - 1);
let mut time = next;
while let Some(following) = points.get(index + 1) {
let current_time = points[index]["timeMs"].as_f64().unwrap_or(time);
let following_time = following["timeMs"].as_f64().unwrap_or(current_time);
if following_time < current_time {
// A wall-clock change begins a new playback segment.
time = following_time;
} else if following_time > time {
break;
}
index += 1;
}
let end = last["timeMs"].as_f64().unwrap_or(time);
let finished = index + 1 == points.len() && time >= end;
(index, if finished { end } else { time }, finished)
});
state.play_time.set(time);
if index != current {
state.index.set(index);
}
if finished {
state.playing.set(false);
}
!finished
}
fn seek_playback(state: State, value: f64) {
state.playing.set(false);
let (index, time) = state.points.with_untracked(|points| {
let value = value.clamp(0.0, points.len().saturating_sub(1) as f64);
let index = value.floor() as usize;
let from = points
.get(index)
.and_then(|point| point["timeMs"].as_f64())
.unwrap_or(0.0);
let to = points
.get(index + 1)
.and_then(|point| point["timeMs"].as_f64())
.unwrap_or(from);
(index, from + (to - from).max(0.0) * value.fract())
});
state.index.set(index);
state.play_time.set(time);
}
#[component]
pub fn History() -> impl IntoView {
let now = js_sys::Date::now();
@@ -295,70 +433,43 @@ pub fn History() -> impl IntoView {
speed: RwSignal::new(1),
busy: RwSignal::new(false),
status: RwSignal::new(String::new()),
record: RwSignal::new(None),
};
let requests = Requests::default();
list(state, requests.clone(), false);
Effect::new(move |_| {
let _ = map_call("setIndex", &[JsValue::from_f64(state.index.get() as f64)]);
let cursor = Memo::new(move |_| {
let index = state.index.get();
let time = state.play_time.get();
let progress = state
.points
.with(|points| point_progress(points, index, time));
(index, progress)
});
let stopped = Arc::new(AtomicBool::new(false));
let end = stopped.clone();
on_cleanup(move || end.store(true, Ordering::Relaxed));
spawn_local(async move {
let mut last = None;
while !stopped.load(Ordering::Relaxed) {
TimeoutFuture::new(200).await;
if stopped.load(Ordering::Relaxed) {
break;
}
if !visible() {
state.playing.set(false);
last = None;
continue;
}
if !state.playing.get_untracked() {
last = None;
continue;
}
let now = js_sys::Date::now();
let elapsed = last
.map(|previous: f64| (now - previous).max(0.0))
.unwrap_or(0.0);
last = Some(now);
let next =
state.play_time.get_untracked() + elapsed * f64::from(state.speed.get_untracked());
let (index, time, finished) = state.points.with_untracked(|points| {
if points.is_empty() {
return (0, 0.0, true);
}
let mut index = state.index.get_untracked().min(points.len() - 1);
let mut time = next;
while index + 1 < points.len() {
let current = points[index]["timeMs"].as_f64().unwrap_or(time);
let following = points[index + 1]["timeMs"].as_f64().unwrap_or(current);
if following < current {
// A wall-clock adjustment starts a new segment.
index += 1;
time = following;
} else if following <= time {
index += 1;
} else {
break;
}
}
let end = points
.last()
.and_then(|p| p["timeMs"].as_f64())
.unwrap_or(time);
let finished = index + 1 == points.len() && time >= end;
(index, if finished { end } else { time }, finished)
});
state.play_time.set(time);
state.index.set(index);
if finished {
state.playing.set(false);
}
Effect::new(move |_| {
let (index, progress) = cursor.get();
let _ = map_call(
"setCursor",
&[JsValue::from_f64(index as f64), JsValue::from_f64(progress)],
);
});
Effect::new(move |_| {
if !state.playing.get() {
let _ = map_call("stopClock", &[]);
return;
}
let frame = Closure::<dyn FnMut(f64) -> bool>::new(move |elapsed: f64| {
if !visible() || !state.playing.get_untracked() {
state.playing.set(false);
return false;
}
advance_playback(state, elapsed)
});
if map_call("startClock", &[frame.into_js_value()]).is_err() {
state.playing.set(false);
}
});
on_cleanup(|| {
let _ = map_call("stopClock", &[]);
});
let error = window_event_listener(
leptos::ev::Custom::new("rid-history-map-error"),
@@ -373,19 +484,81 @@ pub fn History() -> impl IntoView {
let view = window_event_listener(
leptos::ev::Custom::new("rid-workspace-view"),
move |_: web_sys::Event| {
if visible() && state.auto_range.get_untracked() {
if !visible() {
if state.playing.get_untracked() {
state.playing.set(false);
}
if state.record.get_untracked().is_some() {
view_requests.points.fetch_add(1, Ordering::Relaxed);
state.record.set(None);
state.selected.set(String::new());
state.points.set(vec![]);
state.busy.set(false);
send_points(&[], None);
}
} else if state.auto_range.get_untracked() && state.record.get_untracked().is_none() {
list(state, view_requests.clone(), false);
}
},
);
on_cleanup(move || view.remove());
let record_requests = requests.clone();
let record_event = window_event_listener(
leptos::ev::Custom::new("rid-history-record"),
move |event: web_sys::Event| {
if !visible() {
return;
}
let record = event
.dyn_into::<web_sys::CustomEvent>()
.ok()
.as_ref()
.and_then(ReplayRecord::from_event);
if let Some(record) = record {
record_requests.targets.fetch_add(1, Ordering::Relaxed);
state.record.set(Some(record.clone()));
load_points(
state,
record_requests.clone(),
record.target_id,
Some(record.flight_key),
);
if let Some(heading) = web_sys::window()
.and_then(|w| w.document())
.and_then(|document| document.get_element_by_id("history-playback-title"))
.and_then(|element| element.dyn_into::<web_sys::HtmlElement>().ok())
{
let _ = heading.focus();
}
} else if state.record.get_untracked().is_some() {
state.record.set(None);
list(state, record_requests.clone(), false);
}
},
);
on_cleanup(move || record_event.remove());
let search_requests = requests.clone();
let more_requests = requests.clone();
let target_requests = requests.clone();
view! {
<div class="history-workspace">
<aside class="history-sidebar" aria-label="历史轨迹查询">
<h1>"历史轨迹"</h1><p>"按目标和时间范围查找已保存的位置。"</p>
<h1 id="history-playback-title" tabindex="-1">{move||if state.record.with(Option::is_some){"轨迹回放"}else{"历史轨迹"}}</h1>
<Show when=move||state.record.with(Option::is_some)>
<button type="button" on:click=move |_|{
if let Some(window)=web_sys::window()
&& let Ok(event)=web_sys::Event::new("rid-history-return-records") {
let _ = window.dispatch_event(&event);
}
}>"返回记录查询"</button>
<dl class="history-record-details">
<dt>"UAS ID"</dt><dd>{move||state.record.with(|r|r.as_ref().map(|r|r.target_id.clone()).unwrap_or_default())}</dd>
<dt>"开始时间"</dt><dd>{move||state.record.with(|r|r.as_ref().map(|r|display_time(r.start_ms)).unwrap_or_default())}</dd>
<dt>"结束时间"</dt><dd>{move||state.record.with(|r|r.as_ref().and_then(|r|r.end_ms).map(display_time).unwrap_or_else(||"接收中".into()))}</dd>
</dl>
</Show>
<div class="history-query" hidden=move||state.record.with(Option::is_some)>
<p>"按目标和时间范围查找已保存的位置。"</p>
<label>"目标标识"<input type="search" placeholder="搜索目标标识" prop:value=move||state.query.get() on:input=move|e|state.query.set(event_target_value(&e))/></label>
<label>"开始时间"<input type="datetime-local" step="1" prop:value=move||state.from.get() on:input=move|e|{state.auto_range.set(false);state.from.set(event_target_value(&e));}/></label>
<label>"结束时间"<input type="datetime-local" step="1" prop:value=move||state.to.get() on:input=move|e|{state.auto_range.set(false);state.to.set(event_target_value(&e));}/></label>
@@ -398,14 +571,15 @@ pub fn History() -> impl IntoView {
let first=entry["firstMs"].as_u64().map(display_time).unwrap_or_default();
let last=entry["lastMs"].as_u64().map(display_time).unwrap_or_default();
let count=entry["pointCount"].as_u64().unwrap_or(0);
view!{<button type="button" disabled=move||state.busy.get() aria-pressed=move||(state.selected.get()==selected_id).to_string() on:click=move |_|load_points(state,requests.clone(),request_id.clone())><strong>{id}</strong><small>{format!("{first} — {last}")}</small><small>{format!("{count} 个采样点")}</small></button>}
view!{<button type="button" disabled=move||state.busy.get() aria-pressed=move||(state.selected.get()==selected_id).to_string() on:click=move |_|load_points(state,requests.clone(),request_id.clone(),None)><strong>{id}</strong><small>{format!("{first} — {last}")}</small><small>{format!("{count} 个采样点")}</small></button>}
}/>
</div>
<button hidden=move||state.next_offset.get().is_none() disabled=move||state.busy.get() on:click=move |_|list(state,more_requests.clone(),true)>"加载更多目标"</button>
</div>
<p class="history-status" role="status">{move||state.status.get()}</p>
</aside>
<section class="history-main" aria-label="轨迹地图与回放">
<div class="history-map-shell"><div id="history-map" aria-label="历史轨迹地图"></div><span class="history-map-banner">{move||if state.selected.get().is_empty(){"历史轨迹".into()}else{format!("{} · 历史轨迹",state.selected.get())}}</span><div class="history-map-empty" hidden=move||!state.points.get().is_empty()>"选择目标后显示历史轨迹"</div></div>
<div class="history-map-shell"><div id="history-map" aria-label="历史轨迹地图"></div><span class="history-map-banner">{move||if state.selected.get().is_empty(){"历史轨迹".into()}else{format!("{} · 历史轨迹",state.selected.get())}}</span><div class="history-map-empty" hidden=move||!state.points.get().is_empty()>{move||if state.busy.get(){"正在读取轨迹…"}else if state.record.with(Option::is_some){"暂无可显示的轨迹点"}else{"选择目标后显示历史轨迹"}}</div></div>
<div class="track-playback-controls">
<div class="track-playback-controls-head"><h2>"回放控制"</h2><span class="history-space"></span><p class="history-warning">"历史画面,不代表实时位置;未核实坐标不记录。"</p></div>
<div class="history-playback">
@@ -416,13 +590,49 @@ pub fn History() -> impl IntoView {
state.playing.update(|v| *v = !*v);
}>{move||if state.playing.get(){"暂停"}else{"播放"}}</button>
<span class="history-time">{move||state.points.with(|p|p.get(state.index.get()).and_then(|p|p["timeMs"].as_u64()).map(display_time).unwrap_or_else(||"—".into()))}</span>
<input type="range" min="0" max=move||state.points.with(|p|p.len().saturating_sub(1).to_string()) prop:value=move||state.index.get().to_string() disabled=move||state.points.with(Vec::is_empty) aria-label="回放进度" on:input=move|e|{
let index=event_target_value(&e).parse::<usize>().unwrap_or(0);
state.playing.set(false);state.index.set(index);
if let Some(t)=state.points.with_untracked(|p|p.get(index).and_then(|p|p["timeMs"].as_f64())){state.play_time.set(t);}
<input type="range" min="0" step="0.01" max=move||state.points.with(|p|p.len().saturating_sub(1).to_string()) prop:value=move||{
let (index, progress)=cursor.get();
format!("{:.2}",index as f64 + progress)
} disabled=move||state.points.with(Vec::is_empty) aria-label="回放进度" on:input=move|e|{
if let Ok(value)=event_target_value(&e).parse::<f64>() && value.is_finite() {
seek_playback(state, value);
}
}/>
<button on:click=move |_|state.speed.update(|v|*v=match *v{1=>4,4=>16,16=>64,_=>1}) aria-label="切换回放速度">{move||format!("{}×",state.speed.get())}</button>
</div>
<div class="history-osd" hidden=move||state.points.with(Vec::is_empty) aria-label="轨迹点 OSD">
{move||state.points.with(|points| points.get(state.index.get()).map(|point| {
let osd = &point["osd"];
let mut heights = [
("椭球高", &point["altitudeM"]),
("几何高度", &osd["geometricAltitudeM"]),
("气压高度", &osd["pressureAltitudeM"]),
(if osd["relativeHeightM"].is_number() {"离地高度"} else {"相对高度"}, &osd["heightAglM"]),
("相对高度", &osd["relativeHeightM"]),
].into_iter()
.filter(|(_, value)| value.is_number())
.map(|(label, value)| format!("{label} {}", playback_number(value, 1, "m")))
.collect::<Vec<_>>();
if heights.is_empty() { heights.push("高度 未记录".into()); }
let position = match (point["latitude"].as_f64(), point["longitude"].as_f64()) {
(Some(lat), Some(lon)) => format!("{lat:.6}, {lon:.6}"),
_ => "—".into(),
};
let pilot = osd["pilotPosition"].as_array().and_then(|coords| {
let [lon, lat] = coords.as_slice() else { return None };
Some(format!("{:.6}, {:.6}", lat.as_f64()?, lon.as_f64()?))
});
view! {
<span>"坐标 "{position}</span>
{heights.into_iter().map(|height|view!{<span>{height}</span>}).collect::<Vec<_>>()}
<span>"速度 "{playback_number(&osd["speedMps"], 1, "m/s")}</span>
<span>"升降速度 "{playback_number(&osd["verticalSpeedMps"], 1, "m/s")}</span>
<span>"航向 "{playback_number(&point["headingDeg"], 0, "°")}</span>
<span>"RSSI "{playback_number(&osd["rssi"], 0, "dBm")}</span>
{pilot.map(|position|view!{<span>"飞手坐标 "{position}</span>})}
}
}))}
</div>
<p>"每个目标通常每秒保存一个点;数据仅保存在本机,不自动删除。"</p>
</div>
</section>
+14 -7
View File
@@ -10,17 +10,20 @@ mod target_lists;
mod workspace;
fn main() {
let realtime = web_sys::window()
let path = web_sys::window()
.unwrap()
.location()
.pathname()
.unwrap_or_default()
== "/realtime";
.unwrap_or_default();
let embedded = path == "/workbench/module.html";
let realtime = path == "/realtime";
mount_to_body(move || {
let lists = target_lists::Lists::new();
view! {
<div inner_html=include_str!("workspace.html")/>
<section id="geofence-view" class="workspace-pane" tabindex="-1" aria-label="电子围栏" hidden inner_html=include_str!("geofences.html")/>
{(!embedded).then(|| view!{
<div inner_html=include_str!("workspace.html")/>
<section id="geofence-view" class="workspace-pane" tabindex="-1" aria-label="电子围栏" hidden inner_html=include_str!("geofences.html")/>
})}
<section id="map-settings-view" class="workspace-pane" tabindex="-1" aria-label="地图配置" hidden inner_html=include_str!("map_settings.html")/>
<section id="target-lists-view" class="workspace-pane" tabindex="-1" aria-label="黑白名单管理" hidden><target_lists::Manager lists=lists/></section>
<section id="receivers-view" class="workspace-pane" tabindex="-1" aria-label="设备管理" hidden inner_html=include_str!("receivers.html")/>
@@ -32,8 +35,12 @@ fn main() {
}
});
map_settings::init();
geofences::init();
workspace::init(realtime);
if embedded {
workspace::init_embedded();
} else {
geofences::init();
workspace::init(realtime);
}
if !realtime {
registry::init();
}
+1 -1
View File
@@ -24,7 +24,7 @@
<div class="map-settings-scroll">
<section id="map-step-region" tabindex="-1" aria-label="选择区域"><h3 class="map-section-title">选择下载区域</h3><p class="map-settings-small">先确定范围,再设置图层与精度。</p><label class="map-settings-label">常用区域<select id="map-region"><option value="">选择已保存的区域…</option></select></label><button class="map-current" data-map-action="box">在地图上框选范围</button><p id="map-bounds-summary" class="map-range-summary">尚未选择范围</p><details class="map-advanced"><summary>精确坐标与常用区域管理</summary><div class="map-settings-fields"><label class="map-settings-label">西侧经度<input id="map-west" type="number" min="-180" max="180" step="0.000001"></label><label class="map-settings-label">南侧纬度<input id="map-south" type="number" min="-85.051128" max="85.051128" step="0.000001"></label><label class="map-settings-label">东侧经度<input id="map-east" type="number" min="-180" max="180" step="0.000001"></label><label class="map-settings-label">北侧纬度<input id="map-north" type="number" min="-85.051128" max="85.051128" step="0.000001"></label></div><label class="map-settings-label">常用区域名称<input id="map-region-name" maxlength="40" placeholder="填写区域名称"></label><div class="map-settings-actions"><button data-map-action="region-save">加入常用</button><button data-map-action="region-delete">移除所选</button></div><button id="map-region-persist" data-map-action="save-regions" disabled>保存区域更改</button><div id="map-region-message" class="map-settings-message" role="status" aria-live="polite">区域编辑后需保存到本机。</div></details></section>
<section id="map-step-layers" tabindex="-1" aria-label="图层与精度" hidden><h3 class="map-section-title">图层与精度</h3><p class="map-settings-small">层级越高,细节越丰富,下载量也越大。</p><div class="map-settings-fields"><label class="map-settings-label">起始层级<input id="map-min-zoom" type="number" min="0" max="18" value="10"></label><label class="map-settings-label">结束层级<input id="map-max-zoom" type="number" min="0" max="18" value="14"></label></div><div class="map-layer-choices"><label><input type="checkbox" id="map-download-road" checked> 路网与标注</label><label><input type="checkbox" id="map-download-imagery" checked> 影像与标注</label></div><p class="map-settings-small">单次最多 20000 张瓦片,核算成功后才能开始下载。</p></section>
<section id="map-step-review" tabindex="-1" aria-label="核算与下载" hidden><h3 class="map-section-title">确认下载任务</h3><p id="map-download-summary" class="map-range-summary"></p><p class="map-settings-small" id="map-estimate-message">尚未核算。</p><button id="map-estimate" data-map-action="estimate">重新核算</button><progress id="map-download-progress" value="0" max="1" aria-label="离线地图下载进度"></progress><p class="map-settings-small">仅手动开始下载。已完成瓦片可复用;失败或取消不视为完整离线包,实际大小以下载结果为准。</p></section>
<section id="map-step-review" tabindex="-1" aria-label="核算与下载" hidden><h3 class="map-section-title">确认下载任务</h3><p id="map-download-summary" class="map-range-summary"></p><p class="map-settings-small" id="map-estimate-message">尚未核算。</p><button id="map-estimate" data-map-action="estimate">重新核算</button><progress id="map-download-progress" value="0" max="1" aria-label="离线地图下载进度"></progress><p class="map-settings-small">瓦片保存到数据目录下的 <code>map_cache</code>。将该文件夹放在 EXE 旁,程序启动后会自动读取。失败或取消后可重试,已完成的瓦片会复用。</p></section>
</div>
<footer class="map-panel-footer"><div id="map-step-message" class="map-settings-message" role="status" aria-live="polite"></div><div id="map-download-message" class="map-settings-message" role="status" aria-live="polite">暂无下载任务</div><div class="map-footer-actions"><button id="map-step-back" data-map-action="previous" hidden>上一步</button><button id="map-step-next" class="primary" data-map-action="next">下一步</button><button class="primary" id="map-download-start" data-map-action="start" disabled hidden>开始下载</button><button id="map-download-cancel" data-map-action="cancel" disabled hidden>取消任务</button></div></footer>
</section>
+5 -5
View File
@@ -322,13 +322,13 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
continue;
}
let target = entry["target_id"].as_str().unwrap_or("");
let message = if entry["event_type"] == "blacklist" {
format!("黑名单命中:{target}")
} else {
format!(
let message = match entry["event_type"].as_str() {
Some("blacklist") => format!("黑名单命中:{target}"),
Some("unregistered") => format!("未登记无人机:{target}"),
_ => format!(
"围栏进入:{target} · {}",
entry["fence_name"].as_str().unwrap_or("")
)
),
};
log_event_at(events, message, entry["occurred_at_ms"].as_u64());
cursor = cursor.max(id);
+6 -4
View File
@@ -2,9 +2,11 @@
<div class="rx-toolbar"><label>查找设备 <input id="rx-search" type="search" placeholder="名称、串口或接收机 ID"></label><span id="rx-summary" role="status">正在加载接收机…</span><button class="primary" id="rx-add">+ 添加接收机</button><button id="rx-refresh">刷新</button></div>
<section class="rx-surface" aria-label="接收机列表区域">
<p id="rx-error" class="rx-error" role="alert" hidden></p>
<p class="rx-legend"><span><i class="rx-dot ok" aria-hidden="true"></i>正在接收</span><span><i class="rx-dot info" aria-hidden="true"></i>连接中或等待</span><span><i class="rx-dot warn" aria-hidden="true"></i>失败、不匹配或待核实</span><span><i class="rx-dot idle" aria-hidden="true"></i>未启用</span><span>身份用描边标记,和连接状态分开</span></p>
<div id="rx-cards" class="rx-cards"></div><p id="rx-empty" hidden>没有匹配的接收机。</p>
<p class="rx-footnote">卡片标题用芯片和 USB 插口区分设备。两只相同的 CH340,看「集线器 · 端口」对应哪个插口。乐鑫调试口等其他串口默认停用,需要时再启用。蓝牙串口不会自动加入。</p>
<nav class="rid-pager" aria-label="接收器诊断分页">
<span id="rx-page-summary" class="rid-page-summary"></span>
<div class="rid-pager-actions"><button id="rx-page-prev" type="button" disabled>上一页</button><span id="rx-page-number" class="rid-page-number" tabindex="-1" aria-live="polite"></span><button id="rx-page-next" type="button" disabled>下一页</button></div>
</nav>
</section>
<div id="rx-pop" class="rx-pop" role="dialog" aria-label="其余提示" hidden></div>
</div>
@@ -14,9 +16,9 @@
<label>连接方式<select name="transport"><option value="serial">USB 串口</option><option value="udp">UDP 接收监听</option><option value="tcp-listen">TCP 接收监听</option></select></label>
<div id="rx-serial-fields"><label>串口<input name="serialPort" list="rx-port-options" placeholder="例如 COM16"><datalist id="rx-port-options"></datalist></label><label>波特率<input name="baudRate" type="number" min="1200" max="4000000" value="115200"></label></div>
<div id="rx-network-fields" hidden><label>监听 IP<input name="bindIp" value="127.0.0.1"></label><label>监听端口<input name="port" type="number" min="1" max="65535" value="8788"></label></div>
<label>报文协议<select name="format"><option value="raw">原始诊断(不生成目标)</option><option value="uid-json">UID / ua_* JSON</option><option value="rid-device-json">RID 设备 JSON(message / uav)</option><option value="json-lines">约定 JSON / JSON Lines</option><option value="postcard">约定 Postcard</option></select></label>
<label id="rx-peer-fields" hidden>允许来源 IP<input name="peerIp" maxlength="45" placeholder="设备 IP,可留空"></label>
<div id="rx-uid-fields" hidden><label>UID 身份范围<select name="uidIdentity"><option value="source-scoped">按接收机隔离(默认)</option><option value="global-device">跨接收机合并(已确认 UID 唯一)</option></select></label><p class="rx-note">仅在设备协议确认 UID 唯一对应无人机时启用合并。切换身份范围后,原有人工关联和名单不会自动迁移;同一接收机发出相同 UID 且没有其他身份字段时无法区分多架飞机。</p></div>
<p id="rx-protocol-note" class="rx-note"></p><p class="rx-footnote">只读接收;修改连接参数会重启当前接收任务。</p>
<p class="rx-footnote">只读接收;修改连接参数会重启当前接收任务。</p>
<div class="rx-actions"><button class="primary" id="rx-save" type="submit">保存配置</button><button id="rx-delete" type="button">删除接收机</button></div>
</form>
<section id="rx-diagnostic" hidden><p id="rx-status-label"></p><dl id="rx-stats"></dl><button id="rx-capture" type="button">读取最新原始报文</button><pre id="rx-raw">尚未读取。最多显示最近 4 KiB。</pre></section>
+10 -8
View File
@@ -1,11 +1,11 @@
<div class="registry-workspace">
<aside class="history-panel" aria-labelledby="history-title"><header class="history-heading"><h2 id="history-title">本地档案</h2><button id="refresh-list" type="button" aria-label="刷新记录" title="刷新记录">↻</button></header><div class="history-content">
<div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号或机型"><span id="search-count" aria-live="polite"></span></div>
<div class="archiveTools"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号或机型"><span id="search-count" aria-live="polite"></span></div>
<button id="new-registration" type="button" class="primary">+ 新建设备登记</button>
<div class="history-toolbar"><button id="selection-toggle" type="button" aria-pressed="false">选择</button><div class="export-controls"><button id="export-toggle" type="button" disabled aria-expanded="false" aria-controls="export-options">导出⌄</button><div id="export-options" class="registry-popup" hidden><button id="export-archive" type="button" disabled>导出档案包</button><button id="export-excel" type="button" disabled>导出 Excel</button><p>仅导出当前页已选档案</p></div></div></div>
<div id="selection-controls" hidden><label class="select-all"><input id="select-all" type="checkbox">全选当前页 <span id="selected-count">(0)</span></label></div>
</div><div id="selection-controls" hidden><label class="select-all"><input id="select-all" type="checkbox">全选当前页 <span id="selected-count">(0)</span></label></div>
<p class="history-message" id="history-message" role="status"></p><div id="history-empty" class="history-empty">正在读取档案…</div><div id="history-cards" class="history-cards"></div>
</div><nav class="pagination" aria-label="档案分页"><span id="page-status" aria-live="polite"></span><div><button id="previous-page" type="button">上一页</button><button id="next-page" type="button">下一页</button></div></nav>
</div><nav id="page-status" class="pagination rid-pager" aria-label="档案分页"><span id="page-count" class="rid-page-summary"></span><div class="rid-pager-actions"><button id="previous-page" type="button">上一页</button><span id="archive-page-number" class="rid-page-number" aria-live="polite"></span><button id="next-page" type="button">下一页</button></div></nav>
<p id="archive-warning" class="archive-warning" role="status" hidden><span id="archive-warning-text"></span> <button id="retry-archive" type="button">重试同步</button></p></aside>
<section class="registration-editor" aria-labelledby="register-title"><header class="registration-heading"><div><h1 id="register-title">新建设备登记</h1><p>填写设备信息,生成本机登记二维码</p></div><span></span></header>
<form id="register-form" aria-labelledby="register-title" novalidate><div class="registration-fields-scroll"><section class="registry-group"><div class="registry-group-heading"><h2>设备身份</h2><span>仅模块 SN 必填</span></div><div class="registration-fields"><div class="registration-field full"><label for="serial-no">模块 SN <span aria-hidden="true">*</span></label><input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" pattern="[A-Za-z0-9\-]{6,40}" aria-describedby="serial-no-hint serial-no-error" placeholder="输入完整模块序列号"><p id="serial-no-hint" class="registry-help">6–40 位英文字母、数字或半角连字符 -;请填写设备实际 SN,不支持中文名称。</p><p id="serial-no-error" class="form-message error" role="alert" hidden></p></div><div class="registration-field"><label for="model-name">机型 <small>选填</small></label><input id="model-name" name="modelName" maxlength="60" placeholder="例如:5 寸穿越机"></div><div class="registration-field"><label for="owner-name">登记人 / 备注 <small>选填</small></label><input id="owner-name" name="ownerName" maxlength="40" placeholder="方便后续查找"></div></div><p class="registry-help">SN 需与上位机模块一致;相同 SN 再次保存将更新原档案。</p></section>
@@ -13,7 +13,7 @@
<section class="registry-group"><div class="registry-group-heading"><h2>设备照片</h2><span>选填 · 最多 2 张</span></div><div class="registration-photos"><div class="photo-slot"><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="0" hidden><button type="button" class="photo-pick" data-photo-choose="0" aria-label="添加照片 1"><img id="slot-preview-0" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 1</strong><span id="slot-name-0">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="0" id="slot-remove-0" hidden>移除照片</button></div><button type="button" data-photo-keep="0" id="slot-keep-0" hidden>保留原选择</button><p id="slot-status-0" class="photo-status" role="status"></p></div><div class="photo-slot"><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="1" hidden><button type="button" class="photo-pick" data-photo-choose="1" aria-label="添加照片 2"><img id="slot-preview-1" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>添加照片 2</strong><span id="slot-name-1">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="1" id="slot-remove-1" hidden>移除照片</button></div><button type="button" data-photo-keep="1" id="slot-keep-1" hidden>保留原选择</button><p id="slot-status-1" class="photo-status" role="status"></p></div></div><p class="registry-help">JPG、PNG、WebP · 每张不超过 5 MB · 仅保存在本机档案</p></section>
<p class="form-message" id="form-message" role="status"></p></div><div class="registration-savebar"><span id="draft-state">保存时校验 SN 与编号</span><button class="primary" id="register-button" type="submit">保存登记并生成二维码 →</button></div></form></section><section class="result-panel registry-group" aria-labelledby="result-title" id="registration-result" tabindex="-1"><header class="result-heading"><h2 id="result-title">二维码与核验</h2><button id="close-archive-detail" type="button" hidden>返回列表</button></header>
<div id="empty-result" class="empty-state"><div class="empty-glyph"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M3 3h6v6H3z M15 3h6v6h-6z M3 15h6v6H3z M14 14h3v3h4v4h-7z"/></svg></div><div><b>等待完成登记</b><p>保存后自动生成二维码,供本地版上位机读取和核验。</p></div><ol><li>填写模块 SN</li><li>保存登记并生成二维码</li><li>在本地版上位机核验</li></ol></div><div id="record-result" class="record-result" hidden>
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
<div class="qr-stage" id="qr-stage" aria-label="可离线扫描的无人机登记标签码"></div>
<div class="record-kicker" id="result-context" role="status"></div>
<p class="result-fpv-label">FPV 编号</p>
<div class="uas-display" id="display-uas"></div>
@@ -22,11 +22,13 @@
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
</div>
<div class="url-box"><span>二维码内容</span><code id="display-url"></code></div>
<div class="result-actions"><button id="download-qr" class="secondary" type="button">下载二维码 PNG</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
<p class="result-tip">扫码读取登记编号、模块 SN、机型和登记信息。修改档案后可重新打印标签。</p>
<div class="result-actions"><button id="print-label" class="primary" type="button">打印标签</button><button id="download-qr" class="secondary" type="button">下载标签码 PNG</button></div>
<p id="label-feedback" class="form-message" role="status"></p>
<div class="url-box"><span>本机档案核验链接</span><code id="display-url"></code></div>
<div class="result-actions"><button id="download-local-qr" class="secondary" type="button">下载本机档案码</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
<div class="result-actions"><a id="open-card" class="secondary action-link" target="_blank" rel="noopener">打开档案卡</a><a id="download-card" class="ghost action-link">下载离线档案卡</a></div>
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
</div>
</section>
</div>
<dialog id="edit-dialog" aria-labelledby="edit-title"><form id="edit-form"><header><h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="registry-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p></header><div class="registration-fields"><div class="registration-field"><label for="edit-model">机型</label><input id="edit-model" maxlength="60"></div><div class="registration-field"><label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40"></div></div><div class="edit-photos"><fieldset><legend>照片 1</legend><div class="photo-slot"><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="2" hidden><button type="button" class="photo-pick" data-photo-choose="2" aria-label="替换照片 1"><img id="slot-preview-2" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 1</strong><span id="slot-name-2">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="2" id="slot-remove-2" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="2" id="slot-keep-2" hidden>保留原选择</button><p id="slot-status-2" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset><fieldset><legend>照片 2</legend><div class="photo-slot"><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="3" hidden><button type="button" class="photo-pick" data-photo-choose="3" aria-label="替换照片 2"><img id="slot-preview-3" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 2</strong><span id="slot-name-3">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="3" id="slot-remove-3" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="3" id="slot-keep-3" hidden>保留原选择</button><p id="slot-status-3" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset></div><p id="edit-message" class="form-message" role="status"></p><div class="result-actions"><button id="edit-save" class="primary" type="submit">保存修改</button><button id="edit-cancel" type="button">取消</button></div></form></dialog>
<dialog id="edit-dialog" aria-labelledby="edit-title"><form id="edit-form"><header><h2 id="edit-title">编辑档案</h2><p id="edit-identity"></p><p class="registry-help">SN 与 FPV 编号不可修改;清空机型或登记人后保存,即清除该字段。</p></header><div class="registration-fields"><div class="registration-field"><label for="edit-model">机型</label><input id="edit-model" maxlength="60"></div><div class="registration-field"><label for="edit-owner">登记人 / 备注</label><input id="edit-owner" maxlength="40"></div></div><div class="edit-photos"><fieldset><legend>照片 1</legend><div class="photo-slot"><input id="edit-photo-1" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="2" hidden><button type="button" class="photo-pick" data-photo-choose="2" aria-label="替换照片 1"><img id="slot-preview-2" alt="照片 1预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 1</strong><span id="slot-name-2">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="2" id="slot-remove-2" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="2" id="slot-keep-2" hidden>保留原选择</button><p id="slot-status-2" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-1" type="checkbox">删除现有照片 1</label></fieldset><fieldset><legend>照片 2</legend><div class="photo-slot"><input id="edit-photo-2" type="file" accept="image/jpeg,image/png,image/webp" data-photo-slot="3" hidden><button type="button" class="photo-pick" data-photo-choose="3" aria-label="替换照片 2"><img id="slot-preview-3" alt="照片 2预览" hidden><span class="photo-plus" aria-hidden="true">+</span><strong>选择替换照片 2</strong><span id="slot-name-3">点击选择本地图片</span></button><div class="photo-slot-actions"><button type="button" data-photo-remove="3" id="slot-remove-3" hidden>取消替换 / 恢复原图</button></div><button type="button" data-photo-keep="3" id="slot-keep-3" hidden>保留原选择</button><p id="slot-status-3" class="photo-status" role="status"></p></div><label class="edit-delete"><input id="edit-delete-2" type="checkbox">删除现有照片 2</label></fieldset></div><p id="edit-message" class="form-message" role="status"></p><div class="result-actions"><button id="edit-save" class="primary" type="submit">保存修改</button><button id="edit-cancel" type="button">取消</button></div></form></dialog>
+320 -49
View File
@@ -3,7 +3,8 @@
mod photos;
use gloo_net::http::Request;
use gloo_timers::future::TimeoutFuture;
use qrcodegen::{QrCode, QrCodeEcc};
use qrcodegen::{QrCode, QrCodeEcc, QrSegment};
use rid_shared::target_lists::{ListKind, Snapshot, valid_target_id};
use serde_json::{Value, json};
use std::{cell::RefCell, collections::HashSet, rc::Rc};
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
@@ -15,6 +16,8 @@ use web_sys::{
#[derive(Default)]
struct State {
rows: Vec<Value>,
lists: Option<Snapshot>,
can_edit_lists: bool,
selected: HashSet<String>,
active: Option<Value>,
editing: Option<Value>,
@@ -54,6 +57,52 @@ fn value(id: &str) -> String {
fn field<'a>(v: &'a Value, name: &str) -> &'a str {
v[name].as_str().unwrap_or("")
}
fn label_code(record: &Value) -> Result<QrCode> {
let mut payload = String::from("无人机登记");
for (title, key) in [
("登记编号", "uasCode"),
("模块 SN", "serialNo"),
("机型", "modelName"),
("登记人/备注", "ownerName"),
("登记日期", "createdAt"),
] {
let raw = field(record, key);
let value = if key == "createdAt" {
raw.get(..10).unwrap_or(raw)
} else {
raw
};
let line = value.split_whitespace().collect::<Vec<_>>().join(" ");
if !line.is_empty() {
payload.push_str(&format!("\n{title}:{line}"));
}
}
QrCode::encode_segments(
&[
QrSegment::make_eci(26),
QrSegment::make_bytes(payload.as_bytes()),
],
QrCodeEcc::Medium,
)
.map_err(|_| "标签二维码生成失败".into())
}
fn qr_svg(qr: &QrCode) -> String {
let extent = qr.size() + 8;
let mut svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\" shape-rendering=\"crispEdges\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><path fill=\"black\" d=\""
);
for y in 0..qr.size() {
for x in 0..qr.size() {
if qr.get_module(x, y) {
svg.push_str(&format!("M{} {}h1v1h-1z", x + 4, y + 4));
}
}
}
svg.push_str("\"/></svg>");
svg
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
@@ -98,6 +147,7 @@ async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
let req = match method {
"POST" => Request::post(url),
"PATCH" => Request::patch(url),
"PUT" => Request::put(url),
"DELETE" => Request::delete(url),
_ => Request::get(url),
};
@@ -115,6 +165,128 @@ async fn api(url: &str, method: &str, body: Option<Value>) -> Result<Value> {
Err(payload["error"].as_str().unwrap_or("请求失败").to_owned())
}
}
// Use the same SN-keyed, revision-checked list store as the list manager.
async fn refresh_lists(state: &Shared) -> Result<()> {
let result = async {
let payload = api("/api/target-lists", "GET", None).await?;
let snapshot: Snapshot =
serde_json::from_value(payload).map_err(|_| "名单响应无效,请刷新后重试".to_owned())?;
let auth = api("/api/auth/status", "GET", None).await?;
Ok::<_, String>((
snapshot,
matches!(field(&auth, "role"), "admin" | "operator"),
))
}
.await;
let mut s = state.borrow_mut();
match result {
Ok((snapshot, allowed)) => {
s.lists = Some(snapshot);
s.can_edit_lists = allowed;
Ok(())
}
Err(error) => {
s.lists = None;
s.can_edit_lists = false;
Err(error)
}
}
}
fn list_actions(s: &State, sn: &str) -> String {
if !s.can_edit_lists || !valid_target_id(sn) {
return String::new();
}
let Some(snapshot) = &s.lists else {
return String::new();
};
let current = snapshot
.entries
.iter()
.find(|entry| entry.target_id == sn)
.map(|entry| entry.list_kind);
let revision = snapshot.revision;
[
(ListKind::White, "white", "白名单"),
(ListKind::Black, "black", "黑名单"),
]
.into_iter()
.map(|(kind, wire, label)| {
let verb = if current == Some(kind) {
"移除"
} else {
"加入"
};
let operation = if current == Some(kind) {
"remove"
} else {
"add"
};
format!(
r#"<button type="button" data-action="list-{operation}-{wire}" data-list-revision="{revision}">{verb}{label}</button>"#
)
})
.collect()
}
async fn change_list(
state: &Shared,
row: &Value,
action: &str,
expected_revision: u64,
) -> Result<()> {
let sn = field(row, "serialNo");
let (revision, note) = {
let s = state.borrow();
if !s.can_edit_lists {
return Err("当前账号不能修改黑白名单".into());
}
let snapshot = s.lists.as_ref().ok_or("请刷新后重试")?;
if snapshot.revision != expected_revision {
return Err("名单已更新,请重新打开菜单后重试".into());
}
let entry = snapshot.entries.iter().find(|entry| entry.target_id == sn);
(
snapshot.revision,
entry.map(|entry| entry.note.clone()).unwrap_or_default(),
)
};
let path = format!("/api/target-lists/{}", js_sys::encode_uri_component(sn));
let removing = action.starts_with("list-remove-");
let kind = if action.ends_with("-white") {
"white"
} else {
"black"
};
let payload = if removing {
api(&format!("{path}?revision={revision}"), "DELETE", None).await?
} else {
// PUT atomically replaces the previous kind; never delete then insert.
api(
&path,
"PUT",
Some(json!({"list_kind":kind,"note":note,"expected_revision":revision})),
)
.await?
};
state.borrow_mut().lists = Some(
serde_json::from_value(payload)
.map_err(|_| "名单已提交,响应无效,请刷新核对".to_owned())?,
);
message(
"history-message",
&format!(
"{}已{}{}",
sn,
if removing { "移除" } else { "加入" },
if kind == "white" {
"白名单"
} else {
"黑名单"
}
),
false,
);
Ok(())
}
fn archive_status(payload: &Value) {
if payload["archiveStatus"] == "pending" {
hidden("archive-warning", false);
@@ -214,7 +386,8 @@ fn render_rows(state: &Shared) {
let current = s.active.as_ref().is_some_and(|r| r["id"] == row["id"]);
let date = field(row, "createdAt");
let short = date.get(..10).unwrap_or(date).replace('-', ".");
html.push_str(&format!(r#"<article class="archive-card{}{}" data-id="{id}"><label class="archive-select"><input id="select-{id}" type="checkbox" data-action="select" aria-label="选择档案 {sn}" {}>选择导出</label><div class="archive-card-head"><h3>{sn}</h3><button id="more-{id}" type="button" class="archive-more" data-action="more" aria-label="{sn} 更多操作" aria-expanded="false" aria-controls="actions-{id}">···</button></div><strong>{}</strong><p>{} · {}</p><div class="archive-card-foot"><time datetime="{}" title="{}">{}</time><button id="view-{id}" type="button" data-action="view">查看档案 →</button></div><div id="actions-{id}" class="registry-popup" hidden><button type="button" data-action="edit">编辑资料 / 照片</button><a href="{}" target="_blank" rel="noopener">打开档案卡</a><a href="{}">下载离线档案卡</a><button type="button" data-action="qr">查看二维码</button><button type="button" class="delete-record" data-action="delete">删除档案</button></div></article>"#, if selected {" selected"} else {""}, if current {" is-current"} else {""}, if selected {"checked"} else {""}, escape(field(row,"uasCode")), escape(field(row,"modelName")), escape(field(row,"ownerName")), escape(date), escape(date), escape(&short), escape(field(row,"archiveUrl")), escape(field(row,"downloadArchiveUrl"))));
let list_actions = list_actions(&s, field(row, "serialNo"));
html.push_str(&format!(r#"<article class="archive-card{}{}" data-id="{id}"><label class="archive-select"><input id="select-{id}" type="checkbox" data-action="select" aria-label="选择档案 {sn}" {}>选择导出</label><div class="archive-card-head"><h3>{sn}</h3><button id="more-{id}" type="button" class="archive-more" data-action="more" aria-label="{sn} 更多操作" aria-expanded="false" aria-controls="actions-{id}">···</button></div><strong>{}</strong><p>{} · {}</p><div class="archive-card-foot"><time datetime="{}" title="{}">{}</time><button id="view-{id}" type="button" data-action="view">查看档案 →</button></div><div id="actions-{id}" class="registry-popup" hidden><a href="/workbench/platform.html?module=flight-plans&amp;record={id}" target="_top">申请飞行报备</a>{list_actions}<button type="button" data-action="edit">编辑资料 / 照片</button><a href="{}" target="_blank" rel="noopener">打开档案卡</a><a href="{}">下载离线档案卡</a><button type="button" data-action="qr">查看二维码</button><button type="button" class="delete-record" data-action="delete">删除档案</button></div></article>"#, if selected {" selected"} else {""}, if current {" is-current"} else {""}, if selected {"checked"} else {""}, escape(field(row,"uasCode")), escape(field(row,"modelName")), escape(field(row,"ownerName")), escape(date), escape(date), escape(&short), escape(field(row,"archiveUrl")), escape(field(row,"downloadArchiveUrl"))));
}
el("history-cards").set_inner_html(&html);
hidden("history-empty", !s.rows.is_empty());
@@ -264,12 +437,12 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
s.selected.retain(|id| ids.contains(id));
}
text(
"page-status",
&format!(
"第 {page} / {} 页 · 共 {} 条",
pages.max(1),
payload["total"]
),
"archive-page-number",
&format!("第 {page} / {} 页", pages.max(1)),
);
text(
"page-count",
&format!("共 {} 条 · 每页 20 条", payload["total"]),
);
text(
"search-count",
@@ -287,6 +460,13 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
"没有找到匹配的档案。"
},
);
let lists_result = refresh_lists(&state).await;
if state.borrow().generation != generation {
return Ok(());
}
if let Err(error) = lists_result {
message("history-message", &error, true);
}
render_rows(&state);
page_buttons(&state);
return Ok(());
@@ -390,26 +570,11 @@ fn draw(state: &Shared, record: Value) {
.set_attribute("src", &format!("{url}?v={}", js_sys::Date::now()));
}
hidden("saved-photos", !has_photos);
if let Ok(qr) = QrCode::encode_text(field(&record, "qrUrl"), QrCodeEcc::Medium) {
let size = qr.size();
let extent = size + 8;
let mut svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {extent} {extent}\"><rect width=\"100%\" height=\"100%\" fill=\"white\"/><g fill=\"black\">"
);
for y in 0..size {
for x in 0..size {
if qr.get_module(x, y) {
svg.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"1\" height=\"1\"/>",
x + 4,
y + 4
));
}
}
}
svg.push_str("</g></svg>");
el("qr-stage").set_inner_html(&svg);
match label_code(&record) {
Ok(qr) => el("qr-stage").set_inner_html(&qr_svg(&qr)),
Err(error) => text("qr-stage", &error),
}
text("label-feedback", "");
state.borrow_mut().active = Some(record);
render_rows(state);
el("registration-result").scroll_into_view();
@@ -662,46 +827,85 @@ async fn export(state: Shared, kind: &str) -> Result<()> {
});
Ok(())
}
fn download_qr(state: &Shared) -> Result<()> {
fn download_qr(state: &Shared, local: bool) -> Result<()> {
let row = state.borrow().active.clone().ok_or("请先登记")?;
let qr = QrCode::encode_text(field(&row, "qrUrl"), QrCodeEcc::Medium)
.map_err(|_| "二维码生成失败")?;
let qr = if local {
QrCode::encode_text(field(&row, "qrUrl"), QrCodeEcc::Medium)
.map_err(|_| "本机二维码生成失败")?
} else {
label_code(&row)?
};
let canvas: HtmlCanvasElement = document()
.create_element("canvas")
.map_err(err)?
.unchecked_into();
canvas.set_width(640);
canvas.set_height(640);
let extent = qr.size() + 8;
let cell = 640 / extent;
let side = (extent * cell) as u32;
canvas.set_width(side);
canvas.set_height(side);
let context: web_sys::CanvasRenderingContext2d = canvas
.get_context("2d")
.map_err(err)?
.ok_or("Canvas 不可用")?
.unchecked_into();
context.set_fill_style_str("white");
context.fill_rect(0.0, 0.0, 640.0, 640.0);
context.fill_rect(0.0, 0.0, side.into(), side.into());
context.set_fill_style_str("black");
let cell = 640.0 / f64::from(qr.size() + 8);
for y in 0..qr.size() {
for x in 0..qr.size() {
if qr.get_module(x, y) {
let left = (f64::from(x + 4) * cell).floor();
let top = (f64::from(y + 4) * cell).floor();
let right = (f64::from(x + 5) * cell).ceil();
let bottom = (f64::from(y + 5) * cell).ceil();
context.fill_rect(left, top, right - left, bottom - top);
context.fill_rect(
((x + 4) * cell).into(),
((y + 4) * cell).into(),
cell.into(),
cell.into(),
);
}
}
}
download(
&canvas.to_data_url().map_err(err)?,
&format!(
"{}-{}-LOCAL.png",
"{}-{}-{}.png",
field(&row, "serialNo"),
field(&row, "uasCode")
field(&row, "uasCode"),
if local { "LOCAL" } else { "LABEL" }
),
);
Ok(())
}
fn print_label(state: &Shared) -> Result<()> {
let row = state.borrow().active.clone().ok_or("请先登记")?;
let qr = label_code(&row)?;
let page = window()
.open_with_url_and_target("about:blank", "_blank")
.map_err(err)?
.ok_or("请允许打开标签打印预览")?;
let doc = page.document().ok_or("无法生成打印预览")?;
doc.set_title(&format!("无人机登记标签 · {}", field(&row, "uasCode")));
doc.body()
.ok_or("无法生成打印预览")?
.set_inner_html(include_str!("registry_label.html"));
for (id, key) in [("label-number", "uasCode"), ("label-serial", "serialNo")] {
doc.get_element_by_id(id)
.ok_or("标签字段不可用")?
.set_text_content(Some(field(&row, key)));
}
doc.get_element_by_id("label-code")
.ok_or("标签二维码不可用")?
.set_inner_html(&qr_svg(&qr));
let print = Closure::<dyn FnMut(Event)>::new(move |_| {
let _ = page.print();
});
doc.get_element_by_id("label-print")
.ok_or("打印按钮不可用")?
.add_event_listener_with_callback("click", print.as_ref().unchecked_ref())
.map_err(err)?;
print.forget();
Ok(())
}
fn listen(name: &str, handler: impl Fn(Event) + 'static) {
let closure = Closure::<dyn Fn(Event)>::new(handler);
document()
@@ -725,6 +929,14 @@ pub fn init() {
..State::default()
}));
for event in ["rid-workspace-view", "focus"] {
// Entering the iframe also fires focus before the user's pagination click.
if event == "focus"
&& document()
.body()
.is_some_and(|body| body.class_name() == "rid-embedded")
{
continue;
}
let state = state.clone();
let refresh = Closure::<dyn FnMut(Event)>::new(move |_| {
let screen = document()
@@ -1013,9 +1225,19 @@ pub fn init() {
dialog().close();
return;
}
if id == "download-qr" {
if let Err(e) = download_qr(&state) {
message("form-message", &e, true);
if matches!(
id.as_str(),
"download-qr" | "download-local-qr" | "print-label"
) {
let result = if id == "print-label" {
print_label(&state)
} else {
download_qr(&state, id == "download-local-qr")
};
if let Err(e) = result {
message("label-feedback", &e, true);
} else {
text("label-feedback", "");
}
return;
}
@@ -1036,14 +1258,63 @@ pub fn init() {
.cloned();
let Some(row) = row else { return };
if action == "more" {
toggle_menu(
&state,
&format!("actions-{record_id}"),
&format!("more-{record_id}"),
);
if state
.borrow()
.menu
.as_ref()
.is_some_and(|(popup, _)| popup == &format!("actions-{record_id}"))
{
close_menu(&state, true);
return;
}
state.borrow_mut().busy = true;
spawn_local(async move {
let result = refresh_lists(&state).await;
state.borrow_mut().busy = false;
render_rows(&state);
if let Err(error) = result {
message("history-message", &error, true);
}
if document()
.get_element_by_id(&format!("actions-{record_id}"))
.is_some()
{
toggle_menu(
&state,
&format!("actions-{record_id}"),
&format!("more-{record_id}"),
);
}
});
return;
}
close_menu(&state, true);
if matches!(
action.as_str(),
"list-add-white" | "list-add-black" | "list-remove-white" | "list-remove-black"
) {
let Some(revision) = t
.get_attribute("data-list-revision")
.and_then(|v| v.parse::<u64>().ok())
else {
return;
};
state.borrow_mut().busy = true;
saving_controls(&state, true);
spawn_local(async move {
let result = change_list(&state, &row, &action, revision).await;
if let Err(error) = result {
let _ = refresh_lists(&state).await;
message("history-message", &error, true);
}
state.borrow_mut().busy = false;
saving_controls(&state, false);
render_rows(&state);
page_buttons(&state);
focus(&format!("more-{record_id}"));
});
return;
}
if action == "edit" {
state.borrow_mut().edit_return = format!("more-{record_id}");
edit(&state, row);
+26
View File
@@ -0,0 +1,26 @@
<style>
@page { size: 60mm 40mm; margin: 0; }
* { box-sizing: border-box; }
body { margin: 0; color: #111; background: #edf0f3; font: 14px system-ui, sans-serif; }
.controls { padding: 16px; text-align: center; }
.controls button { font: inherit; padding: 6px 20px; }
.asset-label {
width: 60mm; height: 40mm; padding: 1mm; background: #fff; display: grid;
grid-template-columns: 29mm minmax(0, 1fr); align-items: center; gap: .6mm;
margin: 0 auto; font-variant-numeric: tabular-nums;
}
.asset-label svg { width: 100%; height: auto; display: block; }
.asset-label h1 { margin: 0 0 1mm; font-size: 9pt; }
.asset-label p { margin: .8mm 0 0; font-size: 6.5pt; overflow-wrap: anywhere; }
.asset-label strong { font-size: 8pt; overflow-wrap: anywhere; }
@media print {
body { background: #fff; }
.controls { display: none; }
.asset-label { margin: 0; }
}
</style>
<header class="controls"><button id="label-print" type="button">打印标签</button><p>纸张 60 × 40 mm,缩放 100%</p></header>
<main class="asset-label" aria-label="无人机登记标签">
<div id="label-code" aria-label="设备信息二维码"></div>
<div><h1>无人机登记</h1><strong id="label-number"></strong><p>模块 SN</p><p id="label-serial"></p></div>
</main>
+71 -7
View File
@@ -5,6 +5,7 @@ use rid_shared::target_lists::{
Entry, ListKind, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
};
use serde_json::Value;
use std::collections::HashMap;
use wasm_bindgen_futures::spawn_local;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -415,21 +416,84 @@ pub(super) fn Manager(lists: Lists) -> impl IntoView {
.get()
.min(rows.get().len().div_ceil(50).max(1) - 1)
});
let page_ids = Memo::new(move |_| {
rows.get()
.into_iter()
.skip(page.get() * 50)
.take(50)
.map(|entry| entry.target_id)
.collect::<Vec<_>>()
});
let registrations = RwSignal::new(HashMap::<String, bool>::new());
Effect::new(move |_| {
if !lists.open.get() {
return;
}
let ids = page_ids.get();
if ids.is_empty() {
return;
}
spawn_local(async move {
let url = format!("/api/target-registration-status?ids={}", ids.join(","));
let Ok(response) = Request::get(&url).send().await else {
return;
};
if !response.ok() {
return;
}
let Ok(value) = response.json::<Value>().await else {
return;
};
if !lists.open.get_untracked() || page_ids.get_untracked() != ids {
return;
}
let Some(entries) = value["entries"].as_array() else {
return;
};
registrations.set(
entries
.iter()
.filter_map(|row| {
Some((
row["targetId"].as_str()?.to_owned(),
row["registered"].as_bool()?,
))
})
.collect(),
);
});
});
view! {
<section id="rt-list-manager" tabindex="-1" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get()>
<header class="rt-list-manager-head"><div><h2>"黑白名单管理"</h2><p>"按目标标识精确匹配,区分大小写。名单与设备登记档案独立。"</p></div><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.editor_open.set(true);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="返回工作区" on:click=move |_|lists.close()>"返回工作区"</button></header>
<header class="rt-list-manager-head"><div><h2>"黑白名单管理"</h2><p>"用实时目标列表里的 RID 标识添加条目,区分大小写。设备登记仅建立档案,白名单在这里手动添加。"</p></div><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.editor_open.set(true);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="返回工作区" on:click=move |_|lists.close()>"返回工作区"</button></header>
<div class="rt-list-manager-body">
<aside class="rt-list-category-panel" aria-label="名单分类"><h3>"名单分类"</h3><div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div><div class="rt-list-policy"><h3>"标记与告警规则"</h3><p>"白名单标记为可信,围栏免告警。黑名单突出显示并记录告警。所有目标继续接收和显示。"</p><p>"移除后恢复为未分类,保留遥测与登记档案。"</p></div></aside>
<aside class="rt-list-category-panel" aria-label="名单分类"><h3>"名单分类"</h3><div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div><div class="rt-list-policy"><h3>"告警规则"</h3><p><strong>"白名单"</strong>" · 进入围栏时免围栏告警。设备未登记时,仍会产生未登记告警。"</p><p><strong>"黑名单"</strong>" · 发现目标时产生黑名单告警。"</p><p><strong>"设备登记"</strong>" · 用于识别已登记设备,地图上显示绿色。"</p></div></aside>
<section class="rt-list-table-panel" aria-label="名单目录">
<div class="rt-list-table-toolbar">
<label class="rt-list-search"><span class="rt-list-search-label">"搜索名单"</span><input placeholder="搜索目标标识或备注" prop:value=move||lists.query.get() on:input=move|event|{lists.query.set(event_target_value(&event));lists.manager_page.set(0);}/></label></div>
<p class="rt-list-help" hidden=move||lists.ready.get()>"正在读取本机名单…"</p>
<p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
<div class="rt-list-rows"><table aria-label="黑白名单条目"><thead><tr><th scope="col">"目标标识"</th><th scope="col">"分类"</th><th scope="col">"备注"</th><th scope="col">"操作"</th></tr></thead><tbody><Show when=move||lists.editor_open.get()&&(!lists.editing.get()||!rows.get().iter().skip(page.get()*50).take(50).any(|e|e.target_id==lists.draft_id.get()))><tr class="rt-inline-editor-row"><td colspan="4"><ListEditor lists=lists/></td></tr></Show><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();let note_id=entry.target_id.clone();let selected_id=entry.target_id.clone();let editor_id=entry.target_id.clone();
view!{<tr class="rt-list-row" class:selected=move||lists.editing.get()&&lists.draft_id.get()==selected_id data-target-id=entry.target_id.clone()><td class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong></td><td><Badge lists=lists target=badge_id/></td><td class="rt-list-row-note"><p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==note_id).map(|entry|entry.note.clone()).unwrap_or_default())}</p></td><td class="rt-list-row-actions"><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></td></tr><Show when=move||lists.editor_open.get()&&lists.editing.get()&&lists.draft_id.get()==editor_id><tr class="rt-inline-editor-row"><td colspan="4"><ListEditor lists=lists/></td></tr></Show>}
<div class="rt-list-rows"><table aria-label="黑白名单条目"><thead><tr><th scope="col">"RID 标识"</th><th scope="col">"名单类型"</th><th scope="col">"设备登记"</th><th scope="col">"名单备注"</th><th scope="col">"操作"</th></tr></thead><tbody><Show when=move||lists.editor_open.get()&&(!lists.editing.get()||!page_ids.get().contains(&lists.draft_id.get()))><tr class="rt-inline-editor-row"><td colspan="5"><ListEditor lists=lists/></td></tr></Show><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();let note_id=entry.target_id.clone();let selected_id=entry.target_id.clone();let editor_id=entry.target_id.clone();let registration_id=entry.target_id.clone();
view!{
<tr class="rt-list-row" class:selected=move||lists.editing.get()&&lists.draft_id.get()==selected_id data-target-id=entry.target_id.clone()>
<td class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong></td>
<td><Badge lists=lists target=badge_id/></td>
<td>{move||registrations.with(|items|match items.get(&registration_id){Some(true)=>"已登记",Some(false)=>"未登记",None=>"待核验"})}</td>
<td class="rt-list-row-note"><p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==note_id).map(|entry|if entry.note.is_empty(){"—".into()}else{entry.note.clone()}).unwrap_or_default())}</p></td>
<td class="rt-list-row-actions"><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></td>
</tr>
<Show when=move||lists.editor_open.get()&&lists.editing.get()&&lists.draft_id.get()==editor_id><tr class="rt-inline-editor-row"><td colspan="5"><ListEditor lists=lists/></td></tr></Show>
}
}/></tbody></table><p class="rt-list-help" hidden=move||!lists.ready.get()||!rows.get().is_empty()>"暂无匹配条目,可点击新增条目。"</p></div>
<nav class="rt-list-pagination" aria-label="名单分页"><span>{move||format!("共 {} 条",rows.get().len())}</span><button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button><span>{move||format!("{} / {}",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span><button type="button" disabled={move||(page.get()+1)*50>=rows.get().len()} on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button></nav>
<nav class="rt-list-pagination rid-pager" aria-label="名单分页">
<span class="rid-page-summary">{move||format!("共 {} 条 · 每页 50 条",rows.get().len())}</span>
<div class="rid-pager-actions">
<button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button>
<span class="rid-page-number" aria-live="polite">{move||format!("第 {} / {} 页",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span>
<button type="button" disabled={move||(page.get()+1)*50>=rows.get().len()} on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button>
</div>
</nav>
</section>
</div>
@@ -443,7 +507,7 @@ fn ListEditor(lists: Lists) -> impl IntoView {
view! {
<form id="rt-list-entry-form" on:submit=move |event|{event.prevent_default();lists.save(lists.draft_id.get_untracked().trim().to_owned(),lists.draft_kind.get_untracked(),lists.draft_note.get_untracked());}>
<div class="rt-inline-editor-heading"><h3>{move||if lists.editing.get(){"编辑名单条目"}else{"新增名单条目"}}</h3><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.editor_open.set(false)>"收起编辑"</button></div>
<label for="rt-list-entry-id">"目标标识"<input id="rt-list-entry-id" required maxlength="64" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/></label>
<label for="rt-list-entry-id">"RID 标识"<input id="rt-list-entry-id" required maxlength="64" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() aria-describedby="rid-list-id-hint" prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/><small id="rid-list-id-hint">"在实时目标列表点击「复制 RID」获取。"</small></label>
<label for="rt-list-entry-kind">"名单类型"<select id="rt-list-entry-kind" disabled=move||lists.busy.get() prop:value=move||match lists.draft_kind.get(){ListKind::White=>"white",ListKind::Black=>"black"} on:change=move|event|lists.draft_kind.set(if event_target_value(&event)=="white"{ListKind::White}else{ListKind::Black})><option value="white">"白名单"</option><option value="black">"黑名单"</option></select></label>
<label for="rt-list-entry-note" class="rt-inline-note">"备注(最多200字)"<textarea id="rt-list-entry-note" maxlength="200" disabled=move||lists.busy.get() prop:value=move||lists.draft_note.get() on:input=move|event|lists.draft_note.set(event_target_value(&event))></textarea></label>
<div class="rt-inline-editor-actions"><button class="primary" type="submit" disabled=move||!lists.ready.get()||lists.busy.get()>{move||if lists.busy.get(){"正在保存…"}else{"保存名单条目"}}</button></div>
File diff suppressed because one or more lines are too long
+40
View File
@@ -317,7 +317,45 @@ fn queue_save(state: Shared) {
}
});
}
fn embedded_view(view: &str) -> &str {
match view {
"register" | "archives" | "maps" | "target-lists" | "receivers" | "history" => view,
_ => "home",
}
}
pub(super) fn init_embedded() {
if let Some(body) = document().body() {
body.set_class_name("rid-embedded");
}
let Some(window) = web_sys::window() else {
return;
};
let navigate =
Closure::<dyn FnMut(web_sys::CustomEvent)>::new(|event: web_sys::CustomEvent| {
if let Some(view) = event.detail().as_string() {
show(embedded_view(&view), false);
}
});
let _ = window.add_event_listener_with_callback(
"rid-embedded-navigate",
navigate.as_ref().unchecked_ref(),
);
navigate.forget();
show("home", false);
if let Ok(event) = Event::new("rid-embedded-ready") {
let _ = window.dispatch_event(&event);
}
}
pub(super) fn navigate(view: &str) {
if document()
.body()
.is_some_and(|body| body.class_name() == "rid-embedded")
{
show(embedded_view(view), false);
return;
}
let realtime = web_sys::window()
.is_some_and(|w| w.location().pathname().unwrap_or_default() == "/realtime");
show(view, realtime);
@@ -645,6 +683,8 @@ pub fn init(realtime: bool) {
"receivers"
} else if search.contains("app=target-lists") {
"target-lists"
} else if search.contains("app=maps") {
"maps"
} else if realtime {
"realtime"
} else if search.contains("app=geofences") {
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"/>

After

Width:  |  Height:  |  Size: 89 B

+89
View File
@@ -0,0 +1,89 @@
(() => {
'use strict';
const MAX_LINK_GAP_MS = 30000;
const BASE_JUMP_M = 260;
const MAX_SPEED_MPS = 120;
const TO_RAD = Math.PI / 180;
function registrationColors(registered) {
if (registered === true) return {fill:'#26ad72', glow:'rgba(38,210,133,.82)'};
if (registered === false) return {fill:'#ec4361', glow:'rgba(255,64,96,.86)'};
return {fill:'#637c91', glow:'rgba(128,158,180,.45)'};
}
function createMarker({heading = 0, fill = 'rgba(255,211,90,.96)', glow = 'rgba(255,211,90,.86)', opacity = 1} = {}) {
const badge = document.createElement('div');
badge.className = 'rid-drone-marker';
badge.setAttribute('aria-hidden', 'true');
badge.style.setProperty('--rid-drone-fill', fill);
badge.style.setProperty('--rid-drone-glow', glow);
badge.style.opacity = opacity;
const plane = document.createElement('span');
plane.className = 'rid-drone-plane';
plane.style.transform = 'rotate(' + heading + 'deg)';
badge.append(plane);
return badge;
}
function validPosition(point) {
return Number.isFinite(point?.longitude) && Math.abs(point.longitude) <= 180
&& Number.isFinite(point?.latitude) && Math.abs(point.latitude) <= 90
&& Number.isFinite(point?.timeMs);
}
function jumping(from, to) {
const dy = Math.sin((to.latitude - from.latitude) * TO_RAD / 2);
const dx = Math.sin((to.longitude - from.longitude) * TO_RAD / 2);
const latitude = Math.cos(from.latitude * TO_RAD) * Math.cos(to.latitude * TO_RAD);
const metres = 12742000 * Math.asin(Math.sqrt(Math.min(1, dy * dy + latitude * dx * dx)));
const seconds = Math.max(0.5, (to.timeMs - from.timeMs) / 1000);
return metres > BASE_JUMP_M + MAX_SPEED_MPS * seconds;
}
function shortInterval(from, to) {
const elapsed = to.timeMs - from.timeMs;
return elapsed >= 0 && elapsed < MAX_LINK_GAP_MS;
}
function trackHeading(fromLat, fromLng, toLat, toLng) {
const east = (((toLng - fromLng + 540) % 360) - 180) * Math.cos((fromLat + toLat) * TO_RAD / 2);
const north = toLat - fromLat;
return east || north ? (Math.atan2(east, north) / TO_RAD + 360) % 360 : null;
}
function prepareTrack(samples) {
const points = [];
let pendingBreak = false;
let skipped = 0;
let newSegments = 0;
for (let index = 0; index < samples.length; index += 1) {
const point = samples[index];
if (!validPosition(point)) {
pendingBreak = true;
skipped += 1;
continue;
}
const previous = points.at(-1);
const next = samples[index + 1];
const connectedBefore = previous && !point.segmentStart && !pendingBreak && shortInterval(previous, point);
// Discard an isolated out-and-back spike only when the adjacent run is still continuous.
if (connectedBefore && validPosition(next) && !next.segmentStart && shortInterval(previous, next)
&& shortInterval(point, next) && jumping(previous, point) && jumping(point, next) && !jumping(previous, next)) {
skipped += 1;
continue;
}
if (previous && !point.segmentStart && (!connectedBefore || jumping(previous, point))) {
points.push({...point, segmentStart: true});
newSegments += 1;
} else {
points.push(point);
}
pendingBreak = false;
}
return {points, skipped, newSegments};
}
window.ridDroneMap = Object.freeze({createMarker, prepareTrack, trackHeading, registrationColors, MAX_LINK_GAP_MS});
})();
+61
View File
@@ -0,0 +1,61 @@
.rid-drone-marker {
box-sizing: border-box;
display: grid;
place-items: center;
width: 32px;
height: 32px;
border: 2px solid rgb(255 255 255 / 92%);
border-radius: 50%;
background: var(--rid-drone-fill);
box-shadow: 0 0 18px var(--rid-drone-glow);
}
.rid-drone-plane {
width: 21px;
height: 21px;
background: #fff;
clip-path: polygon(50% 2%, 57% 9%, 58% 34%, 95% 59%, 95% 68%, 58% 57%,
57% 79%, 72% 91%, 72% 98%, 50% 90%, 28% 98%, 28% 91%,
43% 79%, 42% 57%, 5% 68%, 5% 59%, 42% 34%, 43% 9%);
}
.rid-pilot-marker {
box-sizing: border-box;
display: grid;
place-items: center;
width: 32px;
height: 32px;
border: 2px solid #fff1c5;
border-radius: 9px;
background: #ffd35a;
box-shadow: 0 2px 7px #081726bb;
font-size: 17px;
}
.rid-pair-label {
position: absolute;
bottom: calc(100% + 5px);
left: 50%;
transform: translateX(-50%);
box-sizing: border-box;
width: max-content;
max-width: 240px;
padding: 3px 7px;
border: 1px solid #80b5d8;
border-radius: 6px;
background: #0b2034f2;
color: #eff8ff;
font: 600 12px/1.25 "Segoe UI", "Microsoft YaHei", sans-serif;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
box-shadow: 0 2px 5px #06101b9c;
}
.rid-pilot-marker .rid-pair-label {
top: calc(100% + 5px + var(--rid-pilot-label-offset));
bottom: auto;
border-color: #dcaf4b;
}
.mapWrap[data-hide-models] .rid-pair-label { display: none; }
+62
View File
@@ -0,0 +1,62 @@
@import url('/workbench/pagination.css');
body.rid-embedded {
--work-text: #e6f5ff;
--work-muted: #b2cada;
--work-line: #36536a;
--work-panel: #102438;
--work-input: #091a2c;
--glass-surface: #102438;
--glass-solid: #102438;
--mc-accent: #69ccff;
--mc-accent-blue: #1e88ff;
background: #0b1d2e;
}
body.rid-embedded > .workspace-pane {
inset: 0;
background: transparent;
backdrop-filter: none;
}
body.rid-embedded .registry-workspace {
height: 100dvh;
}
body.rid-embedded .rt-list-manager-head button[aria-label="返回工作区"] {
display: none;
}
body.rid-embedded :is(.history-panel, .track-playback-controls, .rx-surface, .registry-group) {
border-color: var(--work-line);
}
body.rid-embedded :is(button, input, select, textarea, summary):focus-visible {
outline: 2px solid #7ddcff;
outline-offset: 2px;
}
/* Archive lists fill the workspace; cards retain their responsive grid width. */
body.rid-embedded[data-screen=archives]:not([data-archive-detail=open]) .registry-workspace {
width:100%; max-width:none; margin-inline:0; box-sizing:border-box;
}
body.rid-embedded[data-screen=archives]:not([data-archive-detail=open]) .registry-workspace .history-panel {
height:100%; min-height:0; border-radius:8px; box-shadow:none;
}
body.rid-embedded[data-screen=archives] .archiveTools { flex-flow:row wrap; align-items:center; gap:10px 12px; margin-bottom:18px; }
body.rid-embedded[data-screen=archives] .archiveTools .history-search { flex:1 1 240px; max-width:520px; margin:0; }
body.rid-embedded[data-screen=archives] .archiveTools #new-registration { width:auto; min-height:40px; }
body.rid-embedded[data-screen=archives] .archiveTools .history-toolbar { margin:0 0 0 auto; gap:8px; }
body.rid-embedded[data-screen=archives] .archiveTools :is(#selection-toggle,#export-toggle) { min-height:40px; }
body.rid-embedded[data-screen=archives] .archive-card { border-radius:8px; padding:16px; }
body.rid-embedded[data-screen=archives] .archive-card .archive-more { flex:none; min-width:28px; }
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools { flex-direction:column; align-items:stretch; }
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools .history-search { flex:none; }
body.rid-embedded[data-screen=archives][data-archive-detail=open] .archiveTools .history-toolbar { margin:0; }
@media (max-width: 760px) {
body.rid-embedded .registry-workspace {
height: auto;
min-height: 100dvh;
}
body.rid-embedded .rx-cards {
grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr));
}
body.rid-embedded .rt-list-manager-head {
flex-wrap: wrap;
align-items: flex-start;
}
}
+48
View File
@@ -0,0 +1,48 @@
const modulePath = '/workbench/module.html';
if (location.pathname === modulePath) {
if (window.parent === window) {
location.replace('/workbench/platform.html');
} else {
const available = new Set(['home', 'register', 'archives', 'target-lists', 'maps', 'history', 'receivers']);
let navigating = false;
function send(type, view) {
window.parent.postMessage({ type, view }, location.origin);
}
function ready() {
send('rid-embedded-ready');
}
window.addEventListener('rid-embedded-ready', ready);
if (document.body?.className === 'rid-embedded') ready();
window.addEventListener('message', event => {
if (event.origin !== location.origin || event.source !== window.parent ||
event.data?.type !== 'rid-embedded-navigate' || !available.has(event.data.view)) return;
navigating = true;
try {
const { view, record, mapOptions } = event.data;
if (view === 'history') window.ridHistory?.setMapOptions(mapOptions);
if (document.body.dataset.screen !== view) {
window.dispatchEvent(new CustomEvent('rid-embedded-navigate', { detail: view }));
}
if (view === 'history') {
window.dispatchEvent(new CustomEvent('rid-history-record', {
detail: record ? JSON.stringify(record) : null
}));
}
} finally {
navigating = false;
}
});
window.addEventListener('rid-history-return-records', () => send('rid-embedded-return-records'));
window.addEventListener('rid-workspace-view', () => {
const view = document.body.dataset.screen;
if (!navigating && available.has(view)) send('rid-embedded-view', view);
});
}
}
+60
View File
@@ -0,0 +1,60 @@
(function () {
'use strict';
// The reference markup uses data attributes for both static and generated controls.
// Only these named actions are callable. Arguments are data, never JavaScript.
const actions = Object.freeze(Object.fromEntries(`
cancelDrawZone clearAllTrackLayers clearCurrentAlerts copyDroneRid deleteZone deleteCenterAlarm finishDrawZone
fitAll focusAlertOnMap focusStationByKey focusZoneByKey logout
mapSetViewWgs84 markAlarmHandled openModule renameZone setBaseMap
shareDroneLocation shareStationLocation startDrawZone testAlarm
toggleMapLabels toggleSidePanel toggleZone trackDrone unlockDroneTracking
`.trim().split(/\s+/).map(name => [name, window[name]])));
function argument(element, value) {
if (value === '@value') return element.value;
if (value === '@checked') return element.checked;
if (value === '@number') return Number(element.value);
if (value === '@true') return true;
if (value.startsWith('@n:')) return Number(value.slice(3));
return value;
}
function run(event, element, kind) {
const name = element.getAttribute(`data-rid-${kind}`);
const args = [];
for (let index = 0; index < 3; index++) {
const value = element.getAttribute(`data-rid-arg${index}`);
if (value !== null) args.push(argument(element, value));
}
if (name === 'stop') {
event.stopPropagation();
return;
}
if (Object.hasOwn(actions, name)) return actions[name](...args);
}
for (const kind of ['click', 'change', 'input']) {
document.addEventListener(kind, event => {
const control = event.target.closest?.(`[data-rid-${kind}]`);
if (control) Promise.resolve().then(() => run(event, control, kind)).catch(error => {
const feedback = document.getElementById('rid-workbench-status');
feedback.textContent = error.message || '操作失败,请重试';
feedback.hidden = false;
clearTimeout(feedback.hideTimer);
feedback.hideTimer = setTimeout(() => { feedback.hidden = true; }, 4500);
});
});
}
for (const control of document.querySelectorAll('.tool[data-rid-click]')) {
control.setAttribute('role', 'button');
control.tabIndex = 0;
}
document.addEventListener('keydown', event => {
const control = event.target.closest?.('div[role="button"][data-rid-click]');
if (control && (event.key === ' ' || event.key === 'Enter')) {
event.preventDefault();
control.click();
}
});
})();
+16
View File
@@ -0,0 +1,16 @@
(() => {
'use strict';
const types = Object.freeze({
whitelist: {label:'白名单',tone:'ok',fill:'#27b888',rank:4},
authorized: {label:'已报备',tone:'ok',fill:'#27b888',rank:5},
unregistered: {label:'未登记告警',tone:'danger',fill:'#cc3c48',rank:2},
unfiled: {label:'未报备告警',tone:'warning',fill:'#ca921e',rank:3},
geofence_enter: {label:'防控区告警',tone:'danger',fill:'#cc3c48',rank:0},
blacklist: {label:'黑名单告警',tone:'danger',fill:'#cc3c48',rank:1},
unknown: {label:'待核验',tone:'muted',fill:'#929eaa',rank:6}
});
const meta = code => types[code] || types.unknown;
const tag = code => {const value=meta(code);return `<span class="flightTag ${value.tone}">${value.label}</span>`;};
const tags = values => (values?.length ? [...new Set(values)] : ['unknown']).sort((a,b)=>meta(a).rank-meta(b).rank).map(tag).join(' ');
window.ridFlightStatus=Object.freeze({types,meta,tag,tags,colors:code=>({fill:meta(code).fill,glow:meta(code).fill+'88'})});
})();
+704
View File
@@ -0,0 +1,704 @@
.nav button:focus-visible,
.moduleNav button:focus-visible,
.tool[role="button"]:focus-visible {
outline: 2px solid #65d8ff;
outline-offset: 2px;
}
#app .top { z-index: 2300; }
body { color-scheme: dark; }
#app .top .nav { align-items: center; flex-wrap: nowrap; }
#app .top .nav .btn { margin: 0; flex: 0 0 auto; }
.overview-totals { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
.overview-totals span { color: #b9d6e8; font-size: 12px; padding: 4px 8px; border: 1px solid #294a60; border-radius: 5px; background: #102639; }
.overview-totals strong { margin-inline-start: 3px; color: #f0f9ff; font-variant-numeric: tabular-nums; }
.mapDisplayOptions {
grid-column: 1 / -1;
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
padding-top: 5px;
border-top: 1px solid #36546a;
color: #e1f2ff;
}
.mapDisplayOptions label {
display: inline-flex;
align-items: center;
gap: 5px;
min-height: 22px;
font-size: 12px;
cursor: pointer;
}
.mapDisplayOptions input {
flex: none;
width: 14px;
height: 14px;
margin: 0;
accent-color: #74bfff;
cursor: pointer;
}
.mapDisplayOptions input:focus-visible {
outline: 2px solid #7ddcff;
outline-offset: 2px;
}
.nav-account {
flex: 0 0 auto;
max-width: 130px;
margin-inline: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
color: #a5c9de;
}
#workbenchNav button[aria-current="page"] {
border-color: #67bdff;
background: #123c60;
color: #e7f7ff;
}
.moduleNav {
display: flex;
flex: 0 0 auto;
flex-wrap: wrap;
gap: 3px 12px;
padding: 6px 14px 0;
border-bottom: 1px solid #28455b;
background: #0a1b2d;
}
.moduleNav[hidden] { display: none; }
.moduleNav button {
margin: 0;
padding: 7px 8px;
min-height: 34px;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: transparent;
box-shadow: none;
color: #b2cbdd;
font-size: 13px;
}
.moduleNav button:hover { color: #e9f6ff; }
.moduleNav button[aria-current="page"] { color: #e9f6ff; border-bottom-color: #69c2ff; }
@media (max-width: 2240px) {
#app .top .nav { gap: 5px !important; }
#app .top .nav .btn { padding-inline: 7px !important; font-size: 12px !important; }
.nav-account { max-width: 110px; }
}
@media (max-width: 1700px) {
#app .top { height: 102px; align-items: flex-start; padding-top: 13px !important; }
#app .top .titleBox {
position: absolute;
left: 50%;
top: 31px;
margin: 0;
transform: translate(-50%, -50%);
max-width: calc(100% - 32px);
white-space: nowrap;
overflow: hidden;
}
#app .top .title { overflow: hidden; text-overflow: ellipsis; }
#app .top .nav {
position: absolute;
inset: auto 14px 8px;
max-width: none;
justify-content: safe center;
overflow-x: auto;
padding: 3px;
}
#app .main { top: 102px; }
}
@media (max-width: 900px) {
#app .top { height: 122px; }
#app .top .brand { display: flex; position: absolute; left: 50%; top: 49px; transform: translateX(-50%); }
#app .top .brandLogo { display: none; }
#app .main { top: 122px; }
}
#rid-workbench-status {
position: fixed;
z-index: 4000;
inset: auto 1rem 1rem auto;
max-width: min(420px, calc(100vw - 2rem));
margin: 0;
padding: 0.75rem 1rem;
border: 1px solid #2b6894;
border-radius: 10px;
background: #0b2035;
color: #e6f6ff;
}
.rid-module-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
margin-bottom: 14px;
color: #b2cada;
font-size: 13px;
line-height: 1.5;
}
.rid-module-editor:empty { display: none; }
.rid-module-feedback { padding: 9px 12px; margin-bottom: 10px; color: #9ff3d9; border: 1px solid #266977; border-radius: 8px; }
.rid-module-feedback.dangerText { color: #ffc4cb; border-color: #864555; }
.moduleBody :focus-visible,
.mapWrap :is(button, select):focus-visible,
.centerLoginPanel button:focus-visible { outline: 2px solid #7ddcff; outline-offset: 2px; }
.rid-admin-form, .rid-admin-form fieldset, .rid-admin-fields {
display: flex; flex-wrap: wrap; align-items: end; gap: 10px;
}
.rid-admin-form fieldset { border: 0; margin: 0; padding: 0; min-width: 0; }
.rid-admin-form label, .rid-period label { display: grid; gap: 5px; color: #c7e5f6; font-size: 13px; }
.rid-admin-form .rid-check { display: flex; flex-direction: row; align-items: center; min-height: 34px; }
.rid-module-page [hidden] { display: none !important; }
.rid-module-page button:disabled { opacity: .55; cursor: default; }
.moduleBody {
padding: clamp(12px, 1.5vw, 24px);
background: #0b1d2e;
}
.moduleBody .rid-period {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 12px;
padding: 12px;
border-color: #29465c;
background: #102438;
}
.rid-period label { min-width: 0; flex: 0 1 190px; }
.rid-period label:first-child:has(input:not([type])) { flex: 1 1 220px; max-width: 380px; }
#alarmFilters label:has(select) { flex-basis: 135px; }
.moduleBody :is(input:not([type=checkbox]), select) { min-width: 0; min-height: 36px; }
.moduleBody input::placeholder { color: #8ea9bd; }
.moduleBody button:not(.red):not(:disabled) { background: #1b63a6; }
.moduleBody button:not(.red):not(:disabled):hover { background: #2376be; }
.moduleBody :is(.rid-period, .rid-module-toolbar, .rid-admin-form) button { min-height: 36px; padding-inline: 14px; }
.moduleBody .rid-module-toolbar button[data-action="refresh-rx"],
.moduleBody .rid-admin-form button[data-action="cancel-edit"],
.moduleBody .dataTable button:not(.red):not(:disabled) {
box-shadow: inset 0 0 0 1px #365973;
background: #18324a;
}
.moduleBody .dataTable :is(th, td) { vertical-align: middle; }
.moduleBody .dataTable td { overflow-wrap: anywhere; }
.moduleBody .dataTable th { background: #132d43; }
.moduleBody .dataTable tbody tr:last-child td { border-bottom: 0; }
.moduleBody .dataTable td .smallBtn { margin: 2px; padding: 5px 8px; }
.moduleBody .resultCount { font-size: 13px; color: #bed3e1; font-variant-numeric: tabular-nums; }
.moduleBody .moduleEmpty {
min-height: 116px;
padding: 16px;
text-align: center;
color: #aac2d4;
}
.moduleBody .moduleSplit {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.moduleBody .moduleSplit .dataTable { min-width: 0; }
.moduleBody .moduleSplit .dataTable :is(th, td) { white-space: normal; }
.moduleBody .moduleSplit .dataTable :is(th, td):last-child {
text-align: end;
font-variant-numeric: tabular-nums;
}
.moduleBody .stateTag.neutral { background: #223b51; color: #c1d4e3; }
.moduleBody .stateTag { white-space: normal; max-width: 240px; }
.moduleBody .dataTableWrap { max-height: max(180px, calc(100dvh - 350px)); }
.moduleBody:not([hidden]):has(#alarmResult), #alarmResult {
display: flex;
flex-direction: column;
min-height: 0;
}
#alarmResult { flex: 1 1 auto; }
#alarmFilters, #alarmResult > :is(.resultCount, .rid-pager) { flex: none; }
#alarmResult > .dataTableWrap { min-height: 0; }
@media (max-width: 560px), (max-height: 620px) {
#alarmResult { flex: none; }
#alarmResult > .dataTableWrap { max-height: 52dvh; }
}
.moduleBody .rid-pager .rid-pager-actions button:not(:disabled) { background: #18344c; }
.moduleBody .rid-pager .rid-pager-actions button:hover:not(:disabled) { background: #254f70; }
[data-module="configs"] { max-width: 780px; }
.rid-config-form fieldset { display: grid; width: 100%; gap: 14px; }
.rid-config-form input[name="name"] { max-width: 410px; }
.rid-config-form button { justify-self: start; }
.rid-config-options { display: flex; flex-wrap: wrap; column-gap: 20px; }
.rid-admin-form :is(label, .rid-admin-fields) { max-width: 100%; }
.rid-admin-form input[type="checkbox"] { width: 16px; height: 16px; accent-color: #489be5; }
.rid-admin-form .btnrow { flex-wrap: wrap; }
@media (max-width: 760px) {
.moduleBody .moduleSplit { grid-template-columns: 1fr; }
}
@media (max-width: 560px) {
#app .top .nav { inset-inline: 8px; }
.nav-account { max-width: 64px; }
#app .moduleBody .rid-period {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
}
.rid-period label:has(input:not([type])),
.rid-period label:has(select),
.rid-period button { grid-column: 1 / -1; }
.rid-period label:has(input:not([type])) { max-width: none; }
.rid-period button { justify-self: end; }
}
@media (max-width: 410px) {
.nav-account { display: none; }
#app .moduleBody .rid-period { grid-template-columns: 1fr !important; }
}
.loginCenterMountain .centerLoginScene {
display: grid;
grid-template-rows: auto 1fr auto;
gap: 24px;
min-height: 100dvh;
padding: clamp(18px, 3vw, 42px);
}
.loginCenterMountain .centerLoginHeader,
.loginCenterMountain .centerLoginPanel,
.loginCenterMountain .centerLoginFooter { position: relative; inset: auto; }
.loginCenterMountain .centerLoginBg { animation: none; }
.loginCenterMountain .centerLoginPanel {
place-self: center;
transform: none;
width: min(100%, 410px);
padding: clamp(20px, 3vw, 36px);
border-radius: 14px;
border-color: #365976;
box-shadow: 0 16px 50px #0006;
background: #0b2035f2;
}
.centerLoginPanel::before,
.centerLoginSubmit::before { display: none; }
.centerPanelHeading h1 { margin: 0 0 24px; font-size: 24px; color: #f4f9ff; }
.centerLoginPanel .centerField input { padding-inline: 13px; }
.centerLoginPanel .centerLoginSubmit {
height: 44px;
letter-spacing: 0;
font-size: 15px;
background: #1a69ad;
border: 1px solid #3d8ac8;
box-shadow: none;
}
.centerLoginPanel .centerLoginSubmit:hover { transform: none; }
.centerLoginPanel .centerLoginState { text-align: center; color: #b0c9dc; }
.centerLoginFooter { color: #b0c5d7; }
#moduleTitle {
position: absolute;
inset: 0 auto auto 0;
width: 1px;
height: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
#moduleBody[hidden], #moduleEmbed [hidden], #moduleEmbed[hidden] { display: none; }
.moduleEmbed { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.moduleEmbed iframe { flex: 1; min-height: 0; width: 100%; border: 0; }
#moduleEmbedStatus { margin: 18px 20px; color: #bfddf2; }
#moduleEmbedRetry { align-self: start; margin: 0 20px; }
#app .left { overflow: hidden; }
#app .left .deviceListPanel,
#app .left .targetListPanel {
display: flex;
flex-direction: column;
flex: 1 1 0;
min-height: 0;
overflow: hidden;
}
#app .left .p-title { flex: 0 0 auto; }
#app .left #stationList,
#app .left #droneList {
flex: 1 1 auto;
min-height: 0;
max-height: none;
overflow: auto;
padding-inline-end: 3px;
}
#app .right { overflow: hidden; }
#app .right > :is(.zonePanel, .alertPanel) {
display: flex;
flex-direction: column;
flex: 1 1 0;
min-height: 0;
overflow: hidden;
}
#app .right .p-title { flex: 0 0 auto; }
#app .right :is(.zonePanelContent, #alertList) {
flex: 1 1 auto;
min-height: 0;
max-height: none;
overflow: auto;
padding-inline-end: 3px;
}
#app .main > :is(.left, .right) { max-width: 100%; }
@media (max-width: 1100px) {
#app .main { grid-template-columns: minmax(0, 1fr) !important; }
#app .main > :is(.left, .right) { top: 62px; bottom: 12px; max-height: none; }
#app .sideToggle { top: 12px; transform: none; height: 36px; border-radius: 7px; }
#app .main .sideToggle.leftToggle { left: 9px; }
#app .main .sideToggle.rightToggle { right: 9px; }
}
.zonePanelContent [hidden] { display: none; }
.zoneCoordinateEntry {
border: 1px solid #284a61;
border-radius: 6px;
background: #0c2136;
}
.zoneCoordinateEntry > summary {
padding: 8px 10px;
color: #cae7f6;
cursor: pointer;
}
.zoneCoordinateEntry > summary:hover { background: #132c42; }
.zoneCoordinateEntry form,
.zoneCoordinateEntry form label { display: grid; gap: 5px; min-width: 0; }
.zoneCoordinateEntry form { gap: 8px; border-top: 1px solid #284a61; padding: 9px; font-size: 12px; }
.zoneFormFields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(86px, .64fr); gap: 7px; }
.zoneCoordinateEntry :is(input, select, textarea) { width: 100%; min-width: 0; }
.zoneCoordinateEntry textarea {
border: 1px solid #325671;
border-radius: 5px;
padding: 7px 8px;
background: #091a2d;
color: #dcecf6;
resize: vertical;
font: 12px/1.5 ui-monospace, monospace;
}
.zoneCoordinateEntry form button { justify-self: end; }
#zoneCoordinateHelp, .zoneDrawEditor p { margin: 0; color: #a8c7dc; font-size: 12px; }
.zoneDrawEditor {
margin-top: 8px;
padding: 8px;
border: 1px solid #284a61;
border-radius: 6px;
}
.zoneDrawActions { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; margin-top: 7px; }
.zoneDrawActions input { width: 100%; }
.zoneDrawActions button { white-space: nowrap; }
.zoneFeedback { flex: 0 0 auto; margin: 0 0 8px; color: #a3dfca; font-size: 12px; }
.zoneFeedback.error { color: #ffadb7; }
.zoneList { list-style: none; margin: 10px 0 0; padding: 0; }
.zoneListItem, .workbenchAlert { padding: 9px 10px; border: 1px solid #244359; border-radius: 6px; background: #0c2032; }
.zoneListItem + .zoneListItem, .workbenchAlert + .workbenchAlert { margin-top: 7px; }
.zoneListHead, .workbenchAlertHead, .workbenchAlertTarget {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 3px 8px;
}
.zoneListHead b, .workbenchAlertHead b, .workbenchAlertId { overflow-wrap: anywhere; }
.zoneListMeta { margin: 4px 0; color: #a8c7dc; font-size: 12px; }
.zoneListItem .zoneActions { margin-top: 7px; }
#zoneList .zoneFocus {
display: block;
width: 100%;
margin: 0;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
color: inherit;
text-align: start;
}
#zoneList .zoneFocus:hover b { text-decoration: underline; color: #98d7ff; }
#zoneList .zoneFocus:focus-visible { outline: 2px solid #65d8ff; outline-offset: 3px; }
#zoneList .zoneFocus .zoneListMeta { display: block; font-weight: 400; }
.workbenchAlert { border-width: 2px; }
.workbenchAlertHead { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; }
.workbenchAlertHead b { font-size: 14px; }
.workbenchAlertMeta { position: relative; display: inline-flex; align-items: center; padding-inline-end: 13px; }
.workbenchAlertHead time { color: #a8c7dc; font-size: 11px; white-space: nowrap; font-variant-numeric: tabular-nums; }
.workbenchAlertId { display: block; margin-top: 5px; color: #cfe5f3; font-size: 12px; }
.workbenchAlertTarget { margin-top: 5px; }
.workbenchAlertPosition { color: #a8c7dc; font-size: 12px; font-variant-numeric: tabular-nums; }
.panel .panelCount { margin-inline-start: auto; color: #b5d4e5; font-size: 12px; font-weight: 500; white-space: nowrap; font-variant-numeric: tabular-nums; }
.alert-unread-dot { position: absolute; inset-inline-end: 0; top: 50%; transform: translateY(-50%); width: 7px; height: 7px; border-radius: 50%; background: #ff5b74; }
.rid-station-marker { position: relative; box-sizing: border-box; display: grid; place-items: center; width: 31px; height: 31px; border: 2px solid #bcdfff; border-radius: 7px; background: #28639f; color: white; box-shadow: 0 1px 6px #081725b0; }
.rid-station-marker.waiting { background: #6b4b26; border-color: #f4cc8c; }
.rid-station-marker.offline { background: #344453; border-color: #acbcc8; }
.alertPanel .alarmSettingRow {
flex: 0 0 auto;
margin-top: 8px;
padding: 8px 0 0;
border-top: 1px solid #244359;
}
#stationList .stationCard {
margin: 0 0 8px;
border: 1px solid #22435d;
border-radius: 8px;
background: #0c2136;
font-size: 12px;
line-height: 1.4;
}
#stationList .stationCard.offline { background: #0a1b2d; }
.stationCardHead {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 2px 9px;
padding: 8px 10px;
cursor: pointer;
list-style: none;
}
.stationCardHead::-webkit-details-marker { display: none; }
.stationCardHead::before {
content: "";
grid-column: 1;
grid-row: 1 / 3;
width: 6px;
height: 6px;
border-right: 1px solid #a8c7dc;
border-bottom: 1px solid #a8c7dc;
transform: rotate(-45deg);
}
.stationCard[open] .stationCardHead::before { transform: rotate(45deg); }
.stationCardHead:hover { background: #142c41; }
.stationCardHead:focus-visible { outline: 2px solid #65d8ff; outline-offset: -2px; }
.stationName { grid-column: 2; grid-row: 1; overflow-wrap: anywhere; font-size: 13px; }
.stationTransport { grid-column: 2; grid-row: 2; color: #a8c7dc; }
.stationCardHead .tag { grid-column: 3; grid-row: 1 / 3; white-space: nowrap; }
.stationCardBody { padding: 6px 10px 9px; border-top: 1px solid #22435d; }
.stationAddress {
overflow-wrap: anywhere;
margin-top: 3px;
color: #9dc1d9;
font-variant-numeric: tabular-nums;
}
.stationFix, .stationExtra { margin: 5px 0 0; color: #a8c7dc; }
.stationFix.fixed { color: #92e6be; }
.stationMetrics {
display: grid;
grid-template-columns: 1.3fr 1fr 1fr;
gap: 5px;
margin: 6px 0 0;
}
.stationMetrics div {
min-width: 0;
background: #102942;
border-radius: 5px;
padding: 4px 6px;
}
.stationMetrics dt { font-size: 11px; color: #a8c7dc; }
.stationMetrics dd { color: #e4f5ff; font-variant-numeric: tabular-nums; margin: 1px 0 0; }
.stationPosition { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; margin-top: 6px; }
.stationPosition span { flex-basis: 100%; font-variant-numeric: tabular-nums; }
.stationPosition .smallBtn:focus-visible { outline: 2px solid #65d8ff; outline-offset: 2px; }
.targetCard button:focus-visible { outline: 2px solid #65d8ff; outline-offset: 2px; }
.targetCard {
background: #0c2136; border: 1px solid #22435d; border-left: 3px solid var(--target-accent);
border-radius: 8px; padding: 9px 10px; margin: 0 0 8px; font-size: 12px; line-height: 1.4;
}
.targetCard.active { border-color: #5ecbff; border-left-color: var(--target-accent); }
.targetCardHead, .targetIdentity, .targetTelemetry {
display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px;
}
.targetCardHead strong { font-size: 14px; min-width: 0; overflow-wrap: anywhere; }
.targetIdentity { color: #b4d4e9; margin-top: 3px; }
.targetIdentity code { min-width: 0; overflow-wrap: anywhere; }
.targetIdentity .tag, .targetCardHead .tag { flex: none; }
.targetTelemetry { margin-top: 8px; padding: 5px 7px; border-radius: 5px; background: #102942; }
.targetSecondary { margin: 4px 0 0; color: #a8c7dc; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
.targetActions { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 8px; }
/* Shared flight classification across live cards, records and filings. */
.flightTag { display:inline-flex; align-items:center; gap:5px; padding:2px 7px; border:1px solid; border-radius:4px; font-size:12px; line-height:1.5; font-weight:600; white-space:nowrap; }
.flightTag.warning { color:#ffe29a; background:#554016; border-color:#b88624; }
.flightTag.danger { color:#ffd0d4; background:#531f2a; border-color:#b83d4b; }
.flightTag.ok { color:#9ce9c7; background:#153e32; border-color:#287757; }
.flightTag.white { color:#a6e4fa; background:#163a4c; border-color:#3085a3; }
.flightTag.muted { color:#c3ccd5; background:#263540; border-color:#536575; }
.workbenchAlert.warning { border-color:#a67720; background:#2d291c; }
.workbenchAlert.danger { border-color:#ab3948; background:#311e28; }
.workbenchAlert.warning .alert-unread-dot { background:#efbd49; }
.workbenchAlert.danger .alert-unread-dot { background:#ff6172; }
.alertClassification { margin:6px 0 2px; }
.workbenchAlertTarget { flex-wrap:wrap; gap:6px; }
.workbenchAlertPosition { flex:1 1 100%; }
.panelCount { display:inline-flex; flex-wrap:wrap; justify-content:flex-end; gap:8px; font-size:11px; }
.countOk { color:#6bd5a5; } .countWarning { color:#ecc66a; } .countMuted { color:#a2b2bf; }
.dot.flightWarning { background:#ca921e; } .dot.flightDanger { background:#cc3c48; }
/* Reserve the Leaflet zoom column and attribution strip. The remaining controls share one grid. */
.mapWrap { container: live-map / size; }
.mapDock {
position: absolute;
inset: auto 14px 24px 60px;
z-index: 4;
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: end;
gap: 8px;
pointer-events: none;
}
.mapDock > :is(.legend, .toolbar, .mapSourceBox) {
position: static;
inset: auto !important;
transform: none !important;
min-width: 0;
max-width: 100% !important;
pointer-events: auto;
}
.mapDock > .legend {
justify-self: start;
display: block !important;
width: min(328px, 100%) !important;
}
.mapLegendToggle { display: none; }
.mapLegendContent { display: grid; gap: 8px; }
.mapDock > .toolbar {
justify-self: center;
display: flex;
justify-content: center;
gap: 4px !important;
padding: 5px 7px !important;
width: min(292px, 100%);
}
.mapDock .toolbar .tool {
flex: 1 1 0;
display: grid;
place-items: center;
min-width: 0 !important;
min-height: 32px;
padding: 2px !important;
}
.mapDock > .mapSourceBox {
justify-self: end;
flex-wrap: wrap;
justify-content: flex-start;
}
.mapWrap .leaflet-bottom.leaflet-left {
left: 12px !important;
bottom: 24px !important;
}
@container live-map (max-width: 1060px) or (max-height: 370px) {
.mapDock > .legend {
width: fit-content !important;
padding: 4px 7px !important;
}
.mapDock > .legend:has(> .mapLegendToggle[aria-expanded="true"]) {
width: min(328px, 100%) !important;
}
.mapLegendToggle {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
width: 100%;
min-height: 30px;
padding: 3px 6px;
background: transparent;
border: 0;
color: inherit;
font: inherit;
line-height: 1.35;
text-align: left;
cursor: pointer;
}
.mapLegendArrow {
flex: 0 0 auto;
width: 6px;
height: 6px;
border: solid currentColor;
border-width: 0 1px 1px 0;
transform: translateY(1px) rotate(225deg);
}
.mapLegendToggle[aria-expanded="true"] .mapLegendArrow { transform: translateY(-2px) rotate(45deg); }
.mapLegendToggle[aria-expanded="false"] + .mapLegendContent { display: none; }
.mapLegendContent {
max-height: clamp(58px, 32cqh, 180px);
overflow: auto;
padding: 6px 4px 3px;
}
}
@container live-map (max-width: 810px) {
.mapDock { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.mapDock > .legend { grid-column: 1 / -1; }
.mapDock > .toolbar { justify-self: start; }
.mapLegendContent { max-height: clamp(36px, calc(100cqh - 148px), 180px); }
}
@container live-map (max-width: 430px) {
.mapDock { grid-template-columns: minmax(0, 1fr); inset-inline: 52px 10px; }
.mapLegendContent { max-height: clamp(24px, calc(100cqh - 168px), 180px); }
.mapDock > :is(.toolbar, .mapSourceBox) { justify-self: start; }
.mapDock > .legend { max-width: calc(100% - 40px) !important; }
}
@container live-map (max-height: 320px) {
#app .main .mapWrap > .sideToggle {
top: 12px;
transform: none;
height: 36px;
}
}
.legendStatus { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:7px 12px; }
.legend .legendStatus span { min-width:0; align-items:flex-start !important; white-space:normal !important; line-height:1.5 !important; }
.legend .legendStatus .dot { margin-top:4px; }
.legendStatus em { min-width:0; overflow-wrap:anywhere; }
.legendSymbols { display:flex; flex-wrap:wrap; align-items:center; gap:8px 16px; }
.legend .mapDisplayOptions { gap:6px 12px; padding-top:8px; }
.legend .mapDisplayOptions label { white-space:nowrap; min-height:24px; }
/* Fill the workspace; keep pagination below the independently scrolling list. */
.moduleBody:has(> [data-module="flight-plans"]) { display:flex; flex-direction:column; overflow:hidden; }
[data-module="flight-plans"] { width:100%; max-width:none; flex:1; min-height:0; display:flex; flex-direction:column; }
[data-module="flight-plans"] > .rid-module-feedback { flex:none; }
[data-module="flight-plans"] > .rid-module-content { flex:1; min-height:0; display:flex; flex-direction:column; gap:12px; }
[data-module="flight-plans"] .rid-module-toolbar { flex:none; margin:0; }
[data-module="flight-plans"] .rid-module-editor:empty { display:none; }
[data-module="flight-plans"] .rid-module-editor { flex:0 1 auto; min-height:0; max-height:65%; overflow:auto; }
[data-module="flight-plans"] .rid-module-editor > :last-child { margin-bottom:0; }
[data-module="flight-plans"] .planResults { flex:1; min-height:120px; display:flex; flex-direction:column; gap:10px; }
.moduleBody [data-module="flight-plans"] .planResults > .dataTableWrap { flex:1; min-height:0; max-height:none; overflow:auto; }
.moduleBody [data-module="flight-plans"] .planResults > .moduleEmpty { flex:1; min-height:0; display:grid; place-items:center; margin:0; }
[data-module="flight-plans"] .planResults > .rid-pager { flex:none; margin:0; }
[data-module="flight-plans"] .dataTable th { position:sticky; top:0; z-index:1; }
@media (max-height:540px) {
.moduleBody:has(> [data-module="flight-plans"]) { overflow:auto; }
[data-module="flight-plans"] { flex:none; min-height:100%; }
[data-module="flight-plans"] .rid-module-editor { flex:none; max-height:none; overflow:visible; }
[data-module="flight-plans"] .planResults { flex:none; min-height:220px; }
.moduleBody [data-module="flight-plans"] .planResults > .dataTableWrap { flex:none; max-height:50dvh; }
}
[data-module="flight-plans"] .rid-module-toolbar { padding:12px 14px; border:1px solid #29465c; border-radius:8px; background:#102438; }
.flightPlanForm { width:100%; max-width:none; box-sizing:border-box; }
[data-module="flight-plans"] .planSearch { flex:1 1 260px; width:auto; max-width:520px; }
[data-module="flight-plans"] .rid-module-toolbar > label { display:flex; align-items:center; gap:8px; }
[data-module="flight-plans"] .rid-module-toolbar select { width:auto; min-width:150px; }
.planFormHeader { margin-bottom:18px; border-bottom:1px solid #29465c; padding-bottom:14px; }
.planFormHeader h3 { margin:0 0 6px; font-size:16px; }
.planFormHeader p,.planFieldGroup p { margin:0; font-size:12px; line-height:1.7; }
.planEditorColumns { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:24px; }
.planFieldGroup { min-width:0; }
.planFieldGroup h4 { margin:0 0 14px; font-size:13px; font-weight:600; color:#c7e5f6; }
.planFormGrid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px 14px; }
.flightPlanForm label,.planReviewForm label { display:flex; min-width:0; flex-direction:column; gap:6px; margin-bottom:12px; font-size:13px; line-height:1.5; }
.flightPlanForm :is(input,select),.planReviewForm select { width:100%; box-sizing:border-box; min-width:0; }
.flightPlanForm textarea,.planReviewForm textarea { width:100%; box-sizing:border-box; padding:10px; border:1px solid #35566c; border-radius:6px; color:#d9e9f3; background:#091b2a; font:inherit; resize:vertical; }
.flightPlanForm .btnrow,.planReviewForm .btnrow { display:flex; justify-content:flex-end; gap:8px; margin-top:18px; padding-top:14px; border-top:1px solid #29465c; }
.moduleBody [data-module="flight-plans"] button[data-action="cancel-edit"],.moduleBody [data-module="flight-plans"] button[data-action="refresh-plans"] { background:#18324a; border:1px solid #365973; }
.planDetails { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; }
.planDetails dd { margin:0; } .planDetails pre,[data-module="flight-plans"] pre { white-space:pre-wrap; overflow-wrap:anywhere; }
[data-module="flight-plans"] .dataTable td:last-child { min-width:170px; }
[data-module="flight-plans"] .smallBtn { margin:2px; }
@media(max-width:1000px) { .planEditorColumns {grid-template-columns:1fr; gap:8px;} }
@media(max-width:600px) { .planFormGrid {grid-template-columns:1fr; gap:0;} .planDetails {grid-template-columns:1fr;} [data-module="flight-plans"] .planSearch {max-width:none; flex-basis:100%; order:1;} }
/* The create/edit form lives in the browser top layer, without resizing the list. */
.flightPlanDialog { width:min(1040px,calc(100vw - 40px)); max-width:none; max-height:calc(100dvh - 40px); box-sizing:border-box; margin:auto; padding:0; border:1px solid #365973; border-radius:12px; background:#0b1d2e; color:#d9e9f3; box-shadow:0 20px 70px #0008; overflow:auto; color-scheme:dark; }
.flightPlanDialog::backdrop { background:rgba(2,10,18,.7); }
.flightPlanDialog .flightPlanForm { margin:0; padding:24px; border:0; border-radius:0; background:none; }
.flightPlanDialog .planFormHeader { position:relative; padding-right:42px; }
.flightPlanDialog .planFormHeader h3 { font-size:18px; }
.moduleBody .flightPlanDialog .planDialogClose { position:absolute; top:-6px; right:-6px; display:grid; place-items:center; width:32px; height:32px; padding:0; border:1px solid transparent; border-radius:6px; background:transparent; color:#bcd1e0; font-size:24px; font-weight:400; line-height:1; }
.moduleBody .flightPlanDialog .planDialogClose:hover { background:#1a344a; color:#fff; }
.flightPlanDialog .planDialogFeedback { margin-bottom:16px; }
.flightPlanDialog:has(button[type="submit"]:disabled) :is(.planDialogClose,[data-action="cancel-edit"]) { opacity:.5; cursor:wait; }
@media(max-width:600px) { .flightPlanDialog { width:calc(100vw - 24px); max-height:calc(100dvh - 24px); } .flightPlanDialog .flightPlanForm { padding:18px; } }
@@ -0,0 +1,26 @@
BSD 2-Clause License
Copyright (c) 2010-2023, Volodymyr Agafonkin
Copyright (c) 2010-2011, CloudMade
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 B

+661
View File
@@ -0,0 +1,661 @@
/* required styles */
.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position: absolute;
left: 0;
top: 0;
}
.leaflet-container {
overflow: hidden;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-user-drag: none;
}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
image-rendering: -webkit-optimize-contrast;
}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
width: 1600px;
height: 1600px;
-webkit-transform-origin: 0 0;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
max-width: none !important;
max-height: none !important;
}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
max-width: none !important;
max-height: none !important;
width: auto;
padding: 0;
}
.leaflet-container img.leaflet-tile {
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
mix-blend-mode: plus-lighter;
}
.leaflet-container.leaflet-touch-zoom {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.leaflet-container.leaflet-touch-drag {
-ms-touch-action: pinch-zoom;
/* Fallback for FF which doesn't support pinch-zoom */
touch-action: none;
touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
-ms-touch-action: none;
touch-action: none;
}
.leaflet-container {
-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
filter: inherit;
visibility: hidden;
}
.leaflet-tile-loaded {
visibility: inherit;
}
.leaflet-zoom-box {
width: 0;
height: 0;
-moz-box-sizing: border-box;
box-sizing: border-box;
z-index: 800;
}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
-moz-user-select: none;
}
.leaflet-pane { z-index: 400; }
.leaflet-tile-pane { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane { z-index: 500; }
.leaflet-marker-pane { z-index: 600; }
.leaflet-tooltip-pane { z-index: 650; }
.leaflet-popup-pane { z-index: 700; }
.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg { z-index: 200; }
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
/* control positioning */
.leaflet-control {
position: relative;
z-index: 800;
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
.leaflet-top,
.leaflet-bottom {
position: absolute;
z-index: 1000;
pointer-events: none;
}
.leaflet-top {
top: 0;
}
.leaflet-right {
right: 0;
}
.leaflet-bottom {
bottom: 0;
}
.leaflet-left {
left: 0;
}
.leaflet-control {
float: left;
clear: both;
}
.leaflet-right .leaflet-control {
float: right;
}
.leaflet-top .leaflet-control {
margin-top: 10px;
}
.leaflet-bottom .leaflet-control {
margin-bottom: 10px;
}
.leaflet-left .leaflet-control {
margin-left: 10px;
}
.leaflet-right .leaflet-control {
margin-right: 10px;
}
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-popup {
opacity: 0;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity: 1;
}
.leaflet-zoom-animated {
-webkit-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
}
svg.leaflet-zoom-animated {
will-change: transform;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.leaflet-zoom-anim .leaflet-zoom-hide {
visibility: hidden;
}
/* cursors */
.leaflet-interactive {
cursor: pointer;
}
.leaflet-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
cursor: crosshair;
}
.leaflet-popup-pane,
.leaflet-control {
cursor: auto;
}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
cursor: move;
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
pointer-events: none;
}
.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
/* visual tweaks */
.leaflet-container {
background: #ddd;
outline-offset: 1px;
}
.leaflet-container a {
color: #0078A8;
}
.leaflet-zoom-box {
border: 2px dotted #38f;
background: rgba(255,255,255,0.5);
}
/* general typography */
.leaflet-container {
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.5;
}
/* general toolbar styles */
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
}
.leaflet-bar a {
background-color: #fff;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar a,
.leaflet-control-layers-toggle {
background-position: 50% 50%;
background-repeat: no-repeat;
display: block;
}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
background-color: #f4f4f4;
}
.leaflet-bar a:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar a:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar a.leaflet-disabled {
cursor: default;
background-color: #f4f4f4;
color: #bbb;
}
.leaflet-touch .leaflet-bar a {
width: 30px;
height: 30px;
line-height: 30px;
}
.leaflet-touch .leaflet-bar a:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.leaflet-touch .leaflet-bar a:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
/* zoom control */
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
font: bold 18px 'Lucida Console', Monaco, monospace;
text-indent: 1px;
}
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
font-size: 22px;
}
/* layers control */
.leaflet-control-layers {
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
background: #fff;
border-radius: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(images/layers.png);
width: 36px;
height: 36px;
}
.leaflet-retina .leaflet-control-layers-toggle {
background-image: url(images/layers-2x.png);
background-size: 26px 26px;
}
.leaflet-touch .leaflet-control-layers-toggle {
width: 44px;
height: 44px;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display: none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display: block;
position: relative;
}
.leaflet-control-layers-expanded {
padding: 6px 10px 6px 6px;
color: #333;
background: #fff;
}
.leaflet-control-layers-scrollbar {
overflow-y: scroll;
overflow-x: hidden;
padding-right: 5px;
}
.leaflet-control-layers-selector {
margin-top: 2px;
position: relative;
top: 1px;
}
.leaflet-control-layers label {
display: block;
font-size: 13px;
font-size: 1.08333em;
}
.leaflet-control-layers-separator {
height: 0;
border-top: 1px solid #ddd;
margin: 5px -10px 5px -6px;
}
/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
background-image: url(images/marker-icon.png);
}
/* attribution and scale controls */
.leaflet-container .leaflet-control-attribution {
background: #fff;
background: rgba(255, 255, 255, 0.8);
margin: 0;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding: 0 5px;
color: #333;
line-height: 1.4;
}
.leaflet-control-attribution a {
text-decoration: none;
}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
text-decoration: underline;
}
.leaflet-attribution-flag {
display: inline !important;
vertical-align: baseline !important;
width: 1em;
height: 0.6669em;
}
.leaflet-left .leaflet-control-scale {
margin-left: 5px;
}
.leaflet-bottom .leaflet-control-scale {
margin-bottom: 5px;
}
.leaflet-control-scale-line {
border: 2px solid #777;
border-top: none;
line-height: 1.1;
padding: 2px 5px 1px;
white-space: nowrap;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
text-shadow: 1px 1px #fff;
}
.leaflet-control-scale-line:not(:first-child) {
border-top: 2px solid #777;
border-bottom: none;
margin-top: -2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom: 2px solid #777;
}
.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
box-shadow: none;
}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}
/* popup */
.leaflet-popup {
position: absolute;
text-align: center;
margin-bottom: 20px;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
}
.leaflet-popup-content {
margin: 13px 24px 13px 20px;
line-height: 1.3;
font-size: 13px;
font-size: 1.08333em;
min-height: 1px;
}
.leaflet-popup-content p {
margin: 17px 0;
margin: 1.3em 0;
}
.leaflet-popup-tip-container {
width: 40px;
height: 20px;
position: absolute;
left: 50%;
margin-top: -1px;
margin-left: -20px;
overflow: hidden;
pointer-events: none;
}
.leaflet-popup-tip {
width: 17px;
height: 17px;
padding: 1px;
margin: -10px auto 0;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: white;
color: #333;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
border: none;
text-align: center;
width: 24px;
height: 24px;
font: 16px/24px Tahoma, Verdana, sans-serif;
color: #757575;
text-decoration: none;
background: transparent;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
color: #585858;
}
.leaflet-popup-scrolled {
overflow: auto;
}
.leaflet-oldie .leaflet-popup-content-wrapper {
-ms-zoom: 1;
}
.leaflet-oldie .leaflet-popup-tip {
width: 24px;
margin: 0 auto;
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
}
.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
border: 1px solid #999;
}
/* div icon */
.leaflet-div-icon {
background: #fff;
border: 1px solid #666;
}
/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
position: absolute;
padding: 6px;
background-color: #fff;
border: 1px solid #fff;
border-radius: 3px;
color: #222;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.leaflet-tooltip.leaflet-interactive {
cursor: pointer;
pointer-events: auto;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
position: absolute;
pointer-events: none;
border: 6px solid transparent;
background: transparent;
content: "";
}
/* Directions */
.leaflet-tooltip-bottom {
margin-top: 6px;
}
.leaflet-tooltip-top {
margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
left: 50%;
margin-left: -6px;
}
.leaflet-tooltip-top:before {
bottom: 0;
margin-bottom: -12px;
border-top-color: #fff;
}
.leaflet-tooltip-bottom:before {
top: 0;
margin-top: -12px;
margin-left: -6px;
border-bottom-color: #fff;
}
.leaflet-tooltip-left {
margin-left: -6px;
}
.leaflet-tooltip-right {
margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
top: 50%;
margin-top: -6px;
}
.leaflet-tooltip-left:before {
right: 0;
margin-right: -12px;
border-left-color: #fff;
}
.leaflet-tooltip-right:before {
left: 0;
margin-left: -12px;
border-right-color: #fff;
}
/* Printing */
@media print {
/* Prevent printers from removing background-images of controls. */
.leaflet-control {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
File diff suppressed because one or more lines are too long
+102
View File
@@ -0,0 +1,102 @@
#liveMap3D {
position: absolute;
inset: 0;
z-index: 1;
}
#liveMap3D[hidden],
.rid-live-3d-marker[hidden],
.rid-live-3d-height[hidden],
.rid-live-3d-popup[hidden] { display: none; }
.mapWrap[data-map-mode="3d"] #map { visibility: hidden; }
.rid-live-3d-trails,
.rid-live-3d-markers {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.rid-live-3d-marker {
position: absolute;
padding: 0;
border: 0;
background: none;
box-shadow: none;
transform: translate(-50%, -50%);
outline-offset: 3px;
pointer-events: auto;
cursor: pointer;
}
.rid-live-3d-height {
position: absolute;
left: calc(100% + 5px);
top: 2px;
padding: 3px 6px;
border: 1px solid #74c4f484;
border-radius: 5px;
background: #071e32ed;
color: #e5f8ff;
font: 600 11px/1.4 system-ui, sans-serif;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.rid-live-3d-popup {
position: absolute;
transform: translate(-50%, calc(-100% - 20px));
z-index: 2;
padding: 12px 22px 12px 14px;
width: max-content;
max-width: min(310px, 100%);
overflow-wrap: anywhere;
border-radius: 12px;
background: #fff;
color: #152537;
box-shadow: 0 3px 15px #10202b75;
font: 13px/1.4 system-ui, sans-serif;
pointer-events: auto;
}
.rid-live-3d-popup.below { transform: translate(-50%, 20px); }
.rid-live-3d-popup button {
position: absolute;
right: 6px;
top: 4px;
padding: 0 4px;
border: 0;
background: transparent;
color: #516476;
box-shadow: none;
}
.mapWrap .zonePopupCard {
min-width: 100px;
color: #192e42;
overflow-wrap: anywhere;
font: 13px/1.5 system-ui, sans-serif;
}
.mapWrap .zonePopupCard strong { display: block; font-size: 14px; font-weight: 650; }
.mapWrap .zonePopupMeta { margin-top: 3px; color: #4b6072; }
.mapWrap .zoneMapPopup .maplibregl-popup-content {
padding: 10px 29px 10px 12px;
border-radius: 8px;
}
.mapWrap .zoneMapPopup .leaflet-popup-content { margin: 10px 29px 10px 12px; }
.mapWrap .zoneMapPopup :is(.maplibregl-popup-close-button, .leaflet-popup-close-button) {
padding: 0;
color: #4b6072;
background: transparent;
border: 0;
box-shadow: none;
font-size: 16px;
width: 24px;
height: 24px;
text-align: center;
}
.mapWrap .zoneMapPopup :is(.maplibregl-popup-close-button, .leaflet-popup-close-button):hover {
color: #192e42;
background: #e7edf2;
}
#mapViewToggle[aria-pressed="true"] {
border-color: #6bccff;
background: #166b97;
color: white;
}
+322
View File
@@ -0,0 +1,322 @@
import * as ml from '/vendor/maplibre-gl.mjs';
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
const COLLECTION = 'FeatureCollection';
function project(matrix, coordinate, width, height) {
const {x, y, z} = coordinate;
const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
if (w <= 0) return null;
return [
(1 + (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w) * width / 2,
(1 - (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w) * height / 2
];
}
export function openLiveMap(container, options) {
const {center, zoom, basemap, onCamera, onError} = options;
const map = new ml.Map({
container, center, zoom: zoom - 1, pitch: options.pitch ?? 52, bearing: options.bearing ?? 0, maxPitch: 70, maxZoom: 17,
renderWorldCopies: false, attributionControl: false,
style: {
version: 8,
sources: {
base: {type:'raster', tiles:[basemap.tiles], tileSize:256, maxzoom:18, attribution:'天地图 © 自然资源部'},
labels: {type:'raster', tiles:[basemap.labels || basemap.tiles], tileSize:256, maxzoom:18},
fences: {type:'geojson', data:{type:COLLECTION, features:[]}}
},
layers: [
{id:'background', type:'background', paint:{'background-color':'#0a1827'}},
{id:'base', type:'raster', source:'base'},
{id:'labels', type:'raster', source:'labels', layout:{visibility:basemap.labels ? 'visible' : 'none'}},
{id:'fences', type:'fill', source:'fences', paint:{'fill-color':'#ff536e','fill-opacity':0.18}},
{id:'fence-outline', type:'line', source:'fences', paint:{'line-color':'#ff637a','line-width':2}}
]
}
});
map.addControl(new ml.NavigationControl(), 'bottom-left');
map.addControl(new ml.AttributionControl({compact:true}), 'bottom-right');
const lines = document.createElement('canvas');
lines.className = 'rid-live-3d-trails';
lines.setAttribute('aria-hidden', 'true');
const context = lines.getContext('2d');
const overlay = document.createElement('div');
overlay.className = 'rid-live-3d-markers';
const popup = document.createElement('div');
popup.className = 'rid-live-3d-popup';
popup.hidden = true;
const close = document.createElement('button');
close.type = 'button';
close.setAttribute('aria-label', '关闭地图详情');
close.textContent = '×';
const popupBody = document.createElement('div');
popup.append(close, popupBody);
overlay.append(popup);
map.getCanvasContainer().append(lines, overlay);
let active = true;
let updatingCamera = false;
let selected = null;
let projection;
const zonePopup = new ml.Popup({closeButton:true, className:'zoneMapPopup', maxWidth:'260px'});
let config = basemap;
let fences = [];
let entries = new Map();
const elements = new Map();
let trailPoints = new WeakMap();
let trackCoords = options.trackCoords;
function closePopup() {
selected = null;
popup.hidden = true;
map.triggerRepaint();
}
close.addEventListener('click', () => {
const button = elements.get(selected)?.button;
closePopup();
button?.focus();
});
function showTarget(id) {
selected = id;
map.triggerRepaint();
}
function toGround(point) {
return ml.MercatorCoordinate.fromLngLat(point);
}
function toAir(point, height) {
return ml.MercatorCoordinate.fromLngLat(point, Math.max(0, height ?? 0));
}
function trailPoint(raw) {
let point = trailPoints.get(raw);
if (!point) {
point = toAir(trackCoords(raw[0], raw[1]), raw[2]);
trailPoints.set(raw, point);
}
return point;
}
function markerFor(entry) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'rid-live-3d-marker';
const visual = document.createElement('span');
const height = document.createElement('span');
height.className = 'rid-live-3d-height';
button.append(visual, height);
button.addEventListener('pointerdown', event => event.stopPropagation());
button.addEventListener('click', event => {
event.stopPropagation();
if (selected === entry.id) closePopup();
else showTarget(entry.id);
});
overlay.append(button);
return {button, visual, height, icon: null};
}
function updateEntries(next) {
entries = new Map();
for (const entry of next) {
entries.set(entry.id, {...entry, ground:toGround(entry.position), air:toAir(entry.position, entry.height),
pilotGround:entry.pilot ? toGround(entry.pilot) : null});
let element = elements.get(entry.id);
if (!element) elements.set(entry.id, element = markerFor(entry));
if (element.icon !== entry.icon) {
element.visual.replaceChildren(entry.icon?.cloneNode(true) || document.createTextNode(entry.label[0]));
element.icon = entry.icon;
element.plane = element.visual.querySelector('.rid-drone-plane');
}
element.button.setAttribute('aria-label', entry.label);
const value = entry.heightLabel || '';
if (element.height.textContent !== value) element.height.textContent = value;
element.height.hidden = !value;
}
for (const [id, element] of elements) {
if (entries.has(id)) continue;
element.button.remove();
elements.delete(id);
if (selected === id) closePopup();
}
map.triggerRepaint();
}
function paint(matrix) {
if (!active || !context || !matrix) return;
const width = container.clientWidth;
const height = container.clientHeight;
if (!width || !height) return;
projection = {matrix:matrix.slice(),width,height};
const scale = Math.min(window.devicePixelRatio || 1, 2);
const pixelsWide = Math.round(width * scale);
const pixelsHigh = Math.round(height * scale);
if (lines.width !== pixelsWide || lines.height !== pixelsHigh) {
lines.width = pixelsWide;
lines.height = pixelsHigh;
}
context.setTransform(scale, 0, 0, scale, 0, 0);
context.clearRect(0, 0, width, height);
context.lineJoin = context.lineCap = 'round';
let popupAnchor;
const screen = coordinate => project(matrix, coordinate, width, height);
for (const [id, entry] of entries) {
const element = elements.get(id);
const position = screen(entry.air);
const visible = position && position[0] >= -32 && position[0] <= width + 32
&& position[1] >= -30 && position[1] <= height + 30;
element.button.hidden = !visible;
if (visible) {
element.button.style.left = position[0] + 'px';
element.button.style.top = position[1] + 'px';
if (element.plane && Number.isFinite(entry.heading)) {
const angle = entry.heading * Math.PI / 180;
const distance = 20 * entry.air.meterInMercatorCoordinateUnits();
const ahead = screen({x:entry.air.x + Math.sin(angle) * distance,
y:entry.air.y - Math.cos(angle) * distance, z:entry.air.z});
if (ahead) {
const screenAngle = Math.atan2(ahead[0] - position[0], position[1] - ahead[1]) * 180 / Math.PI;
element.plane.style.transform = `rotate(${screenAngle}deg)`;
}
}
}
if (entry.trail) {
context.beginPath();
context.setLineDash([]);
context.strokeStyle = entry.trailColor || '#43efa0';
context.lineWidth = 2.5;
let previous;
for (const raw of entry.trail) {
const point = screen(trailPoint(raw));
if (!point) { previous = undefined; continue; }
if (previous && !raw[3]) {
context.lineTo(...point);
} else {
context.moveTo(...point);
}
previous = raw;
}
context.stroke();
}
if (entry.pilotGround && visible) {
const pilot = screen(entry.pilotGround);
if (pilot) {
context.beginPath();
context.strokeStyle = '#55d5ef';
context.lineWidth = 1.5;
context.setLineDash([5, 5]);
context.moveTo(...pilot);
context.lineTo(...position);
context.stroke();
}
}
if (entry.height > 0 && visible) {
const ground = screen(entry.ground);
if (ground) {
context.beginPath();
context.setLineDash([4, 4]);
context.strokeStyle = '#a6e5ff';
context.lineWidth = 1.5;
context.moveTo(...ground);
context.lineTo(...position);
context.stroke();
}
}
element.button.setAttribute('aria-expanded', String(selected === id));
if (selected === id && visible) popupAnchor = [position, entry.popup];
}
popup.hidden = !popupAnchor;
if (popupAnchor) {
const [position, content] = popupAnchor;
if (popupBody.dataset.content !== content) {
popupBody.innerHTML = content;
popupBody.dataset.content = content;
}
const half = Math.min(popup.offsetWidth / 2, width / 2);
popup.style.left = Math.max(half, Math.min(width - half, position[0])) + 'px';
popup.style.top = position[1] + 'px';
popup.classList.toggle('below', position[1] < popup.offsetHeight + 30);
}
}
function applyStyle() {
map.getSource('base')?.setTiles([config.tiles]);
if (config.labels) map.getSource('labels')?.setTiles([config.labels]);
if (map.getLayer('labels')) map.setLayoutProperty('labels','visibility', config.labels ? 'visible' : 'none');
map.getSource('fences')?.setData({type:COLLECTION, features:fences});
}
map.on('style.load', () => {
applyStyle();
map.addLayer({id:'rid-airspace', type:'custom', renderingMode:'3d', render(_gl, args) {
paint(args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix);
}});
});
map.on('moveend', () => {
if (active && !updatingCamera) onCamera(map.getCenter(), map.getZoom() + 1);
});
map.on('click', event => {
closePopup();
if (!map.getLayer('fences')) return;
const [zone] = map.queryRenderedFeatures(event.point, {layers:['fences']});
if (zone) {
zonePopup.setLngLat(event.lngLat)
.setDOMContent(options.createZonePopupContent(zone.properties))
.addTo(map);
}
});
map.on('webglcontextlost', onError);
function resize() {
if (!active) return;
updatingCamera = true;
try {
map.resize();
} finally {
updatingCamera = false;
}
}
return {
getCamera: () => ({pitch:map.getPitch(), bearing:map.getBearing()}),
showTarget,
setActive(value) {
active = value;
if (!active) zonePopup.remove();
resize();
},
resize,
destroy: () => map.remove(),
setView(center, zoom) {
const current = map.getCenter();
if (Math.abs(current.lng - center[0]) < 1e-8 && Math.abs(current.lat - center[1]) < 1e-8
&& Math.abs(map.getZoom() - zoom + 1) < 1e-6) return;
updatingCamera = true;
try { map.jumpTo({center, zoom:zoom - 1}); } finally { updatingCamera = false; }
},
setBasemap(value) {
if (config.tiles === value.tiles && config.labels === value.labels) return;
if (config.tiles !== value.tiles) trailPoints = new WeakMap();
config = value;
applyStyle();
},
setFences(value) {
fences = value;
zonePopup.remove();
map.getSource('fences')?.setData({type:COLLECTION, features:fences});
},
updateEntries,
metrics() {
const screen = coordinate => projection && project(projection.matrix, coordinate, projection.width, projection.height);
return {camera:{pitch:map.getPitch(), bearing:map.getBearing(), zoom:map.getZoom()+1}, size:[lines.width,lines.height],
positions:[...entries.values()].map(entry => ({
id:entry.id, heading:entry.heading, height:entry.height, altitude:entry.air.toAltitude(),
air:screen(entry.air), ground:screen(entry.ground),
tail:entry.trail?.length ? screen(trailPoint(entry.trail.at(-1))) : null
}))};
}
};
}
+34
View File
@@ -0,0 +1,34 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>登录 - RID侦测平台</title>
<link rel="icon" href="/workbench/assets/rid-app.ico" type="image/x-icon">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<link rel="stylesheet" href="/workbench/platform.css">
<link rel="stylesheet" href="/workbench/integration.css">
</head>
<body class="loginPage loginCenterMountain">
<main class="centerLoginScene">
<div class="centerLoginBg" aria-hidden="true"></div>
<div class="centerLoginShade" aria-hidden="true"></div>
<header class="centerLoginHeader">
<div class="centerBrand">
<img class="centerBrandMark" src="/workbench/assets/bsrid_logo_icon_light.png" alt="" width="46" height="46">
<strong id="loginPlatformName">RID侦测平台</strong>
</div>
</header>
<form class="centerLoginPanel">
<div class="centerPanelHeading"><h1>平台登录</h1></div>
<label class="centerField"><span>用户名</span><input id="username" autocomplete="username" placeholder="请输入用户名" required></label>
<label class="centerField"><span>密码</span><input id="password" type="password" autocomplete="current-password" placeholder="请输入密码" required></label>
<button type="submit" class="centerLoginSubmit"><span>登录</span></button>
<div id="loginMsg" class="centerLoginMsg" role="alert"></div>
<div class="centerLoginState" id="loginStatusText" aria-live="polite">正在检查本地账号</div>
</form>
<footer class="centerLoginFooter">© 2026 <span id="loginFooterName">RID侦测平台</span></footer>
</main>
<script src="/workbench/login.js"></script>
</body>
</html>
+61
View File
@@ -0,0 +1,61 @@
(function () {
'use strict';
const status = document.getElementById('loginStatusText');
const form = document.querySelector('.centerLoginPanel');
const button = form.querySelector('button');
const buttonLabel = button.querySelector('span');
const message = document.getElementById('loginMsg');
const username = document.getElementById('username');
const password = document.getElementById('password');
let needsSetup = false;
button.disabled = true;
async function prepare() {
const response = await fetch('/api/auth/status', { cache: 'no-store' });
if (!response.ok) throw new Error('无法读取本地服务状态');
const account = await response.json();
if (account.authenticated) return location.replace('/workbench/platform.html');
needsSetup = !account.configured;
buttonLabel.textContent = needsSetup ? '创建管理员' : '登录';
password.autocomplete = needsSetup ? 'new-password' : 'current-password';
password.minLength = needsSetup ? 10 : 0;
status.textContent = needsSetup ? '首次运行,请设置管理员账号和至少 10 字符的密码' : '本地账号验证';
button.disabled = false;
}
form.addEventListener('submit', async event => {
event.preventDefault();
button.disabled = true;
message.textContent = '';
status.textContent = needsSetup ? '正在创建管理员' : '正在验证本地账号';
try {
const response = await fetch(`/api/auth/${needsSetup ? 'setup' : 'login'}`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username.value.trim(), password: password.value })
});
password.value = '';
const data = await response.json().catch(() => ({}));
if (!response.ok) {
if (response.status === 409) await prepare();
throw new Error(data.error || '本地账号验证失败');
}
status.textContent = '认证通过,正在进入平台';
location.replace('/workbench/platform.html');
} catch (error) {
message.textContent = error.message;
status.textContent = '请检查后重试';
button.disabled = false;
}
});
prepare().catch(error => { message.textContent = error.message; });
fetch('/api/workbench/branding', { cache: 'no-store' })
.then(response => response.ok ? response.json() : null)
.then(branding => {
if (!branding?.name) return;
document.getElementById('loginPlatformName').textContent = branding.name;
document.getElementById('loginFooterName').textContent = branding.name;
document.title = `登录 - ${branding.name}`;
})
.catch(() => {});
})();
+127
View File
@@ -0,0 +1,127 @@
(() => {
'use strict';
const nativeViews = Object.freeze({
register: 'register', archives: 'archives', drones: 'target-lists',
maps: 'maps', history: 'history', receivers: 'receivers'
});
const workbenchViews = new Map(Object.entries(nativeViews).map(([key, view]) => [view, key]));
const container = document.getElementById('moduleEmbed');
const content = document.getElementById('moduleBody');
const status = document.getElementById('moduleEmbedStatus');
const retry = document.getElementById('moduleEmbedRetry');
let frame;
let pendingView = 'home';
let pendingRecord;
let ready = false;
let timer;
function navigate(view) {
if (ready) frame.contentWindow.postMessage({
type: 'rid-embedded-navigate', view, record: view === 'history' ? pendingRecord : undefined,
mapOptions: view === 'history' ? {
basemap: document.getElementById('mapSourceSelect').value === 'tdt-vector' ? 'road' : 'imagery',
labels: document.getElementById('labelToggle').checked
} : undefined
}, location.origin);
}
function mount() {
frame = document.createElement('iframe');
frame.title = 'RID 业务模块';
frame.hidden = true;
frame.src = '/workbench/module.html';
container.append(frame);
}
function waiting() {
status.textContent = '正在打开业务模块…';
status.hidden = false;
retry.hidden = true;
clearTimeout(timer);
timer = setTimeout(async () => {
if (ready || container.hidden) return;
const account = await window.ridWorkbenchApi.request('/api/auth/status').catch(() => null);
if (ready || container.hidden) return;
if (account && !account.authenticated) return location.replace('/workbench/');
status.textContent = '业务模块加载失败,请重试。';
retry.hidden = false;
}, 10000);
}
function hide() {
pendingView = 'home';
pendingRecord = undefined;
container.hidden = true;
content.hidden = false;
clearTimeout(timer);
navigate(pendingView);
}
function show(name, record) {
if (!Object.hasOwn(nativeViews, name)) {
hide();
return false;
}
pendingView = nativeViews[name];
pendingRecord = name === 'history' && record ? {
flightKey: record.flightKey, targetId: record.targetId, timeMs: record.timeMs, endMs: record.endMs
} : undefined;
content.hidden = true;
container.hidden = false;
if (!frame) mount();
frame.title = document.getElementById('moduleTitle').textContent;
if (ready) navigate(pendingView);
else waiting();
return true;
}
retry.addEventListener('click', () => {
frame.remove();
ready = false;
mount();
frame.title = document.getElementById('moduleTitle').textContent;
waiting();
});
function returnToRecords() {
if (pendingView !== 'history' || !pendingRecord) return false;
const records = content.querySelector('[data-module="records"]');
if (!records) return false;
const key = pendingRecord.flightKey;
window.showModuleHeading('records');
hide();
records.onRecordsReturn?.();
records.querySelector('[data-action="record-play"][data-id="' + CSS.escape(key) + '"]')?.focus();
return true;
}
window.addEventListener('message', event => {
if (event.origin !== location.origin || !frame || event.source !== frame.contentWindow) return;
if (event.data?.type === 'rid-embedded-ready') {
ready = true;
clearTimeout(timer);
status.hidden = retry.hidden = true;
frame.hidden = false;
navigate(pendingView);
return;
}
if (!ready || container.hidden) return;
if (event.data?.type === 'rid-embedded-return-records' && pendingView === 'history' && pendingRecord) {
if (!returnToRecords()) window.openModule('records');
return;
}
if (event.data?.type !== 'rid-embedded-view') return;
const view = event.data.view;
if (view === 'home') {
window.closeModule();
} else if (workbenchViews.has(view)) {
pendingView = view;
window.showModuleHeading(workbenchViews.get(view));
frame.title = document.getElementById('moduleTitle').textContent;
}
});
window.ridModuleHost = Object.freeze({ show, hide, returnToRecords });
})();
+716
View File
@@ -0,0 +1,716 @@
(() => {
'use strict';
const { request, modelRules, resolveModel, roleLabel } = window.ridWorkbenchApi;
const workbench = '/api/workbench';
const receiverPath = '/api/receivers';
const userPath = '/api/auth/users';
const limit = 50;
const transportNames = { serial: 'USB 串口', udp: 'UDP 监听', 'tcp-listen': 'TCP 监听' };
const receiverFormat = format => !format || format === 'raw' ? 'rid-device-json' : format;
const stateNames = {
stopped: '已停用', 'serial-open': '串口已打开', 'udp-listening': 'UDP 监听中',
'tcp-listening': 'TCP 监听中', connecting: '正在连接', disconnected: '连接中断'
};
function receiverState(row) {
const status = row.status;
if (!row.config.enabled) return '已停用';
if (status.lastError) return status.lastError;
if (status.state === 'tcp-listening') {
if (!status.lastDataMs || Date.now() - status.lastDataMs > 15000) return '监听中 · 等待数据';
return '接收中';
}
return stateNames[status.state] || '待机';
}
function receiverTone(row) {
const { state, lastError, lastDataMs } = row.status;
if (!row.config.enabled) return 'neutral';
if (lastError || state === 'disconnected') return 'danger';
if (/^(serial-open|udp-listening|tcp-listening)$/.test(state) &&
lastDataMs && Date.now() - lastDataMs <= 15000) return 'ok';
return 'neutral';
}
function receiverSource(row) {
return row.status.lastPeerIp || (row.config.peerIp ? '未收到 · 已配置 ' + row.config.peerIp : '—');
}
const alertNames = Object.fromEntries(Object.entries(window.ridFlightStatus.types).map(([key,value])=>[key,value.label]));
const column = (label, key) => ({ label, key });
const cell = (label, render) => ({ label, render });
const time = value => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—';
const fixed = (value, digits) => Number.isFinite(value) ? value.toFixed(digits) : '—';
const editorField = (label, control) => `<label>${label}${control}</label>`;
const input = (name, value, props = '') =>
`<input name="${name}" value="${escAttr(value)}" ${props}>`;
const select = (name, entries, selected) => `<select name="${name}">${entries.map(([value, label]) =>
`<option value="${escAttr(value)}" ${selected === value ? 'selected' : ''}>${esc(label)}</option>`
).join('')}</select>`;
const enabled = (name, value, label) =>
`<label class="rid-check"><input type="checkbox" name="${name}" ${value ? 'checked' : ''}>${label}</label>`;
const button = (label, action, id, danger = false) =>
`<button type="button" class="smallBtn ${danger ? 'red' : ''}" data-action="${action}" data-id="${escAttr(id)}">${label}</button>`;
const editorFooter = label => `<div class="btnrow"><button type="submit">${label}</button><button type="button" data-action="cancel-edit">取消</button></div>`;
const toolbar = (left, right = '') => `<div class="rid-module-toolbar">${left}${right}</div>`;
const section = (title, body) => `<section class="configGroup"><h3>${title}</h3>${body}</section>`;
const live = root => root.isConnected && activeModuleName === root.dataset.module;
function feedback(root, message, error = false) {
const el = root.querySelector('.flightPlanDialog[open] .planDialogFeedback') || root.querySelector('.rid-module-feedback');
el.textContent = message;
el.hidden = !message;
el.classList.toggle('dangerText', error);
}
function run(root, control, operation) {
if (!live(root) || control.disabled) return;
control.disabled = true;
feedback(root, '');
Promise.resolve().then(operation).catch(error => {
if (live(root)) feedback(root, error.message || '操作失败,请重试', true);
}).finally(() => { control.disabled = false; });
}
function onForm(root, form, operation) {
form.addEventListener('submit', event => {
event.preventDefault();
run(root, event.submitter || form.querySelector('button[type="submit"]'),
() => operation(new FormData(form)));
});
}
function onAction(root, action, operation) {
for (const control of root.querySelectorAll(`[data-action="${action}"]`)) {
control.onclick = () => run(root, control, () => operation(control.dataset.id, control));
}
}
function editArea(root, body) {
const pane = root.querySelector('.rid-module-editor');
pane.innerHTML = body;
if (body) pane.querySelector('input,select')?.focus();
onAction(root, 'cancel-edit', () => editArea(root, ''));
return pane.querySelector('form');
}
function body(root, html) {
if (live(root)) root.querySelector('.rid-module-content').innerHTML = html;
}
function managedTable(root, label, columns, rows, empty, pageSize = 20) {
const offset = Math.min(root.pageOffset ?? 0, lastPageOffset(rows.length, pageSize));
root.pageOffset = offset;
return renderTable(columns, rows.slice(offset, offset + pageSize), empty)
+ renderPager(label, offset, rows.length, pageSize);
}
function bindManagedTable(root, reload) {
bindPager(root, async (offset, direction) => {
const previousOffset = root.pageOffset;
root.pageOffset = offset;
try {
await reload();
if (live(root)) {
(root.querySelector(`[data-page-direction="${direction}"]:enabled`) || root.querySelector('.rid-page-number'))?.focus();
}
} catch (error) {
root.pageOffset = previousOffset;
if (live(root)) feedback(root, error.message || '换页失败,请重试', true);
}
});
}
function dates(withKeyword, right = '') {
return `<form class="filterBar rid-period">
${withKeyword ? editorField('关键字', input('q', '', 'maxlength="80" placeholder="UAS ID / 上报机型 / BSSID / 接收器"')) : ''}
${editorField('开始时间', input('from', '', 'type="datetime-local" required'))}
${editorField('结束时间', input('to', '', 'type="datetime-local" required'))}
<button type="submit">查询</button>${right}
</form><div class="moduleResult" aria-live="polite"></div>`;
}
function dateForm(root, name) {
const form = root.querySelector('.rid-period');
const from = form.elements.from, to = form.elements.to;
from.id = `${name}From`;
to.id = `${name}To`;
setDefaultModuleDates(from.id, to.id);
return form;
}
function period(values, offset = 0) {
const fromMs = new Date(values.get('from')).getTime();
const toMs = new Date(values.get('to')).getTime() + 59999;
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || fromMs > toMs) {
throw new Error('请选择有效的开始和结束时间');
}
return new URLSearchParams({ fromMs, toMs, offset, limit, q: (values.get('q') || '').trim() });
}
async function records(root) {
body(root, dates(true));
const form = dateForm(root, 'record');
const result = root.querySelector('.moduleResult');
let values = new FormData(form);
let generation = 0;
let refreshTimer;
const query = (offset, activeRows) => {
const params = period(values, offset);
if (activeRows) {
params.delete('q');
params.set('flightKeys', activeRows.map(row => row.flightKey).join(','));
}
return request(`${workbench}/observations?${params}`);
};
const details = rules => [
['UAS ID', row => row.targetId],
['机型', row => resolveModel(row.targetId, row.model, rules) || '—'],
['飞行状态', row => (row.flightStatuses?.length ? row.flightStatuses : ['unknown']).map(code=>window.ridFlightStatus.meta(code).label).join(' · ')],
['开始时间', row => time(row.timeMs)],
['结束时间', row => row.endMs == null ? '接收中' : time(row.endMs)],
['BSSID', row => row.bssid || '—'],
['RSSI / dBm', row => fixed(row.rssi, 1)],
['高度 / m', row => fixed(row.altitudeM, 1)],
['速度 / m/s', row => fixed(row.speedMps, 1)],
['坐标', row => Number.isFinite(row.latitude) && Number.isFinite(row.longitude)
? fixed(row.latitude, 6) + ', ' + fixed(row.longitude, 6) : '—'],
['接收器', row => row.receiverId || '—']
];
function refreshActiveRows(current, activeRows, columns) {
clearTimeout(refreshTimer);
if (!activeRows.size) return;
refreshTimer = setTimeout(async () => {
if (!live(root) || current !== generation) return;
try {
const data = await query(0, [...activeRows.values()].map(entry => entry.row));
if (!live(root) || current !== generation) return;
for (const row of data.entries) {
const entry = activeRows.get(row.flightKey);
if (!entry) continue;
columns.forEach(([label, read], index) => {
if (label === '飞行状态') {
entry.cells[index].innerHTML = window.ridFlightStatus.tags(row.flightStatuses);
return;
}
const value = read(row);
if (entry.cells[index].textContent !== value) entry.cells[index].textContent = value;
});
Object.assign(entry.row, row);
if (row.endMs != null) activeRows.delete(row.flightKey);
}
} catch {
if (!live(root) || current !== generation) return;
}
refreshActiveRows(current, activeRows, columns);
}, 5000);
}
async function load(offset, focusAction) {
clearTimeout(refreshTimer);
const current = ++generation;
result.innerHTML = '<div class="moduleEmpty">正在查询接收记录…</div>';
try {
const [page, rules] = await Promise.all([query(offset), modelRules().catch(() => [])]);
if (!live(root) || current !== generation) return;
const rows = page.entries;
const columns = details(rules);
const cols = [...columns.map(([label, read]) => cell(label, row => label==='飞行状态'?window.ridFlightStatus.tags(row.flightStatuses):esc(read(row)))),
cell('操作', row => button('回放轨迹', 'record-play', row.flightKey))];
const lastOffset = lastPageOffset(page.total, limit);
if (offset > lastOffset) return load(lastOffset, focusAction);
result.innerHTML = `<div class="resultCount">共 ${page.total} 条记录</div>
${renderTable(cols, rows, '该时段无接收记录')}
${renderPager('记录分页', offset, page.total, limit)}`;
const activeRows = new Map();
const recordsByKey = new Map();
const visibleRows = result.querySelectorAll('tbody tr');
rows.forEach((row, index) => {
const tr = visibleRows[index];
tr.querySelector('[data-action="record-play"]').setAttribute('aria-label', row.targetId + ' 的轨迹回放');
recordsByKey.set(row.flightKey, row);
if (row.endMs == null) activeRows.set(row.flightKey, {row, cells: tr.cells});
});
onAction(root, 'record-play', key => openModule('history', recordsByKey.get(key)));
root.onRecordsReturn = () => refreshActiveRows(current, activeRows, columns);
refreshActiveRows(current, activeRows, columns);
bindPager(result, (next, direction) => load(next, direction).catch(error => {
if (live(root)) feedback(root, error.message || '换页失败,请重试', true);
}), focusAction);
} catch (error) {
if (live(root) && current === generation) result.innerHTML = '<div class="moduleEmpty">查询未完成,可调整条件后重试。</div>';
throw error;
}
}
onForm(root, form, async data => { values = data; await load(0); });
await load(0);
}
async function rankings(root) {
body(root, dates(false));
const form = dateForm(root, 'rank');
const result = root.querySelector('.moduleResult');
const today = new Date();
today.setHours(0, 0, 0, 0);
const trackStats = request('/api/history/summary?fromMs=' + today.getTime()).catch(() => null);
async function load(values) {
const params = period(values);
result.innerHTML = '<div class="moduleEmpty">正在统计…</div>';
try {
const [targets, models, receivers, alarms, devices, tracks, flightStates] = await Promise.all([
...['target', 'model', 'receiver'].map(dim => request(`${workbench}/rankings?${params}&dimension=${dim}`)),
request(`/api/monitoring/rankings?${params}`),
request(receiverPath),
trackStats,
request(`${workbench}/rankings?${params}&dimension=flight_status`)
]);
if (!live(root)) return;
const names = new Map(devices.receivers.map(item => [item.id, item.name]));
const rows = (data, labels) => data.entries.map((row, index) => ({
...row, rank: index + 1, name: labels?.get(row.name) || row.name
}));
const groups = [
['目标排行', rows(targets)], ['上报机型排行', rows(models)],
['设备 / 链路贡献', rows(receivers, names)],
['告警类型', rows(alarms, new Map(Object.entries(alertNames))), '次数'],
['飞行状态(本次最高告警级别)', rows(flightStates, new Map(Object.entries(alertNames))), '飞行次数']
];
result.innerHTML = `${tracks ? `<p class="resultCount">今日轨迹点 ${Number(tracks.since).toLocaleString('zh-CN')} · 累计 ${Number(tracks.total).toLocaleString('zh-CN')}</p>` : ''}
<div class="moduleSplit">${groups.map(([label]) => `<section><h3>${label}</h3><div></div></section>`).join('')}</div>`;
result.querySelectorAll('.moduleSplit section > div').forEach((table, index) => {
const [label, ranking, countLabel = '接收记录'] = groups[index];
const pageSize = 10;
const cols = [column('名次', 'rank'), column('名称', 'name'), column(countLabel, 'count')];
function display(offset, direction) {
table.innerHTML = renderTable(cols, ranking.slice(offset, offset + pageSize), '该时段无统计数据')
+ (ranking.length > pageSize ? renderPager(label + '分页', offset, ranking.length, pageSize) : '');
bindPager(table, display, direction);
}
display(0);
});
} catch (error) {
if (live(root)) result.innerHTML = '<div class="moduleEmpty">统计未完成,可重新查询。</div>';
throw error;
}
}
onForm(root, form, load);
await load(new FormData(form));
}
async function settings(root, admin) {
const current = await request(`${workbench}/settings`);
if (!live(root)) return;
body(root, section('平台信息与告警', `<form class="rid-admin-form rid-config-form">
<fieldset ${admin ? '' : 'disabled'}>
${editorField('平台名称', input('name', current.name, 'required maxlength="60"'))}
<div class="rid-config-options">
${enabled('sound', current.sound, '声音报警')}
${enabled('flash', current.flash, '告警闪屏')}
</div>
${editorField('告警闪屏时长(秒)', input('flashSeconds', current.flashSeconds ?? 10, 'type="number" min="1" max="60" step="1" required'))}
${admin ? '<button type="submit">保存平台设置</button>' : ''}
</fieldset>
</form>`));
if (!admin) return;
let savedSettings = current;
const configForm = root.querySelector('.rid-config-form');
onForm(root, configForm, async data => {
savedSettings = await request(`${workbench}/settings`, 'PUT', {
...savedSettings, name: data.get('name'),
sound: data.has('sound'), flash: data.has('flash'), flashSeconds: Number(data.get('flashSeconds'))
});
if (!live(root)) return;
configForm.elements.name.value = savedSettings.name;
applyPlatformSettings(savedSettings);
feedback(root, '平台设置已保存。');
});
}
const deviceListKey = data => JSON.stringify([data.receivers.map(row => row.id), data.discovery]);
const deviceEditorOpen = root => root.querySelector('.rid-module-editor form, button[data-action]:disabled');
function refreshReceiverStatus(root, rows) {
const byId = new Map(rows.map(row => [row.id, row]));
for (const source of root.querySelectorAll('[data-rx-source]')) {
const row = byId.get(source.dataset.rxSource);
const tableRow = source.closest('tr');
if (!row || !tableRow) continue;
const status = tableRow.querySelector('[data-rx-status]');
for (const [cell, value] of [[source, receiverSource(row)], [status, receiverState(row)],
[tableRow.querySelector('[data-rx-time]'), time(row.status.lastDataMs)]]) {
if (cell.textContent !== value) cell.textContent = value;
}
status.className = 'stateTag ' + receiverTone(row);
}
}
function watchDevices(root, admin) {
async function poll() {
if (!live(root)) return;
try {
if (document.hidden || deviceEditorOpen(root)) return;
const data = await request(receiverPath);
if (live(root) && !deviceEditorOpen(root)) {
if (deviceListKey(data) !== root.receiverListKey) await devices(root, admin, '', data);
else refreshReceiverStatus(root, data.receivers);
}
} catch (_) {
// The next poll or a manual refresh can recover from a temporary failure.
} finally {
if (live(root)) setTimeout(poll, 2000);
}
}
setTimeout(poll, 2000);
}
async function devices(root, admin, notice = '', snapshot) {
const [data, ports] = await Promise.all([
snapshot || request(receiverPath), admin ? request('/api/receiver/ports') : { ports: [] }
]);
if (!live(root) || (snapshot && deviceEditorOpen(root))) return;
const focused = snapshot && root.contains(document.activeElement) ? document.activeElement.dataset : null;
root.receiverListKey = deviceListKey(data);
const discovery = (data.discovery || []).map(entry => {
const state = entry.error || (entry.listening ? '监听中 · 等待新设备' : '正在启动');
return toolbar('<span>TCP 自动登记入口 <strong>' + esc(entry.endpoint) + '</strong> · ' +
esc(state) + '</span>', admin ? button('取消保留', 'disable-discovery', entry.endpoint) : '');
}).join('');
body(root, toolbar(admin ? button('新增接收器', 'add-rx', '') : '',
button('刷新', 'refresh-rx', '') + '<span class="muted">TCP 监听开启后,有效报文会自动登记新设备。</span>') +
discovery + '<div class="rid-module-editor"></div>' +
`<div class="resultCount">共 ${data.receivers.length} 台 / 32 台</div>` +
managedTable(root, '接收器列表分页', [
cell('设备名称', r => esc(r.name) + (r.networkDiscovered ? ' <small class="muted">自动登记</small>' : '')),
cell('标识', r => esc(r.hardwareId || r.id)),
cell('接入方式', r => esc(transportNames[r.config.transport])),
cell('接收端点', r => esc(r.config.transport === 'serial' ? r.config.serialPort :
`${r.config.bindIp}:${r.config.port}`)),
cell('来源 IP', r => '<span data-rx-source="' + escAttr(r.id) + '">' + esc(receiverSource(r)) + '</span>'),
cell('安装位置', r => esc(r.location ?? r.devicePlace)),
column('备注', 'note'),
cell('状态', r => '<span data-rx-status class="stateTag ' + receiverTone(r) + '">' + esc(receiverState(r)) + '</span>'),
cell('最后接收', r => '<span data-rx-time>' + esc(time(r.status.lastDataMs)) + '</span>'),
...(admin ? [cell('操作', r => button('编辑', 'edit-rx', r.id) + button(r.config.enabled ? '停用' : '启用', 'toggle-rx', r.id) +
button('删除', 'delete-rx', r.id, true))] : [])
], data.receivers, '暂无接收器', 12));
bindManagedTable(root, () => devices(root, admin));
if (focused?.action) {
const action = CSS.escape(focused.action);
const id = CSS.escape(focused.id ?? '');
root.querySelector(`[data-action="${action}"][data-id="${id}"]`)?.focus({preventScroll:true});
}
feedback(root, data.error || notice, Boolean(data.error));
onAction(root, 'refresh-rx', () => devices(root, admin));
onAction(root, 'disable-discovery', async endpoint => {
if (!confirm('取消保留 ' + endpoint + '?该端点没有启用的接收器时会停止监听。')) return;
await request('/api/receiver/discovery', 'PUT', { endpoint, enabled: false });
if (live(root)) await devices(root, admin, '已取消保留此 TCP 入口。');
});
const edit = item => {
const c = item?.config || { transport: 'serial', format: 'rid-device-json', uidIdentity: 'source-scoped', baudRate: 115200, bindIp: '127.0.0.1', port: 8788 };
const portList = `<datalist id="rid-board-ports">${ports.ports.map(port => `<option value="${escAttr(port)}"></option>`).join('')}</datalist>`;
const form = editArea(root, section(item ? '编辑接收器' : '新增接收器', `<form class="rid-admin-form">
${editorField('设备名称', input('name', item?.name, 'required maxlength="120"'))}
${editorField('接入方式', select('transport', Object.entries(transportNames), c.transport))}
<div data-rx-group="serial" class="rid-admin-fields">
${editorField('COM 串口', input('serialPort', c.serialPort, 'list="rid-board-ports" maxlength="12"'))}
${editorField('波特率', input('baudRate', c.baudRate, 'type="number" min="1200" max="4000000" required'))}
</div>
<div data-rx-group="network" class="rid-admin-fields">
${editorField('监听 IP(本机网卡地址)', input('bindIp', c.bindIp, 'required maxlength="45"'))}
${editorField('监听端口', input('port', c.port, 'type="number" min="1" max="65535" required'))}
</div>
<div data-rx-group="peer">
${editorField('允许来源 IP(设备地址,可留空)', input('peerIp', c.peerIp, 'maxlength="45" placeholder="例如 192.168.1.200"'))}
</div>
<div data-rx-group="identity">
${editorField('UID 归并', select('uidIdentity', [['source-scoped', '按接收源区分'], ['global-device', '按设备 UID 合并']], c.uidIdentity))}
</div>
${editorField('安装位置', input('location', item?.location ?? item?.devicePlace, 'maxlength="160"'))}
${editorField('备注', input('note', item?.note, 'maxlength="160"'))}
${enabled('enabled', c.enabled, '立即启用')}
${portList}${editorFooter('保存设备')}
</form>`));
const toggleFields = () => {
const transport = form.elements.transport.value;
const serial = transport === 'serial';
const uid = c.format === 'uid-json';
for (const [group, visible] of [['serial', serial], ['network', !serial], ['peer', transport === 'tcp-listen'], ['identity', uid]]) {
const scope = form.querySelector(`[data-rx-group="${group}"]`);
scope.hidden = !visible;
scope.querySelectorAll('input,select').forEach(control => { control.disabled = !visible; });
}
};
form.elements.transport.onchange = toggleFields;
toggleFields();
onForm(root, form, async values => {
const config = { ...c, enabled: values.has('enabled'), transport: values.get('transport'), format: receiverFormat(c.format) };
if (values.has('serialPort')) {
config.serialPort = values.get('serialPort').trim().toUpperCase();
config.baudRate = Number(values.get('baudRate'));
} else {
config.bindIp = values.get('bindIp').trim();
config.port = Number(values.get('port'));
}
config.peerIp = values.get('peerIp')?.trim() || null;
if (values.has('uidIdentity')) config.uidIdentity = values.get('uidIdentity');
await request(item ? `${receiverPath}/${encodeURIComponent(item.id)}` : receiverPath, item ? 'PUT' : 'POST', {
name: values.get('name').trim(), config, location: values.get('location'), note: values.get('note')
});
if (live(root)) await devices(root, admin, '设备已保存。');
});
};
const find = id => data.receivers.find(item => item.id === id);
onAction(root, 'add-rx', () => edit(null));
onAction(root, 'edit-rx', id => edit(find(id)));
onAction(root, 'toggle-rx', async id => {
const path = `${receiverPath}/${encodeURIComponent(id)}`;
const item = await request(path);
const config = { ...item.config, enabled: !item.config.enabled };
if (config.enabled) config.format = receiverFormat(config.format);
await request(path, 'PUT', { name: item.name, config });
if (live(root)) await devices(root, admin, item.config.enabled ? '接收器已停用。' : '已保存启用设置,实际接收状态见下方。');
});
onAction(root, 'delete-rx', async id => {
const receiver = find(id);
const consequence = receiver.status.state === 'tcp-listening' && receiver.config.format === 'rid-device-json'
? ' TCP 入口会继续接收,设备重新推送有效数据时会再次登记。' : '';
if (!confirm('删除接收器「' + receiver.name + '」?已保存的接收记录会保留。' + consequence)) return;
await request(`${receiverPath}/${encodeURIComponent(id)}`, 'DELETE');
if (live(root)) await devices(root, admin, '设备已删除。');
});
}
const modelFields = [['serial', 'SN 前缀'], ['target', 'UAS ID'], ['model', '上报机型']];
const modelFieldNames = Object.fromEntries(modelFields);
async function models(root, admin, notice = '') {
const entries = await modelRules(true);
if (!live(root)) return;
body(root, toolbar(admin ? button('新增型号规则', 'add-model', '') : '',
'<span>SN 从首位匹配,忽略大小写。多个前缀命中时取最长的一条。</span>') +
'<div class="rid-module-editor"></div>' +
'<div class="resultCount">共 ' + entries.length + ' 条规则</div>' +
managedTable(root, '型号库分页', [
cell('匹配字段', r => esc(modelFieldNames[r.field] || r.field)),
column('关键字', 'pattern'), column('厂商', 'vendor'), column('机型', 'model'), column('备注', 'note'),
cell('状态', r => r.enabled ? '<span class="stateTag ok">已启用</span>' : '<span class="stateTag neutral">已停用</span>'),
...(admin ? [cell('操作', r => button('编辑', 'edit-model', r.id) + button('删除', 'delete-model', r.id, true))] : [])
], entries, '暂无本地型号规则'));
bindManagedTable(root, () => models(root, admin));
feedback(root, notice);
const edit = item => {
const form = editArea(root, section(item ? '编辑型号规则' : '新增型号规则', `<form class="rid-admin-form">
${editorField('匹配字段', select('field', modelFields, item?.field || 'serial'))}
${editorField('前缀 / 关键字', input('pattern', item?.pattern, 'required maxlength="80"'))}
${editorField('厂商', input('vendor', item?.vendor, 'maxlength="60"'))}
${editorField('显示机型', input('model', item?.model, 'required maxlength="80"'))}
${editorField('备注', input('note', item?.note, 'maxlength="200"'))}
${enabled('enabled', item?.enabled ?? true, '启用规则')}${editorFooter('保存规则')}
</form>`));
onForm(root, form, async values => {
const data = Object.fromEntries(values);
data.enabled = values.has('enabled');
await request(`${workbench}/models${item ? '/' + item.id : ''}`, item ? 'PUT' : 'POST', data);
if (live(root)) await models(root, admin, '型号规则已保存。');
});
};
onAction(root, 'add-model', () => edit(null));
onAction(root, 'edit-model', id => edit(entries.find(item => item.id === Number(id))));
onAction(root, 'delete-model', async id => {
if (!confirm('删除这条型号规则?')) return;
await request(`${workbench}/models/${id}`, 'DELETE');
if (live(root)) await models(root, admin, '型号规则已删除。');
});
}
async function users(root, admin, notice = '') {
if (!admin) {
body(root, '<div class="moduleEmpty">仅管理员可管理用户。</div>');
return;
}
const { entries } = await request(userPath);
if (!live(root)) return;
body(root, toolbar(button('新增用户', 'add-user', '')) +
'<div class="rid-module-editor"></div>' +
`<div class="resultCount">共 ${entries.length} 个账号</div>` +
managedTable(root, '用户管理分页', [
column('用户名', 'username'), cell('角色', r => esc(roleLabel(r.role))),
cell('状态', r => r.enabled ? '启用' : '停用'),
cell('操作', r => r.id === 0 ? '初始管理员' : button('编辑', 'edit-user', r.id) + button('删除', 'delete-user', r.id, true))
], entries));
bindManagedTable(root, () => users(root, admin));
feedback(root, notice);
const edit = item => {
const form = editArea(root, section(item ? '编辑用户' : '新增用户', `<form class="rid-admin-form">
${editorField('用户名', input('username', item?.username, item ? 'readonly' : 'required maxlength="40" autocomplete="off"'))}
${editorField(item ? '新密码(留空保留原密码)' : '密码', input('password', '', `type="password" autocomplete="new-password" minlength="10" maxlength="256" ${item ? '' : 'required'}`))}
${editorField('角色', select('role', [['viewer', '只读用户'], ['operator', '操作员']], item?.role))}
${item ? enabled('enabled', item.enabled, '启用账号') : ''}
${editorFooter('保存用户')}
</form><p class="fusionNote">操作员可登记设备、维护名单和防控区、处置告警。只读用户可查看业务页面。</p>`));
onForm(root, form, async values => {
const password = values.get('password');
const role = values.get('role');
if (item) {
await request(`${userPath}/${item.id}`, 'PUT', { password: password || null, role, enabled: values.has('enabled') });
} else {
await request(userPath, 'POST', { username: values.get('username'), password, role });
}
if (live(root)) await users(root, admin, '用户已保存。');
});
};
onAction(root, 'add-user', () => edit(null));
onAction(root, 'edit-user', id => edit(entries.find(item => item.id === Number(id))));
onAction(root, 'delete-user', async id => {
if (!confirm('删除此用户并退出其会话?')) return;
await request(`${userPath}/${id}`, 'DELETE');
if (live(root)) await users(root, admin, '用户已删除。');
});
}
async function flightPlans(root, admin, seed) {
const account = await request('/api/auth/status');
const editable = ['admin','operator'].includes(account.role);
const [snapshot, archive] = await Promise.all([request('/api/flight-plans'),request('/api/records')]);
if (!live(root)) return;
let entries = snapshot.entries;
const records = new Map(archive.records.map(r=>[r.id,r]));
const names = p => records.get(p.recordId) || {};
let keyword='', statusFilter='';
const state = p => !p.enabled ? ['撤销','muted','cancelled'] : p.endMs<=Date.now() ? ['已过期','muted','expired']
: p.approval==='rejected' ? ['已驳回','danger','rejected'] : p.approval!=='approved' ? ['待审批','warning','pending']
: p.startMs>Date.now() ? ['已批准 · 未开始','white','approved'] : ['已批准 · 生效中','ok','active'];
body(root, toolbar(`${editable?button('新增飞行报备','new-plan',''):''}${button('刷新','refresh-plans','')}<input class="planSearch" aria-label="搜索飞行报备" placeholder="搜索 SN、机型或报备名称"><label>状态 ${select('plan-filter',[['','全部'],['pending','待审批'],['approved','已批准 · 未开始'],['active','生效中'],['rejected','已驳回'],['expired','已过期'],['cancelled','已撤销']],'')}</label>`)
+'<div class="rid-module-editor"></div><div class="planResults"></div>');
const result=root.querySelector('.planResults');
function geometryText(g) {return g.type==='circle' ? `圆形 · 半径 ${g.radius_m} m` : `多边形 · ${g.vertices.length} 个顶点`;}
function render() {
const rows=entries.filter(p=>(!statusFilter||state(p)[2]===statusFilter)&&[p.name,names(p).serialNo,names(p).modelName].join(' ').toLowerCase().includes(keyword))
.sort((a,b)=>Number(state(b)[2]==='pending')-Number(state(a)[2]==='pending')||b.startMs-a.startMs);
result.innerHTML=managedTable(root,'飞行报备分页',[
cell('飞机',p=>`<strong>${esc(names(p).modelName||'未填写机型')}</strong><br><code>${esc(names(p).serialNo||'档案已移除')}</code>`),
column('报备名称','name'),cell('飞行时段',p=>`${esc(time(p.startMs))}<br>${esc(time(p.endMs))}`),
cell('允许区域',p=>esc(geometryText(p.geometry))),
cell('状态',p=>{const [label,tone]=state(p);return `<span class="flightTag ${tone}">${label}</span>`;}),
cell('审批',p=>`${esc(p.reviewedBy||'—')}${p.reviewNote?'<br>'+esc(p.reviewNote):''}`),
cell('操作',p=>button('详情','detail-plan',p.id)+(editable?button('编辑','edit-plan',p.id):'')
+(admin&&state(p)[2]==='pending'?button('审批','review-plan',p.id):'')
+(editable&&p.enabled?button('撤销','cancel-plan',p.id,true):''))
],rows,'暂无匹配的飞行报备');
bindManagedTable(root,render);
onAction(root,'detail-plan',id=>details(entries.find(p=>p.id===id)));
onAction(root,'edit-plan',id=>edit(entries.find(p=>p.id===id)));
onAction(root,'review-plan',id=>review(entries.find(p=>p.id===id)));
onAction(root,'cancel-plan',async id=>{
if (!confirm('撤销后该报备将不再允许飞行,确认撤销?')) return;
const plan=entries.find(p=>p.id===id);
await request('/api/flight-plans/'+encodeURIComponent(id),'PUT',{...plan,enabled:false});await reload();
});
}
async function reload(){entries=(await request('/api/flight-plans')).entries;if(live(root)){editArea(root,'');render();}}
function details(p){
editArea(root,section('报备详情',`<dl class="planDetails"><dt>飞机</dt><dd>${esc(names(p).modelName)} · ${esc(names(p).serialNo)}</dd><dt>时间</dt><dd>${esc(time(p.startMs))} — ${esc(time(p.endMs))}</dd><dt>区域(经度,纬度)</dt><dd><pre>${esc((p.geometry.type==='circle'?[p.geometry.center]:p.geometry.vertices).map(v=>v.join(', ')).join('\n'))}</pre>${esc(geometryText(p.geometry))}</dd><dt>备注</dt><dd>${esc(p.note||'—')}</dd><dt>审批</dt><dd>${esc(state(p)[0])} · ${esc(p.reviewedBy||'—')} · ${esc(time(p.reviewedAtMs))}<br>${esc(p.reviewNote)}</dd></dl><button type="button" data-action="cancel-edit">关闭</button>`));
}
function review(p){
const form=editArea(root,`<form class="configGroup planReviewForm"><h3>审批 ${esc(p.name)}</h3><p>${esc(names(p).serialNo)} · ${esc(time(p.startMs))} 至 ${esc(time(p.endMs))}</p><p>${esc(geometryText(p.geometry))}</p><pre>${esc((p.geometry.type==='circle'?[p.geometry.center]:p.geometry.vertices).map(v=>v.join(', ')).join('\n'))}</pre>
${editorField('审批结果',select('decision',[['approve','批准'],['reject','驳回']],'approve'))}
${editorField('审批意见', '<textarea name="note" maxlength="500" rows="2" placeholder="驳回时必填"></textarea>')}${editorFooter('提交审批结果')}</form>`);
onForm(root,form,async data=>{
await request('/api/flight-plans/'+encodeURIComponent(p.id)+'/approval','PUT',{approved:data.get('decision')==='approve',expectedRevision:p.revision,note:data.get('note')});
await reload();feedback(root,'审批结果已保存。');
});
}
function planEditor(html) {
editArea(root,'');
root.querySelector('.flightPlanDialog')?.remove();
const trigger=document.activeElement;
const modal=document.createElement('dialog');
modal.className='flightPlanDialog';
modal.setAttribute('aria-labelledby','flight-plan-dialog-title');
modal.innerHTML=html;
const form=modal.querySelector('form');
const heading=form.querySelector('h3');
heading.id='flight-plan-dialog-title';
const closeButton=document.createElement('button');
closeButton.type='button';closeButton.className='planDialogClose';
closeButton.setAttribute('aria-label','关闭飞行报备弹窗');closeButton.textContent='×';
form.querySelector('.planFormHeader').append(closeButton);
const notice=document.createElement('div');
notice.className='rid-module-feedback planDialogFeedback';
notice.setAttribute('role','alert');notice.hidden=true;
form.querySelector('.planFormHeader').after(notice);
const close=()=>{
if(form.querySelector('button[type="submit"]').disabled) return;
modal.close();modal.remove();
if(trigger?.isConnected) trigger.focus();
else root.querySelector('[data-action="new-plan"]')?.focus();
};
closeButton.onclick=close;
form.querySelector('[data-action="cancel-edit"]').onclick=close;
modal.addEventListener('cancel',event=>{event.preventDefault();close();});
root.append(modal);modal.showModal();
form.querySelector('select,input')?.focus();
return form;
}
function edit(p, recordId) {
if (!editable) return;
if (!records.size) {feedback(root,'请先在设备登记中登记飞机。',true);return;}
const g=p?.geometry||{type:'circle',center:[],radius_m:500};
const form=planEditor(`<form class="configGroup flightPlanForm"><header class="planFormHeader"><h3>${p?'修改飞行报备':'新增飞行报备'}</h3><p class="muted">提交后需管理员审批;修改已批准报备后需要重新审批。坐标使用 WGS84。</p></header><div class="planEditorColumns"><section class="planFieldGroup"><h4>飞行信息</h4><div class="planFormGrid">
${editorField('登记飞机',select('recordId',[['','请选择登记飞机'],...archive.records.map(r=>[r.id,`${r.serialNo} · ${r.modelName||'未填写机型'}`])],p?.recordId||recordId||''))}
${editorField('报备名称',input('name',p?.name||'','required maxlength="80"'))}
${editorField('开始时间',input('start',p?toDatetimeLocalValue(new Date(p.startMs)):toDatetimeLocalValue(new Date()),'type="datetime-local" required'))}
${editorField('结束时间',input('end',p?toDatetimeLocalValue(new Date(p.endMs)):toDatetimeLocalValue(new Date(Date.now()+3600000)),'type="datetime-local" required'))}
</div>${editorField('备注','<textarea name="note" rows="3" maxlength="500" placeholder="选填飞行用途或补充说明">'+esc(p?.note||'')+'</textarea>')}</section><section class="planFieldGroup"><h4>允许飞行区域</h4><div class="planFormGrid">
${editorField('区域形状',select('shape',[['circle','圆形'],['polygon','多边形']],g.type))}
${editorField('圆形半径(米)',input('radius',g.radius_m||500,'type="number" min="1" max="1000000" step="any"'))}
</div>${editorField('允许飞行区域坐标(经度,纬度)',`<textarea name="coordinates" rows="4" required spellcheck="false" placeholder="118.576700, 31.954800">${esc((g.type==='circle'?(g.center.length?[g.center]:[]):g.vertices).map(v=>v.join(', ')).join('\n'))}</textarea>`)}
<p class="muted">圆形填写一行中心坐标;多边形每行一个顶点,按边界顺序填写,至少三个点。</p>
</section></div>${editorFooter('提交报备')}</form>`);
const updateShape=()=>{form.elements.radius.disabled=form.elements.shape.value!=='circle';form.elements.radius.required=!form.elements.radius.disabled;};
form.elements.shape.onchange=updateShape;updateShape();form.elements.recordId.required=true;
onForm(root,form,async data=>{
const coords=String(data.get('coordinates')).trim().split(/\r?\n/).filter(line=>line.trim()).map(line=>line.trim().split(/[,,\s]+/).map(Number));
if (coords.some(v=>v.length!==2||!v.every(Number.isFinite)||Math.abs(v[0])>180||Math.abs(v[1])>90)) throw new Error('每行请填写有效的经度、纬度');
const circle=data.get('shape')==='circle';
if (circle?coords.length!==1:coords.length<3) throw new Error(circle?'圆形只需一行中心坐标':'多边形至少需要三个顶点');
const startMs=new Date(data.get('start')).getTime(),endMs=new Date(data.get('end')).getTime();
if (!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs>=endMs||endMs<=Date.now()) throw new Error('结束时间须晚于开始时间和当前时间');
const id=p?.id||'plan-'+crypto.randomUUID();
await request('/api/flight-plans/'+encodeURIComponent(id),'PUT',{id,recordId:data.get('recordId'),name:data.get('name'),startMs,endMs,
geometry:circle?{type:'circle',center:coords[0],radius_m:Number(data.get('radius'))}:{type:'polygon',vertices:coords},note:data.get('note'),enabled:true,revision:p?.revision||0});
const modal=form.closest('dialog');
modal.close();modal.remove();
root.querySelector('[data-action="new-plan"]')?.focus();
await reload();feedback(root,'报备已提交,等待管理员审批。');
});
}
root.querySelector('.planSearch').oninput=event=>{keyword=event.target.value.trim().toLowerCase();root.pageOffset=0;render();};
root.querySelector('[name="plan-filter"]').onchange=event=>{statusFilter=event.target.value;root.pageOffset=0;render();};
onAction(root,'new-plan',()=>edit());
onAction(root,'refresh-plans',()=>reload());
render();if(seed?.recordId) edit(null,seed.recordId);
}
const pages = {
records, rankings, devices, models, users,
"flight-plans": flightPlans,
configs: settings
};
window.ridWorkbenchModules = Object.freeze({
async open(name, seed) {
const root = document.createElement('div');
root.className = 'rid-module-page';
root.dataset.module = name;
root.innerHTML = '<div class="rid-module-feedback" role="status" hidden></div><div class="rid-module-content"><div class="moduleEmpty">正在加载数据…</div></div>';
document.getElementById('moduleBody').replaceChildren(root);
try {
const account = await request('/api/auth/status');
if (!live(root)) return;
if (!account.authenticated) return location.replace('/workbench/');
await pages[name](root, account.role === 'admin', seed);
if (name === 'devices' && live(root)) watchDevices(root, account.role === 'admin');
} catch (error) {
if (!live(root)) return;
const content = root.querySelector('.rid-module-content');
if (content.firstElementChild?.classList.contains('moduleEmpty')) content.replaceChildren();
feedback(root, error.message || '加载失败,请重试', true);
}
}
});
})();
+66
View File
@@ -0,0 +1,66 @@
.rid-pager,
.registry-workspace .rid-pager {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 14px;
margin: 10px 0 0;
padding: 9px 12px;
border: 1px solid #29465c;
border-radius: 7px;
background: #102438;
color: #c7ddeb;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.rid-pager .rid-pager-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 7px;
}
.rid-page-summary { color: #b3c9d9; }
.rid-page-summary > span { color: #9db8cc; }
.rid-page-number {
min-width: 5.5em;
color: #eff7fc;
text-align: center;
white-space: nowrap;
}
.rid-pager .rid-pager-actions button {
min-width: 58px;
min-height: 32px;
margin: 0;
padding: 4px 9px;
border: 1px solid #466982;
border-radius: 5px;
background: #18344c;
color: #ecf5ff;
font: inherit;
cursor: pointer;
}
.rid-pager .rid-pager-actions button:hover:not(:disabled) {
background: #254f70;
border-color: #76bbe7;
}
.rid-pager .rid-pager-actions button:disabled {
border-color: #2b465b;
background: #13283a;
color: #91aabf;
opacity: 1;
cursor: not-allowed;
}
.rid-pager :focus-visible {
outline: 2px solid #7ddcff;
outline-offset: 2px;
}
.rid-pager[aria-busy="true"] .rid-pager-actions button { cursor: wait; }
@media (max-width: 560px) {
.rid-pager, .registry-workspace .rid-pager { padding-inline: 9px; }
}
File diff suppressed because it is too large Load Diff
+223
View File
@@ -0,0 +1,223 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>RID侦测平台</title>
<link rel="icon" href="/workbench/assets/rid-app.ico" type="image/x-icon">
<link rel="stylesheet" href="/workbench/leaflet/leaflet.css">
<script src="/workbench/leaflet/leaflet.js"></script>
<link rel="stylesheet" href="/workbench/platform.css">
<link rel="stylesheet" href="/workbench/integration.css">
<link rel="stylesheet" href="/workbench/pagination.css">
<link rel="stylesheet" href="/workbench/drone-marker.css">
<link rel="stylesheet" href="/vendor/maplibre-gl.css">
<link rel="stylesheet" href="/workbench/live-map-3d.css">
</head>
<body>
<div id="app">
<div class="top">
<div class="brand">
<img class="logo brandLogo" src="/workbench/assets/bsrid_logo_icon_light.png" alt="" width="42" height="42">
<div class="overview-totals" aria-label="工作台总览">
<span>侦测设备 <strong id="kpiStations">0</strong></span>
<span>实时目标 <strong id="kpiTargets">0</strong></span>
<span>告警 <strong id="kpiAlerts">0</strong></span>
</div>
</div>
<div class="titleBox">
<div class="title" id="platformTitle">RID侦测平台</div>
</div>
<nav class="nav" id="workbenchNav" aria-label="工作台导航">
<button type="button" class="btn" data-rid-click="fitAll" aria-current="page">空域总览</button>
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="records">记录</button>
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="devices">设备管理</button>
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="register">档案</button>
<button type="button" class="btn" data-rid-click="openModule" data-rid-arg0="configs">设置</button>
<span class="nav-account" id="currentUserName">未登录</span>
<button type="button" class="btn" data-rid-click="logout">退出</button>
</nav>
</div>
<div class="main">
<div class="left" id="overviewLeft">
<div class="panel deviceListPanel">
<div class="p-title">侦测设备列表 <span id="stationSummary" class="panelCount">在线 0 · 离线 0</span></div>
<div id="stationList" class="list compactList">
<div class="muted">暂无侦测设备</div>
</div>
</div>
<div class="panel targetListPanel">
<div class="p-title">实时目标列表 <span id="targetSummary" class="panelCount">在线 0</span></div>
<div id="droneList" class="list">
<div class="muted">暂无目标</div>
</div>
</div>
</div>
<div class="mapWrap">
<div id="map" aria-label="平面实时地图"></div>
<div id="liveMap3D" aria-label="三维实时地图" hidden></div>
<div class="gridOverlay"></div>
<div class="mapDock">
<div class="legend" role="group" aria-label="地图图例">
<button type="button" class="mapLegendToggle" aria-controls="mapLegendContent" aria-expanded="false">
图例与显示选项 <span class="mapLegendArrow" aria-hidden="true"></span>
</button>
<div class="mapLegendContent" id="mapLegendContent">
<div class="legendStatus">
<span><i class="dot registeredDrone"></i><em>白名单</em></span>
<span><i class="dot registeredDrone"></i><em>已报备</em></span>
<span><i class="dot flightWarning"></i><em>未报备告警</em></span>
<span><i class="dot flightDanger"></i><em>未登记 / 防控区 / 黑名单告警</em></span>
<span><i class="dot offlineDot"></i><em>待核验</em></span>
</div>
<div class="legendSymbols">
<span title="轨迹"><i class="dot track"></i><em>轨迹</em></span>
<span title="防控区"><i class="dot zone"></i><em>防控区</em></span>
<span title="飞手/遥控器"><i class="dot pilotDot"></i><em>飞手</em></span>
</div>
<div class="mapDisplayOptions" role="group" aria-label="地图显示选项">
<label><input id="showFlightTrails" type="checkbox" checked>显示轨迹</label>
<label><input id="showModelLabels" type="checkbox" checked>显示型号</label>
<label><input id="showPilotMarkers" type="checkbox" checked>显示遥控器</label>
</div>
</div>
</div>
<div class="toolbar" role="group" aria-label="地图绘图工具">
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="polygon" title="绘制多边形防控区">
<div>⬠</div>多边形
</div>
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="rectangle" title="绘制矩形防控区">
<div>▭</div>矩形
</div>
<div class="tool" data-rid-click="startDrawZone" data-rid-arg0="circle" title="绘制圆形防控区">
<div>○</div>圆形
</div>
<div class="tool" data-rid-click="finishDrawZone" title="完成绘制/保存防控区">
<div>✓</div>完成
</div>
<div class="tool" data-rid-click="cancelDrawZone" title="取消绘制">
<div>×</div>取消
</div>
<div class="tool" data-rid-click="clearAllTrackLayers" title="清除实时轨迹">
<div>↺</div>清除实时轨迹
</div>
</div>
<div class="mapSourceBox" title="选择地图底图">
<button type="button" id="mapViewToggle" class="smallBtn" aria-pressed="false" title="切换 2D / 3D 视角">3D</button>
<span id="baseMapIcon">▧</span>
<select id="mapSourceSelect" aria-label="地图底图" data-rid-change="setBaseMap" data-rid-arg0="@value">
<option value="tdt-satellite" selected>天地图影像</option>
<option value="tdt-vector">天地图矢量</option>
<option value="amap-vector" disabled>高德地图(待接入)</option>
<option value="amap-satellite" disabled>高德卫星(待接入)</option>
<option value="osm-vector" disabled>OSM地图(待接入)</option>
<option value="esri-satellite" disabled>Esri卫星(待接入)</option>
<option value="custom-xyz" disabled>专网自定义地图(待接入)</option>
</select>
<label class="labelToggle" title="卫星图可叠加道路、地名、行政区等文字标注">
<input id="labelToggle" type="checkbox" checked data-rid-change="toggleMapLabels" data-rid-arg0="@checked"><span>标注</span>
</label>
<label class="cacheToggle" title="已浏览瓦片缓存到 maps/cache,手动下载的离线地图保存在 map_cache">
<input id="mapCacheQuickToggle" type="checkbox" checked disabled title="使用 RID 现有地图缓存"><span>缓存</span>
</label>
</div>
</div>
<button type="button" class="sideToggle leftToggle" data-rid-click="toggleSidePanel" data-rid-arg0="left" aria-controls="overviewLeft" aria-expanded="true" aria-label="设备与目标" title="收起设备与目标">‹</button>
<button type="button" class="sideToggle rightToggle" data-rid-click="toggleSidePanel" data-rid-arg0="right" aria-controls="overviewRight" aria-expanded="true" aria-label="防控区与告警" title="收起防控区与告警">›</button>
</div>
<div class="right" id="overviewRight">
<section class="panel zonePanel" aria-label="防控区管理">
<div class="p-title">防控区管理</div>
<p class="zoneFeedback" id="zoneFeedback" role="status" hidden></p>
<div class="list zonePanelContent">
<details id="zoneCoordinateEntry" class="zoneCoordinateEntry">
<summary>录入坐标</summary>
<form id="zoneCoordinateForm">
<div class="zoneFormFields">
<label>区域名称<input id="coordinateZoneName" maxlength="40" required></label>
<label>形状<select id="coordinateZoneType">
<option value="polygon">多边形</option>
<option value="rectangle">矩形</option>
<option value="circle">圆形</option>
</select></label>
</div>
<label>坐标(经度,纬度)
<textarea id="zoneCoordinates" rows="3" spellcheck="false" required aria-describedby="zoneCoordinateHelp" placeholder="118.782100, 31.982300"></textarea>
</label>
<p id="zoneCoordinateHelp">每行一个顶点,按边界顺序输入,至少三行。</p>
<label id="zoneRadiusField" hidden>半径(米)
<input id="zoneRadius" type="number" inputmode="decimal" min="1" max="1000000" step="any" disabled>
</label>
<button type="submit" id="coordinateZoneSave">保存防控区</button>
</form>
</details>
<div class="zoneDrawEditor" id="zoneDrawEditor" hidden>
<p id="drawHint"></p>
<div class="zoneDrawActions">
<input id="zoneName" maxlength="40" placeholder="防控区名称" aria-label="地图绘制防控区名称">
<button type="button" id="zoneDrawSave" data-rid-click="finishDrawZone">保存绘制</button>
</div>
</div>
<ul id="zoneList" class="zoneList"></ul>
</div>
</section>
<section class="panel alertPanel" aria-label="告警中心">
<div class="p-title">告警中心 <span class="panelCount" id="alertBadge">未读 0 · 已读 0</span></div>
<p id="alertFeedback" class="muted" role="status" hidden></p>
<div id="alertList" class="list">
<div class="muted">暂无告警</div>
</div>
<div class="alarmSettingRow">
<label><input id="soundAlarmToggle" type="checkbox" checked> 声音报警</label>
<label><input id="flashAlarmToggle" type="checkbox" checked> 告警闪屏</label>
<button type="button" class="smallBtn gray" data-rid-click="testAlarm">测试告警</button>
<button type="button" id="clearAlarm" class="smallBtn gray" data-rid-click="clearCurrentAlerts" disabled>清除显示</button>
</div>
</section>
</div>
<section id="moduleWorkspace" class="moduleWorkspace" aria-labelledby="moduleTitle">
<h2 id="moduleTitle" tabindex="-1"></h2>
<nav class="moduleNav" data-module-group="records" aria-label="记录分类" hidden>
<button type="button" data-rid-click="openModule" data-rid-arg0="records">轨迹记录</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="alarms">报警查询</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="rankings">统计分析</button>
</nav>
<nav class="moduleNav" data-module-group="devices" aria-label="设备管理分类" hidden>
<button type="button" data-rid-click="openModule" data-rid-arg0="devices">接收器列表</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="receivers">接收器诊断</button>
</nav>
<nav class="moduleNav" data-module-group="register" aria-label="档案分类" hidden>
<button type="button" data-rid-click="openModule" data-rid-arg0="register">设备登记</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="archives">本地档案</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="flight-plans">飞行报备</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="drones">黑白名单</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="models">型号库</button>
</nav>
<nav class="moduleNav" data-module-group="configs" aria-label="设置分类" hidden>
<button type="button" data-rid-click="openModule" data-rid-arg0="configs">平台设置</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="maps">地图与离线下载</button>
<button type="button" data-rid-click="openModule" data-rid-arg0="users">用户管理</button>
</nav>
<div id="moduleBody" class="moduleBody"></div>
<div id="moduleEmbed" class="moduleEmbed" hidden>
<p id="moduleEmbedStatus" role="status" hidden></p>
<button id="moduleEmbedRetry" type="button" hidden>重新加载</button>
</div>
</section>
</div>
</div>
<div id="alarmOverlay"><div class="alarmText" role="status"></div></div>
<p id="rid-workbench-status" role="status" aria-live="polite" hidden></p>
<script src="/workbench/drone-map.js"></script>
<script src="/workbench/flight-status.js"></script>
<script src="/workbench/rid-api.js"></script>
<script src="/workbench/platform.js"></script>
<script src="/workbench/modules.js"></script>
<script src="/workbench/module-host.js"></script>
<script src="/workbench/events.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+453
View File
@@ -0,0 +1,453 @@
(function () {
'use strict';
// Translate the authorized reference view's shapes at one boundary. Business
// rules, session checks, persistence, and receiver ownership stay in RID.
async function request(path, method = 'GET', body, options = {}) {
const response = await fetch(path, {
...options, method, cache: 'no-store', credentials: 'same-origin',
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
});
if (response.status === 401) {
location.replace('/workbench/');
throw new Error('会话已结束,请重新登录');
}
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const error = new Error(data.error || data.message || `RID 服务返回 HTTP ${response.status}`);
error.status = response.status;
throw error;
}
return data;
}
let receivers;
let receiverRequest;
let receiversAt = -Infinity;
async function receiverRows(refresh = false) {
if (!refresh && receivers && performance.now() - receiversAt < 900) return receivers;
if (!receiverRequest) {
receiverRequest = request('/api/receivers').then(data => {
if (data.error) throw new Error(data.error);
receiversAt = performance.now();
return receivers = data.receivers;
}).finally(() => { receiverRequest = null; });
}
return receiverRequest;
}
const stateLabels = {
'serial-open': '串口已打开', 'udp-listening': 'UDP 正在监听', 'tcp-listening': 'TCP 正在监听',
'connecting': '正在连接', 'disconnected': '连接中断', 'stopped': '未连接'
};
function link(row) {
const state = row?.status?.state;
const serial = row?.config.transport === 'serial';
const lastData = serial ? row.status?.lastValidFrameMs : row?.status?.lastDataMs;
const connected = Boolean(row?.config.enabled && ['serial-open', 'udp-listening', 'tcp-listening'].includes(state));
const receiving = connected && lastData != null && Date.now() - lastData <= 15000;
const tcp = row?.config.transport === 'tcp-listen';
let message = row?.status?.lastError || stateLabels[state] || '未连接';
if (connected && tcp) {
const peer = row.status.lastPeerIp;
message = receiving && peer ? '接收中 · ' + peer : 'TCP 监听中 · 等待数据';
}
if (connected && serial) message = receiving ? '串口接收中' : '串口已打开 · 等待有效报文';
return { connected, receiving, message };
}
function isStation(row) {
if (row.config.transport !== 'serial') return true;
return row.status.lastValidFrameMs != null || Boolean(row.userConfigured && row.config.serialPort);
}
async function sourceStatus() {
const rows = await receiverRows();
const serial = rows.filter(row => row.config.transport === 'serial');
const tcp = rows.filter(row => row.config.transport === 'tcp-listen');
const udp = rows.filter(row => row.config.transport === 'udp');
const collection = list => list.find(row => link(row).connected) || list[0];
return {
usb: link(collection(serial)), ble: { connected: false, message: '本阶段未接入 BLE' },
tcp: link(collection(tcp)), udp: link(collection(udp)), tcpDevices: tcp.map(link)
};
}
async function changeSerial(body, enabled) {
if (!/^COM[1-9]\d*$/i.test(body.port || '')) throw new Error('请先选择串口');
const port = body.port.toUpperCase();
const rows = await receiverRows(true);
const serial = rows.find(row => row.config.transport === 'serial' && row.config.serialPort === port);
if (!serial && !enabled) return { ok: true, connected: false, message: '该串口未被本平台打开' };
const code = serial ? `/api/receivers/${encodeURIComponent(serial.id)}` : '/api/receivers';
const config = { ...(serial?.config || { transport: 'serial', format: 'raw' }), enabled, serialPort: port };
if (enabled) config.baudRate = Number(body.baud);
await request(code, serial ? 'PUT' : 'POST', { name: serial?.name || `USB 串口 ${port}`, config });
receiversAt = -Infinity;
return { ok: true, connected: false, message: enabled ? '已启动串口接收任务,等待设备状态' : '串口已断开' };
}
const targets = new Map();
let ownership = new Map();
let lastFrame = -Infinity;
let stream;
let retry;
let stopped = false;
function applyFrame(frame) {
if (frame.snapshot) targets.clear();
for (const id of frame.removed) targets.delete(id);
for (const target of frame.targets) targets.set(target.observation.target_id, target);
lastFrame = performance.now();
if (frame.snapshot || frame.targets.length || frame.removed.length) {
window.dispatchEvent(new Event('rid-live-frame'));
}
}
function connectStream() {
if (stopped || stream) return;
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
stream = new WebSocket(`${protocol}//${location.host}/api/realtime/ws?format=json`);
stream.onmessage = ({ data }) => {
try {
const frame = JSON.parse(data);
applyFrame(frame);
stream.send(String(frame.sequence));
} catch (_) {
stream.close();
}
};
stream.onclose = () => {
stream = null;
if (!stopped) retry = setTimeout(connectStream, 2500);
};
}
window.addEventListener('pagehide', () => { stopped = true; clearTimeout(retry); stream?.close(); });
window.addEventListener('pageshow', () => { stopped = false; connectStream(); });
let rules = [];
let rulesExpires = 0;
let pendingRules;
function modelRules(refresh = false) {
if (!refresh && performance.now() < rulesExpires) return Promise.resolve(rules);
return pendingRules ??= request('/api/workbench/models').then(data => {
rulesExpires = performance.now() + 10000;
return rules = data.entries;
}).finally(() => { pendingRules = null; });
}
const modelRuleIndexes = new WeakMap();
function indexModelRules(entries) {
let index = modelRuleIndexes.get(entries);
if (index) return index;
const prefixes = new Map();
const keywords = [];
for (const rule of entries) {
if (!rule.enabled) continue;
if (rule.field === 'serial') prefixes.set(rule.pattern.toUpperCase(), rule);
else if (rule.field === 'target' || rule.field === 'model') keywords.push(rule);
}
const lengths = [...new Set([...prefixes.keys()].map(prefix => prefix.length))].sort((a, b) => b - a);
index = {prefixes, lengths, keywords};
modelRuleIndexes.set(entries, index);
return index;
}
function resolveModel(targetId, reported, entries = rules, serial) {
const {prefixes, lengths, keywords} = indexModelRules(entries);
const sn = (serial || '').trim().toUpperCase();
let match;
for (const length of lengths) {
if (length > sn.length) continue;
match = prefixes.get(sn.slice(0, length));
if (match) break;
}
if (!match) {
const ident = (targetId || '').toLowerCase();
const model = (reported || '').toLowerCase();
match = keywords.find(rule => (rule.field === 'target' ? ident : model).includes(rule.pattern));
}
if (!match) return reported;
const vendor = match.vendor.toLowerCase();
const name = match.model.toLowerCase();
if (match.field === 'serial' && (name === vendor || name.startsWith(vendor + ' '))) {
return match.model;
}
return [match.vendor, match.model].filter(Boolean).join(' ');
}
function detectionReceiver(id) {
const row = receivers?.find(receiver => receiver.id === id);
if (!row) return null;
// A network receiver with no peer restriction cannot identify which sender owns its last GNSS fix.
const identified = row.config.transport === 'serial'
|| (row.config.transport === 'tcp-listen' && !!row.config.peerIp);
const fresh = performance.now() - receiversAt <= 5000;
return {name: row.name, gnss: identified && fresh ? row.status.gnss : null};
}
async function liveRows() {
if (performance.now() - lastFrame > 2000) {
const frame = await request('/api/realtime/snapshot');
if (performance.now() - lastFrame > 2000) applyFrame(frame);
}
await Promise.all([modelRules().catch(() => rules), refreshOwnership()]);
return cachedLiveRows();
}
async function registrations(ids) {
const unique = [...new Set(ids)];
const batches = [];
for (let start = 0; start < unique.length; start += 96) {
const params = new URLSearchParams({ids: unique.slice(start, start + 96).join(',')});
batches.push(request('/api/target-registration-status?' + params));
}
const rows = (await Promise.all(batches)).flatMap(response => response.entries);
return new Map(rows.map(row => [row.targetId, row]));
}
let ownershipRequest;
let flightAssessments = new Map();
function refreshOwnership() {
return ownershipRequest ??= Promise.all([registrations(targets.keys()),request("/api/flight-status")]).then(([rows,status]) => {
ownership = rows;
flightAssessments = new Map(status.entries.map(row=>[row.targetId,row]));
}).catch(error => {flightAssessments.clear();console.warn('飞行状态暂不可用', error.message);})
.finally(() => { ownershipRequest = null; });
}
function registrationInfo(status) {
if (!status) return {};
const registryClass = status.listKind === 'black' ? 'blacklist'
: status.listKind === 'white' ? 'whitelist' : status.registered ? 'registered' : 'unregistered';
return { registered: status.registered, registryClass };
}
function cachedLiveRows() {
return [...targets.values()].map(target => {
const observation = target.observation;
const telemetry = observation.telemetry || {};
const source = target.sources?.find(source => source.observation.receiver_id === observation.receiver_id);
return {
uasId: observation.target_id, model: resolveModel(observation.target_id, telemetry.model || telemetry.name, rules, telemetry.serial) || 'RID 目标', bssid: telemetry.mac,
lat: observation.latitude, lng: observation.longitude, alt: observation.altitude_m,
pilotLat: telemetry.pilot_position?.[1], pilotLng: telemetry.pilot_position?.[0],
geometricAltitude: telemetry.geometric_altitude_m, pressureAltitude: telemetry.pressure_altitude_m,
heightAgl: telemetry.height_agl_m, relativeHeight: telemetry.relative_height_m,
speed: telemetry.speed_mps, rssi: telemetry.rssi, heading: observation.heading_deg,
source: observation.receiver_id, time: timestamp(target.received_at_ms), online: true,
sourceCount: target.sources?.length || 1,
receivedAtMs: source?.received_at_ms ?? target.received_at_ms, positionGeneration: target.position_generation,
sampleId: [observation.receiver_id, observation.source_epoch, observation.sequence].join(':'),
...registrationInfo(ownership.get(observation.target_id)),
flightClass: flightAssessments.get(observation.target_id)?.class || "unknown",
flightReason: flightAssessments.get(observation.target_id)?.reason,
positionUnverified: telemetry.position_unverified === true
};
});
}
function projectFence(fence) {
const geometry = fence.geometry;
const point = ([lng, lat]) => ({ lat, lng });
let type = geometry.type;
let points = geometry.vertices?.map(point);
if (type === 'circle') points = [{ ...point(geometry.center), radius: geometry.radius_m }];
if (type === 'polygon' && points.length === 4
&& new Set(points.map(point => point.lat)).size === 2
&& new Set(points.map(point => point.lng)).size === 2) {
type = 'rectangle';
points = [points[0], points[2]];
}
return { id: fence.id, name: fence.name, enabled: fence.enabled, type, points };
}
async function saveZone(method, id, body) {
const snapshot = await request('/api/geofences');
const existing = snapshot.entries.find(zone => zone.id === id);
if (id && !existing) throw new Error('防控区已变更,请刷新后重试');
if (method === 'DELETE') {
await request(`/api/geofences/${encodeURIComponent(id)}?revision=${snapshot.revision}`, method);
return { ok: true };
}
if (!id) id = `zone-${crypto.randomUUID()}`;
const coord = point => [point.lng, point.lat];
let geometry = existing?.geometry;
if (!geometry && body.type === 'circle') {
geometry = { type: 'circle', center: coord(body.points[0]), radius_m: body.points[0].radius };
} else if (!geometry && body.type === 'rectangle') {
const [a, b] = body.points;
geometry = { type: 'polygon', vertices: [coord(a), [a.lng, b.lat], coord(b), [b.lng, a.lat]] };
} else if (!geometry) {
geometry = { type: 'polygon', vertices: body.points.map(coord) };
}
await request(`/api/geofences/${encodeURIComponent(id)}`, 'PUT', {
expected_revision: snapshot.revision, fence: { id, name: body.name, enabled: body.enabled === true, geometry }
});
return { ok: true, id };
}
function timestamp(ms) {
return new Date(ms).toLocaleString('sv-SE', { hourCycle: 'h23' });
}
function dateArgument(value, fallback) {
if (!value) return fallback;
const result = new Date(value.replace(' ', 'T')).getTime();
if (!Number.isSafeInteger(result) || result < 0) throw new Error('日期范围无效');
return result;
}
function range(query) {
return {
fromMs: dateArgument(query.get('start'), 0),
toMs: dateArgument(query.get('end'), Date.now()),
q: query.get('keyword') || ''
};
}
async function events(query, limit = 100, offset, center = false) {
const { fromMs, toMs, q } = range(query);
const params = new URLSearchParams({ limit, from_ms: fromMs, to_ms: toMs, q: q === '未登记' || q === '未登记无人机告警' ? '' : q });
if (q === '未登记' || q === '未登记无人机告警') params.set('type','unregistered');
if (query.get('type')) params.set('type',query.get('type'));
if (query.get('handled')) params.set('handled', query.get('handled') === '1' ? '1' : '0');
if (offset !== undefined) params.set('offset', offset);
if (query.has('before')) params.set('before', query.get('before'));
if (query.has('after')) params.set('after', query.get('after'));
if (query.has('counts')) params.set('counts', '1');
const data = await request(`/api/monitoring/${center ? 'center' : 'events'}?${params}`);
const alerts = data.entries.map(event => ({
id: event.id, time: timestamp(event.occurred_at_ms), timeMs: event.occurred_at_ms,
uasId: event.target_id, lat: event.latitude, lng: event.longitude, kind: event.event_type,
type: window.ridFlightStatus.meta(event.event_type).label,
message: event.event_type === 'unregistered' ? '设备登记中未找到该目标' : event.fence_name || event.target_id,
handled: event.acknowledged_at_ms != null,
acknowledgedBy: event.acknowledged_by
}));
return { alerts, count: data.total ?? alerts.length, read: data.read, unread: data.unread };
}
async function getFlights(query) {
const params = new URLSearchParams({ ...range(query), limit: 120 });
const response = await request('/api/workbench/observations?' + params);
const flights = response.entries.map(row => ({
uasId: row.targetId, flightId: row.flightKey, model: row.model || row.targetId,
start: timestamp(row.timeMs), end: row.endMs == null ? '接收中' : timestamp(row.endMs),
lastLat: row.latitude, lastLng: row.longitude
}));
return { flights, total: response.total };
}
async function getPoints(flightKey) {
const points = [];
let after = 0;
do {
const params = new URLSearchParams({ flightKey, after, limit: 5000 });
const row = await request('/api/history/flight-points?' + params);
points.push(...row.entries);
after = row.nextAfter;
} while (after);
return window.ridDroneMap.prepareTrack(points).points.map(point => {
const osd = point.osd || {};
return {
lat: point.latitude, lng: point.longitude, alt: point.altitudeM,
heading: point.headingDeg, time: timestamp(point.timeMs), timeMs: point.timeMs, segmentStart: point.segmentStart,
speed: osd.speedMps, verticalSpeed: osd.verticalSpeedMps, rssi: osd.rssi,
height: osd.heightAglM, relativeHeight: osd.relativeHeightM,
geometricAltitude: osd.geometricAltitudeM, pressureAltitude: osd.pressureAltitudeM,
pilotLat: osd.pilotPosition?.[1], pilotLng: osd.pilotPosition?.[0]
};
});
}
async function summary() {
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
const [live, links, rows, fences, lists, recentAlerts, historyStats, alertStats] = await Promise.all([
liveRows(), sourceStatus(), receiverRows(), request('/api/geofences'), request('/api/target-lists'),
events(new URLSearchParams(), 6).then(result => result.alerts), request(`/api/history/summary?fromMs=${midnight.getTime()}`),
request(`/api/monitoring/summary?from_ms=${midnight.getTime()}`)
]);
const userData = await request('/api/auth/users').catch(error => {
if (error.status !== 403) throw error;
});
return {
...links, onlineCount: live.length, targetCount: live.length, zones: fences.entries.length,
deviceTotal: rows.length, userTotal: userData?.entries.length, registryTotal: lists.entries.length,
recentAlerts, recentRecords: historyStats.recent.map(point => ({ time: timestamp(point.timeMs), uasId: point.targetId, lat: point.latitude, lng: point.longitude })),
recordsToday: historyStats.since, recordsTotal: historyStats.total, alertsToday: alertStats.since, alertsTotal: alertStats.total
};
}
async function read(route, params) {
switch (route) {
case '/api/current_user': {
const account = await request('/api/auth/status');
if (!account.authenticated) { location.replace('/workbench/'); throw new Error('请重新登录'); }
return { user: { displayName: account.username, role: roleLabel(account.role), canAcknowledge: ['admin', 'operator'].includes(account.role) } };
}
case '/api/platform_configs': {
const prefs = await request('/api/maps/preferences');
return { configs: [{ key: 'default_map', value: prefs.basemap === 'road' ? 'tdt-vector' : 'tdt-satellite' }] };
}
case '/api/status': return sourceStatus();
case '/api/drones': {
const [drones, status] = await Promise.all([liveRows(), sourceStatus()]);
return { drones, count: drones.length, onlineCount: drones.length, status };
}
case '/api/ports': return (await request('/api/receiver/ports')).ports.map(device => ({ device }));
case '/api/zones': return (await request('/api/geofences')).entries.map(projectFence);
case '/api/alerts': params.set('counts', '1'); return events(params, 50, undefined, true);
case '/api/alerts_query': return events(params, 50, params.get('offset') ?? 0);
case '/api/local_stations': return { stations: (await receiverRows()).filter(isStation).map(row => {
const { connected, receiving, message } = link(row);
return {
id: row.id, name: row.name, sn: row.hardwareId, endpoint: row.status.endpoint,
transport: row.config.transport,
deviceIp: row.status.lastPeerIp || row.config.peerIp,
gnss: row.status.gnss,
status: message, linkState: receiving ? 'online' : connected ? 'waiting' : 'offline'
};
}) };
case '/api/local_fusion_info': return { sources: await sourceStatus() };
case '/api/flights': return getFlights(params);
case '/api/flight_track': return { points: await getPoints(params.get('flightId')) };
case '/api/monitor_summary': return summary();
case '/api/map_cache/status': {
const state = await request('/api/maps/status');
return { enabled: true, offlineOnly: state.mode === 'offline', hasTdtKey: state.keyConfigured };
}
default: throw new Error('此功能尚未接入本阶段');
}
}
async function mutate(route, method, body) {
if (route === '/api/zones' || route.startsWith('/api/zones/')) return saveZone(method, route.split('/')[3], body);
switch (route) {
case '/api/logout': return request('/api/auth/logout', 'POST');
case '/api/connect': return changeSerial(body, true);
case '/api/disconnect':
case '/api/release_port': return changeSerial(body, false);
case '/api/alerts_query':
return request(`/api/monitoring/events/${encodeURIComponent(body.id)}/acknowledgement`, 'PUT', {});
default: throw new Error('此功能尚未接入本阶段');
}
}
function roleLabel(role) {
return ({ admin: '管理员', operator: '操作员', viewer: '只读用户' })[role] || '未知角色';
}
window.ridWorkbenchApi = Object.freeze({
request, modelRules, resolveModel, roleLabel, getRecordPoints: getPoints, cachedLiveRows, detectionReceiver,
async registration(target) { return registrationInfo((await registrations([target])).get(target)); },
preferences: () => request('/api/maps/preferences'),
async fetch(path, options = {}) {
const url = new URL(path, location.origin);
try {
if (url.origin !== location.origin) throw new Error('仅允许访问本机 RID 接口');
const method = options.method || 'GET';
const body = typeof options.body === 'string' ? JSON.parse(options.body) : {};
return Response.json(method === 'GET' ? await read(url.pathname, url.searchParams) : await mutate(url.pathname, method, body));
} catch (error) {
return Response.json({ ok: false, message: error.message, error: error.message }, { status: error.status || 400 });
}
}
});
})();