feat(protocol): Observation坐标字段可选化及协议v2扩展

- 将Observation中longitude/latitude/altitude_m/heading_deg改为Option类型,
  支持无位置信息的观测数据
- 新增DeviceTelemetry结构体承载设备遥测扩展字段(serial, mac, model, rssi,
  speed, vertical_speed, pressure_altitude, geometric_altitude, height_agl,
  pilot_position等)
- 新增LegacyObservation兼容结构体及From转换,保持旧接收器协议输入兼容
- PROTOCOL_VERSION从1升至2
- 新增coordinates()辅助方法统一提取有效坐标
- validate()适配Option类型,允许坐标字段同时缺失
- Store新增position_generation机制追踪位置可用性变化,确保合并帧间的
  位置丢失仍能正确断开轨迹
- geofence-map-adapter过滤无效坐标避免渲染异常
- 新增appearance.css外观主题系统,支持blue/graphite/white三套配色
```
This commit is contained in:
2026-10-26 15:14:43 +08:00
parent 6157143a3e
commit 4eaa88baeb
38 changed files with 1285 additions and 123 deletions
+82
View File
@@ -0,0 +1,82 @@
// Serial/TCP/UDP adapter acceptance. Requires the sole UI port 8787 to be free.
// Optional --sample reads a local receiver log; no private sample is checked in.
import {mkdtemp,readFile,writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import net from 'node:net';
import dgram from 'node:dgram';
import assert from 'node:assert/strict';
import {createInterface} from 'node:readline';
const args=process.argv.slice(2),flag=name=>args.includes(name)?args[args.indexOf(name)+1]:null;
const exe=flag('--exe')||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const root=await mkdtemp(path.join(tmpdir(),'RID-device-'));
const base='http://127.0.0.1:8787';
let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
assert.equal(occupied,false,'8787 occupied; refusing to interrupt an existing server');
const child=spawn(exe,['--data-root',root,'--no-browser'],{windowsHide:true,stdio:['ignore','pipe','pipe']});
let output='',failure;child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>failure=e);
const get=async url=>{const r=await fetch(base+url);assert.equal(r.status,200);return r.json();};
async function poll(test){for(let i=0;i<200;i++){if(failure||child.exitCode!==null)throw Error(output||String(failure));if(await test())return;await new Promise(r=>setTimeout(r,25));}throw Error('receiver timeout');}
async function save(config){const r=await fetch(base+'/api/receiver/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(config)});assert.equal(r.status,200,await r.text());}
const snapshot=()=>get('/api/realtime/snapshot');
const status=()=>get('/api/receiver/status');
const encode=uav=>JSON.stringify({message:'RID',uav});
const target=(lon=0,lat=0)=>({serial:'TEST-DEVICE-001',model:'SIMULATED TEST',lon,lat,AltitudeG:-1000,AltitudeP:-1000,Height_AGL:-9000,rssi:-45,freq:2437,direc:90,utc:'1970-01-01 00:00:00.000'});
let udp;
try{
await poll(async()=>{try{return(await fetch(base+'/api/receiver/status')).ok;}catch{return false;}});
const initial=await get('/api/receiver/config');assert.equal(initial.enabled,false);
const probe=dgram.createSocket('udp4');await new Promise(r=>probe.bind(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));
const config={...initial,enabled:true,transport:'tcp-listen',format:'rid-device-json',bindIp:'127.0.0.1',port};
await save(config);await poll(async()=>(await status()).state==='tcp-listening');
const samplePath=flag('--sample');
const sample=samplePath?await readFile(samplePath,'utf8'):'ESP-ROM:boot\r\n'+encode([{serial:'TEST-LOG-A',lon:0,lat:0},{serial:'TEST-LOG-B',lon:0,lat:0}])+'\n{broken\n'+encode([])+'\n';
let decoded=0,rejected=0,ignored=0,accepted=0;const identities=new Set();
for(const line of sample.split(/\r?\n/).slice(0,sample.endsWith('\n')?-1:undefined)){
if(!line.trim().startsWith('{')&&!line.trim().startsWith('[')){ignored++;continue;}
try{const p=JSON.parse(line);if(p.message==='heartbeat'&&Array.isArray(p.uav)&&p.uav.length===0){ignored++;continue;}assert.equal(p.message,'RID');assert.ok(Array.isArray(p.uav));decoded++;for(const u of p.uav){accepted++;identities.add(u.serial);}}catch{rejected++;}
}
const tcp=net.createConnection({host:'127.0.0.1',port});await new Promise((resolve,reject)=>{tcp.once('connect',resolve);tcp.once('error',reject);});
const bytes=Buffer.from(sample+(sample.endsWith('\n')?'':'\n'));
for(let i=0;i<bytes.length;i+=997)if(!tcp.write(bytes.subarray(i,i+997)))await new Promise(r=>tcp.once('drain',r));
tcp.end();await poll(async()=>(await status()).decodedFrames===decoded);
let s=await status();assert.equal(s.rejectedFrames,rejected);assert.equal(s.ignoredLines,ignored);assert.equal(s.acceptedObservations,accepted);
let frame=await snapshot();assert.equal(frame.version,2);assert.equal(frame.targets.length,identities.size);assert.ok(frame.targets.every(t=>t.observation.longitude===null&&t.observation.latitude===null));
const replay={decoded,rejected,ignored,accepted,targets:frame.targets.length,located:0};
// Switch transports and verify release, mixed-entry isolation and position transitions.
await save({...config,transport:'udp'});await poll(async()=>(await status()).state==='udp-listening');
udp=dgram.createSocket('udp4');const send=async text=>new Promise((resolve,reject)=>udp.send(Buffer.from(text),port,'127.0.0.1',e=>e?reject(e):resolve()));
await send(encode([target(),{}, {MAC:'aa:bb:cc:dd:ee:ff',lon:0,lat:30}]));
await poll(async()=>(await status()).acceptedObservations===2);
assert.equal((await status()).invalidTargets,1);
frame=await snapshot();assert.ok(frame.targets.some(t=>t.observation.target_id==='MAC-AABBCCDDEEFF'&&t.observation.longitude===0));
const macBinding=await get('/api/target-bindings/MAC-AABBCCDDEEFF');assert.equal(macBinding.matchSource,'none');
let generation=0;
for(const [lon,lat] of [[120,30],[120.01,30.01],[0,0],[121,31]]){
const before=(await status()).acceptedObservations;await send(encode([target(lon,lat)]));await poll(async()=>(await status()).acceptedObservations===before+1);
const t=(await snapshot()).targets.find(t=>t.observation.target_id==='TEST-DEVICE-001');
assert.equal(t.observation.longitude,lon===0?null:lon);assert.equal(t.observation.altitude_m,null);assert.equal(t.observation.telemetry.geometric_altitude_m,null);
if(lon===120||lon===0||lon===121)generation++;
assert.equal(t.position_generation,generation);
}
// Reconnect TCP twice: receiver-generated sequence must continue to advance.
await save(config);await poll(async()=>(await status()).state==='tcp-listening');
for(let i=0;i<2;i++){const socket=net.createConnection({host:'127.0.0.1',port});await new Promise((resolve,reject)=>{socket.once('connect',resolve);socket.once('error',reject);});socket.end(encode([target()])+'\r\n');await poll(async()=>(await status()).acceptedObservations===i+1);}
await save({...config,enabled:false});assert.equal((await status()).state,'stopped');
await new Promise(r=>setTimeout(r,30500));await poll(async()=>(await snapshot()).targets.length===0);
const report={status:'PASS',root,replay,scenarios:['local raw-log TCP replay','fragmented lines and CRLF','damaged-frame recovery','multi-target isolation','UDP transport switch','MAC identity fallback','position acquire/loss/recovery','coalesced trail generation','TCP reconnect','30s expiry']};
await writeFile(path.join(root,'acceptance.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
if(args.includes('--hold')){
await save({...config,transport:'udp'});await poll(async()=>(await status()).state==='udp-listening');
let heldTargets=[target(),{serial:'TEST-DEVICE-002',model:'SIMULATED POSITION',lon:120.1538,lat:30.2874,AltitudeG:88,direc:180}];
const controlPath=path.join(root,'browser-control.json');
await writeFile(controlPath,JSON.stringify({targets:heldTargets}));
let finishBrowser;
const controlled=new Promise(resolve=>finishBrowser=resolve);
const timer=setInterval(async()=>{try{const control=JSON.parse(await readFile(controlPath,'utf8'));if(control.stop){finishBrowser();return;}if(Array.isArray(control.targets))heldTargets=control.targets;await send(encode(heldTargets));}catch(e){console.error(String(e));}},1000);
await writeFile(path.join(root,'browser-test.json'),JSON.stringify({root,port,pid:child.pid}));console.log(JSON.stringify({browserTest:{root,port,pid:child.pid}}));
const input=createInterface({input:process.stdin});
await Promise.race([controlled,new Promise(resolve=>{process.once('SIGINT',resolve);input.on('line',line=>{if(line==='done')resolve();else {try {const next=JSON.parse(line);if(Array.isArray(next))heldTargets=next;}catch{console.error('Expected a JSON target array or done');}}});})]);input.close();process.stdin.pause();clearInterval(timer);
}
}finally{udp?.close();if(child.exitCode===null&&!failure){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}await writeFile(path.join(root,'server.log'),output);}