feat(realtime): 增加目标接收计数与频率计算支持

- 在 Target 结构体中新增 received_count 字段,用于跟踪每个目标在当前内存轨迹中的接收更新次数。
- 实现 ReceptionRate 结构体,计算目标更新频率,并在 State 中维护每个目标的接收率。
- 更新相关测试,确保接收计数和频率计算的准确性。
- 修改 Web UI 以显示目标的接收频率,提升用户体验。
- 升级协议版本至 4,确保后端、Worker 和前端的一致性。
This commit is contained in:
2026-11-02 17:32:44 +08:00
parent 7af8fb32cf
commit 1d6d7a277e
9 changed files with 194 additions and 34 deletions
+27
View File
@@ -93,6 +93,7 @@ impl Store {
observation: observation.clone(),
received_at_ms: now_ms,
position_generation: 0,
received_count: 0,
sources: vec![],
},
sources: HashMap::new(),
@@ -125,6 +126,7 @@ impl Store {
.sources
.retain(|_, s| now_ms.saturating_sub(s.received_at_ms) < self.ttl_ms);
refresh(track);
track.target.received_count = track.target.received_count.saturating_add(1);
track.suppressed = false;
if let Some(observer) = &self.observer {
observer(&track.target.observation, now_ms);
@@ -333,6 +335,31 @@ mod tests {
}
}
#[test]
fn received_count_tracks_only_accepted_updates_per_target() {
let mut store = Store::new(4, 20, 30_000, 1);
assert!(store.apply(sample("A", 1), 100));
assert!(!store.apply(sample("A", 1), 200));
let mut invalid = sample("A", 2);
invalid.longitude = Some(f64::NAN);
assert!(!store.apply(invalid, 300));
assert!(store.apply(sample("B", 1), 400));
assert!(store.apply(sample("A", 2), 500));
let mut second_source = sample("A", 1);
second_source.receiver_id = "station-2".into();
assert!(store.apply(second_source, 600));
let frame = store.frame(Some(1), 600);
let counts: HashMap<_, _> = frame
.targets
.iter()
.map(|target| (target.observation.target_id.as_str(), target.received_count))
.collect();
assert_eq!(counts.get("A"), Some(&3));
assert_eq!(counts.get("B"), Some(&1));
store.expire(30_600);
assert!(store.apply(sample("A", 1), 30_601));
assert_eq!(store.frame(None, 30_601).targets[0].received_count, 1);
}
#[test]
fn coalesced_position_loss_still_breaks_the_trail() {
let mut store = Store::new(10, 100, 30000, 1);
let a = sample("TEST", 1);
+3 -1
View File
@@ -5,7 +5,7 @@ pub mod geofences;
pub mod map_settings;
pub mod target_lists;
pub const PROTOCOL_VERSION: u16 = 3;
pub const PROTOCOL_VERSION: u16 = 4;
pub const MAX_BATCH: usize = 4096;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
@@ -70,6 +70,8 @@ pub struct Target {
pub received_at_ms: u64,
/// Changes on every position availability transition, even between coalesced frames.
pub position_generation: u64,
/// Accepted updates for this target since its current in-memory track began.
pub received_count: u64,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
+5 -5
View File
@@ -173,14 +173,14 @@ function markerCoordinate(id,index){
if(id===selected&&rawFocus&&passesFilters(id))return {coordinate:rawFocus,unverified:true};
return null;
}
function markerAge(value){if(!liveConnected)return '连接断开';if(!Number.isFinite(value)||value<0)return '—';if(value<1000)return `${Math.round(value)} ms`;if(value<10000)return `${(value/1000).toFixed(1)} 秒`;return `${Math.round(value/1000)} 秒`;}
function markerFrequency(value){if(!liveConnected)return '连接断开';if(!Number.isFinite(value)||value<0)return '—';if(value===0)return '0 Hz';if(value<0.1)return `${value.toFixed(2)} Hz`;if(value<100)return `${value.toFixed(1)} Hz`;return `${Math.round(value)} Hz`;}
function createTargetMarker(id,coordinate){
const root=document.createElement('div');root.className='rt-target-pin';
const card=document.createElement('div');card.className='rt-target-info';
const header=document.createElement('div');header.className='rt-target-info-head';
const name=document.createElement('span');name.className='rt-target-info-id';name.textContent=id;name.title=id;
const age=document.createElement('span');age.className='rt-target-info-age';age.title='该目标最近一次接收数据到服务端生成推送数据的时间,不代表定位精度或完整传输延迟';
header.append(name,age);
const frequency=document.createElement('span');frequency.className='rt-target-info-frequency';frequency.title='服务端接受的目标数据更新频率;多个接收来源合计,5 秒无更新时显示 0 Hz';
header.append(name,frequency);
const coordinates=document.createElement('div');coordinates.className='rt-target-info-coordinates';
const longitude=document.createElement('span');const latitude=document.createElement('span');coordinates.append(longitude,latitude);
const height=document.createElement('div');height.className='rt-target-info-height';
@@ -192,7 +192,7 @@ function createTargetMarker(id,coordinate){
const point=document.createElement('i');point.className='rt-drone-point';
root.append(card,icon,point);
const marker=new maplibre.Marker({element:root,anchor:'bottom'}).setLngLat(coordinate).addTo(map);
return {marker,root,card,name,age,longitude,latitude,height,verification,icon,coordinate:[...coordinate]};
return {marker,root,card,name,frequency,longitude,latitude,height,verification,icon,coordinate:[...coordinate]};
}
function syncTargetMarkers(force=false){
if(!map||!latest)return;
@@ -225,7 +225,7 @@ function syncTargetMarkers(force=false){
const value=markerInfos?.[index*3+1],heightKind=markerInfos?.[index*3+2];
const label=({1:'高度',2:'几何高度',3:'离地高度',4:'相对高度(原始)',5:'气压高度'})[heightKind]||'高度';
entry.height.textContent=`${label} ${Number.isFinite(value)?`${value.toFixed(1)} m`:'—'}`;
entry.age.textContent=`数据年龄 ${markerAge(markerInfos?.[index*3])}`;
entry.frequency.textContent=`数据频率 ${markerFrequency(markerInfos?.[index*3])}`;
entry.verification.textContent=position.unverified?'坐标待核实':'';
}
if(updateText)lastMarkerText=now;
+1 -1
View File
@@ -9,7 +9,7 @@
.rt-target-info{box-sizing:border-box;width:100%;padding:7px 9px;border:1px solid #d6e9f04a;border-radius:6px;background:rgba(9,20,27,.38);backdrop-filter:blur(5px);-webkit-backdrop-filter:blur(5px);text-shadow:0 1px 3px #000,0 0 4px #000}
.rt-target-info-head{display:flex;align-items:center;justify-content:space-between;gap:6px;padding-bottom:4px;border-bottom:1px solid #e0f2fa35}
.rt-target-info-id{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;font-weight:600;letter-spacing:.01em}
.rt-target-info-age{flex:none;white-space:nowrap;color:#d6e8ee;font-size:10px}
.rt-target-info-frequency{flex:none;white-space:nowrap;color:#d6e8ee;font-size:10px}
.rt-target-info-coordinates{display:flex;justify-content:space-between;gap:8px;margin-top:4px;font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap}
.rt-target-info-height,.rt-target-info-verification{margin-top:2px;font-size:11px;font-variant-numeric:tabular-nums}
.rt-target-info-verification{color:#ffe0a2}.rt-target-info-verification:empty{display:none}
+135 -16
View File
@@ -23,10 +23,62 @@ pub fn acknowledge(sequence: f64) {
#[derive(Default)]
struct State {
targets: BTreeMap<String, Target>,
rates: BTreeMap<String, ReceptionRate>,
epoch: Option<u64>,
sequence: u64,
}
const RATE_WINDOW_MS: u64 = 5_000;
#[derive(Default)]
struct ReceptionRate {
baseline: Option<(u64, u64)>,
latest: Option<(u64, u64)>,
measured_hz: Option<f64>,
}
impl ReceptionRate {
fn observe(&mut self, received_at_ms: u64, received_count: u64) {
let sample = (received_at_ms, received_count);
let Some((last_time, last_count)) = self.latest else {
self.baseline = Some(sample);
self.latest = Some(sample);
return;
};
if received_at_ms < last_time || received_count < last_count {
*self = Self {
baseline: Some(sample),
latest: Some(sample),
measured_hz: None,
};
return;
}
if received_count == last_count {
return;
}
self.latest = Some(sample);
if let Some((start_time, start_count)) = self.baseline {
let elapsed = received_at_ms.saturating_sub(start_time);
if elapsed > 0 {
self.measured_hz =
Some((received_count - start_count) as f64 * 1000.0 / elapsed as f64);
if elapsed >= RATE_WINDOW_MS {
self.baseline = Some(sample);
}
}
}
}
fn current(&self, server_time_ms: u64) -> Option<f64> {
let (latest_time, _) = self.latest?;
if server_time_ms.saturating_sub(latest_time) >= RATE_WINDOW_MS {
Some(0.0)
} else {
self.measured_hz
}
}
}
impl State {
fn topology_changed(&self, frame: &Frame) -> bool {
self.epoch.is_none()
@@ -42,6 +94,9 @@ impl State {
return Err("unsupported protocol version");
}
if frame.snapshot {
if self.epoch != Some(frame.epoch) {
self.rates.clear();
}
self.targets.clear();
self.epoch = Some(frame.epoch);
} else if self.epoch != Some(frame.epoch) || frame.sequence < self.sequence {
@@ -50,11 +105,19 @@ impl State {
self.sequence = frame.sequence;
for id in &frame.removed {
self.targets.remove(id);
self.rates.remove(id);
}
for target in &frame.targets {
self.rates
.entry(target.observation.target_id.clone())
.or_default()
.observe(target.received_at_ms, target.received_count);
self.targets
.insert(target.observation.target_id.clone(), target.clone());
}
if frame.snapshot {
self.rates.retain(|id, _| self.targets.contains_key(id));
}
if self.targets.len() > 10000 {
return Err("target capacity exceeded");
}
@@ -83,13 +146,9 @@ fn marker_height(observation: &Observation) -> (f64, u8) {
(f64::NAN, 0)
}
fn marker_info(target: &Target, server_time_ms: u64) -> [f64; 3] {
fn marker_info(target: &Target, rate_hz: Option<f64>) -> [f64; 3] {
let (height, height_kind) = marker_height(&target.observation);
[
server_time_ms.saturating_sub(target.received_at_ms) as f64,
height,
f64::from(height_kind),
]
[rate_hz.unwrap_or(f64::NAN), height, f64::from(height_kind)]
}
fn post_status(scope: &web_sys::DedicatedWorkerGlobalScope, text: &str) {
@@ -144,7 +203,11 @@ pub fn connect(url: &str) -> Result<(), JsValue> {
o.altitude_m.map(f64::from).unwrap_or(f64::NAN),
o.heading_deg.map(f64::from).unwrap_or(f64::NAN),
]);
let info = marker_info(target, frame.server_time_ms);
let rate = state
.rates
.get(id)
.and_then(|rate| rate.current(frame.server_time_ms));
let info = marker_info(target, rate);
marker_infos.extend_from_slice(&info);
max_age = max_age.max(frame.server_time_ms.saturating_sub(target.received_at_ms));
}
@@ -238,19 +301,19 @@ mod tests {
},
received_at_ms,
position_generation: 1,
received_count: 1,
sources: vec![],
}
}
#[test]
fn marker_info_uses_each_targets_receive_time_and_keeps_height_reference() {
fn marker_info_keeps_frequency_and_height_reference() {
let mut recent = target(900);
let older = target(250);
assert_eq!(marker_info(&recent, 1_000)[0], 100.0);
assert_eq!(marker_info(&older, 1_000)[0], 750.0);
assert!(marker_info(&older, 1_000)[1].is_nan());
assert_eq!(marker_info(&older, 1_000)[2], 0.0);
assert_eq!(marker_info(&recent, 800)[0], 0.0);
assert_eq!(marker_info(&recent, Some(10.0))[0], 10.0);
assert!(marker_info(&older, None)[0].is_nan());
assert!(marker_info(&older, None)[1].is_nan());
assert_eq!(marker_info(&older, None)[2], 0.0);
recent.observation.telemetry = Some(DeviceTelemetry {
geometric_altitude_m: Some(125.0),
@@ -258,9 +321,9 @@ mod tests {
relative_height_m: Some(20.0),
..DeviceTelemetry::default()
});
assert_eq!(marker_info(&recent, 1_000)[1..], [125.0, 2.0]);
assert_eq!(marker_info(&recent, Some(10.0))[1..], [125.0, 2.0]);
recent.observation.altitude_m = Some(230.0);
assert_eq!(marker_info(&recent, 1_000)[1..], [230.0, 1.0]);
assert_eq!(marker_info(&recent, Some(10.0))[1..], [230.0, 1.0]);
recent.observation.altitude_m = None;
recent
.observation
@@ -268,7 +331,63 @@ mod tests {
.as_mut()
.unwrap()
.geometric_altitude_m = Some(f64::NAN);
assert_eq!(marker_info(&recent, 1_000)[1..], [31.0, 3.0]);
assert_eq!(marker_info(&recent, Some(10.0))[1..], [31.0, 3.0]);
}
#[test]
fn frequency_counts_coalesced_updates_and_expires_after_silence() {
let mut fast = ReceptionRate::default();
let mut slow = ReceptionRate::default();
fast.observe(1_000, 1);
slow.observe(1_000, 1);
assert_eq!(fast.current(1_000), None);
fast.observe(1_400, 41);
slow.observe(2_000, 2);
assert_eq!(fast.current(2_000), Some(100.0));
assert_eq!(slow.current(2_000), Some(1.0));
fast.observe(1_400, 41);
assert_eq!(fast.current(6_399), Some(100.0));
assert_eq!(fast.current(6_400), Some(0.0));
fast.observe(7_000, 42);
assert_eq!(fast.current(7_000), Some(41.0 * 1000.0 / 6000.0));
fast.observe(500, 1);
assert_eq!(
fast.current(500),
None,
"a restarted track starts a new measurement"
);
}
#[test]
fn decoded_frames_keep_per_target_frequency_through_coalescing() {
let mut state = State::default();
let mut item = target(1_000);
let mut frame = Frame {
version: PROTOCOL_VERSION,
epoch: 1,
sequence: 1,
snapshot: true,
server_time_ms: 1_000,
targets: vec![item.clone()],
removed: vec![],
};
let bytes = postcard::to_allocvec(&frame).unwrap();
state.apply(&postcard::from_bytes(&bytes).unwrap()).unwrap();
assert_eq!(state.rates["TEST"].current(1_000), None);
item.received_at_ms = 1_500;
item.received_count = 6;
frame.snapshot = false;
frame.sequence = 6;
frame.server_time_ms = 1_500;
frame.targets = vec![item];
let bytes = postcard::to_allocvec(&frame).unwrap();
state.apply(&postcard::from_bytes(&bytes).unwrap()).unwrap();
assert_eq!(state.rates["TEST"].current(1_500), Some(10.0));
assert_eq!(state.rates["TEST"].current(6_500), Some(0.0));
frame.targets.clear();
frame.removed.push("TEST".into());
state.apply(&frame).unwrap();
assert!(!state.rates.contains_key("TEST"));
}
#[test]