feat(web-ui): 添加 Windows 系统依赖并更新样式
- 在 Cargo.toml 中为 Windows 平台添加 windows-sys 依赖,版本为 0.52,包含 Win32_Foundation 和 Win32_System_Registry 特性。 - 更新相关 CSS 文件以改善界面样式,确保在不同主题下的视觉一致性。 - 在 JavaScript 文件中实现围栏标记的绘制和管理功能,增强地图交互体验。
This commit is contained in:
Generated
+1
@@ -714,6 +714,7 @@ dependencies = [
|
|||||||
"tokio-serial",
|
"tokio-serial",
|
||||||
"tokio-tungstenite",
|
"tokio-tungstenite",
|
||||||
"tower",
|
"tower",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ fs2 = "0.4"
|
|||||||
regex = "1"
|
regex = "1"
|
||||||
reqwest = { version = "=0.13.5", default-features = false, features = ["native-tls", "query", "system-proxy"] }
|
reqwest = { version = "=0.13.5", default-features = false, features = ["native-tls", "query", "system-proxy"] }
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_System_Registry"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
|
rusqlite = { version = "0.38", features = ["bundled", "backup"] }
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ body.b.theme-white :is(.home-card .mini, .wall-choice, .reference-rail .rail-too
|
|||||||
body.b.theme-white #appearance-view .wall-choice { background: var(--work-input); }
|
body.b.theme-white #appearance-view .wall-choice { background: var(--work-input); }
|
||||||
body.b.theme-white .reference-rail .rail-tooltip { background: var(--glass-solid); }
|
body.b.theme-white .reference-rail .rail-tooltip { background: var(--glass-solid); }
|
||||||
body.b.theme-white :is(.home-card-title, .home-card-open, .home-heading h1, .reference-title, .setting-panel-head h2, .preview-material strong) { color: var(--work-text); }
|
body.b.theme-white :is(.home-card-title, .home-card-open, .home-heading h1, .reference-title, .setting-panel-head h2, .preview-material strong) { color: var(--work-text); }
|
||||||
body.b.theme-white :is(.home-card-desc, .home-heading p, .home-kicker, .home-card .home-preview-caption, .wall-choice span, .preview-values dt, .preview-material span, .preview-material small) { color: var(--work-muted); }
|
body.b.theme-white :is(.home-card-desc, .home-heading p, .home-card .home-preview-caption, .wall-choice span, .preview-values dt, .preview-material span, .preview-material small) { color: var(--work-muted); }
|
||||||
body.b.theme-white .home-card .mini.appearance { background: var(--work-input); }
|
body.b.theme-white .home-card .mini.appearance { background: var(--work-input); }
|
||||||
body.b.theme-white .gf-stage .maplibregl-ctrl-icon { filter: none; }
|
body.b.theme-white .gf-stage .maplibregl-ctrl-icon { filter: none; }
|
||||||
@supports not ((backdrop-filter: blur(7px)) or (-webkit-backdrop-filter: blur(7px))) {
|
@supports not ((backdrop-filter: blur(7px)) or (-webkit-backdrop-filter: blur(7px))) {
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -6,7 +6,7 @@ let tileBuffer;
|
|||||||
let map, layer, latest, ids = [], selected = '', pending = false;
|
let map, layer, latest, ids = [], selected = '', pending = false;
|
||||||
let frameTimes = [], lastFrame = 0;
|
let frameTimes = [], lastFrame = 0;
|
||||||
let marker=null, history=[], lastTrail=0, generations=null, selectedGeneration=null;
|
let marker=null, history=[], lastTrail=0, generations=null, selectedGeneration=null;
|
||||||
let centered=false, workerWasmBytes=0, resizeObserver;
|
let centered=false, workerWasmBytes=0, resizeObserver, rawFocus=null;
|
||||||
let basemap="imagery",tileRevision=0,mapCreations=0;
|
let basemap="imagery",tileRevision=0,mapCreations=0;
|
||||||
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
|
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
|
||||||
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?v=${tileRevision}`:''}`;}
|
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?v=${tileRevision}`:''}`;}
|
||||||
@@ -17,6 +17,47 @@ function located(id,i=ids.indexOf(id)){return i>=0&&latest&&Number.isFinite(late
|
|||||||
function targetVisible(id,i=ids.indexOf(id)){return (!sourceIds||sourceIds.has(id))&&located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
|
function targetVisible(id,i=ids.indexOf(id)){return (!sourceIds||sourceIds.has(id))&&located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
|
||||||
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
|
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
|
||||||
let occlusion={top:0,right:0,bottom:0,left:0};
|
let occlusion={top:0,right:0,bottom:0,left:0};
|
||||||
|
let fenceEntries=[],fenceMarkers=[];
|
||||||
|
function clearFenceMarkers(){for(const marker of fenceMarkers)marker.remove();fenceMarkers=[];}
|
||||||
|
function fenceRing(geometry){
|
||||||
|
if(!geometry)return null;
|
||||||
|
if(geometry.type==='polygon'&&Array.isArray(geometry.vertices)){
|
||||||
|
const vertices=geometry.vertices.filter(point=>Array.isArray(point)&&Number.isFinite(point[0])&&Number.isFinite(point[1])&&Math.abs(point[0])<=180&&Math.abs(point[1])<=90);
|
||||||
|
return vertices.length>=3?[...vertices,vertices[0]]:null;
|
||||||
|
}
|
||||||
|
const center=geometry.center,radius=geometry.radius_m;
|
||||||
|
if(geometry.type!=='circle'||!Array.isArray(center)||!Number.isFinite(center[0])||!Number.isFinite(center[1])||Math.abs(center[0])>180||Math.abs(center[1])>90||!Number.isFinite(radius)||radius<1||radius>1000000)return null;
|
||||||
|
const delta=radius/6371008.8,a=center[1]*Math.PI/180,b=center[0]*Math.PI/180,points=[];
|
||||||
|
for(let i=0;i<=96;i++){const bearing=i/96*2*Math.PI,p=Math.asin(Math.sin(a)*Math.cos(delta)+Math.cos(a)*Math.sin(delta)*Math.cos(bearing));const q=b+Math.atan2(Math.sin(bearing)*Math.sin(delta)*Math.cos(a),Math.cos(delta)-Math.sin(a)*Math.sin(p));points.push([q*180/Math.PI,p*180/Math.PI]);}
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
function fenceLabelPoint(geometry){
|
||||||
|
if(geometry?.type==='circle'&&Array.isArray(geometry.center)&&geometry.center.every(Number.isFinite))return geometry.center;
|
||||||
|
const ring=fenceRing(geometry);
|
||||||
|
if(!ring)return null;
|
||||||
|
const unique=ring.slice(0,-1),lon=unique.reduce((sum,point)=>sum+point[0],0)/unique.length,lat=unique.reduce((sum,point)=>sum+point[1],0)/unique.length;
|
||||||
|
return Number.isFinite(lon)&&Number.isFinite(lat)?[lon,lat]:null;
|
||||||
|
}
|
||||||
|
function paintFences(){
|
||||||
|
if(!map?.getSource('fences'))return;
|
||||||
|
clearFenceMarkers();
|
||||||
|
const features=[];
|
||||||
|
for(const fence of fenceEntries){
|
||||||
|
const ring=fenceRing(fence.geometry);
|
||||||
|
if(!ring)continue;
|
||||||
|
const enabled=fence.enabled!==false;
|
||||||
|
features.push({type:'Feature',properties:{id:String(fence.id??''),name:String(fence.name??'围栏'),enabled},geometry:{type:'Polygon',coordinates:[ring]}});
|
||||||
|
const point=fenceLabelPoint(fence.geometry);
|
||||||
|
if(!point)continue;
|
||||||
|
const element=document.createElement('div');
|
||||||
|
element.className='rt-fence-label';
|
||||||
|
element.textContent=fence.name||'围栏';
|
||||||
|
element.dataset.enabled=enabled?'true':'false';
|
||||||
|
fenceMarkers.push(new maplibre.Marker({element,anchor:'center'}).setLngLat(point).addTo(map));
|
||||||
|
}
|
||||||
|
map.getSource('fences').setData({type:'FeatureCollection',features});
|
||||||
|
}
|
||||||
|
function setFences(entries){fenceEntries=Array.isArray(entries)?entries.filter(fence=>fence&&fence.geometry):[];paintFences();}
|
||||||
function shader(gl, type, source) {
|
function shader(gl, type, source) {
|
||||||
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
||||||
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
||||||
@@ -24,6 +65,7 @@ function shader(gl, type, source) {
|
|||||||
function create(container,initialBasemap="imagery",preferences=null) {
|
function create(container,initialBasemap="imagery",preferences=null) {
|
||||||
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
||||||
tileBuffer?.destroy();
|
tileBuffer?.destroy();
|
||||||
|
clearFenceMarkers();
|
||||||
if (map) map.remove();
|
if (map) map.remove();
|
||||||
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
|
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
|
||||||
// A configured startup camera takes precedence over the legacy first-target fallback.
|
// A configured startup camera takes precedence over the legacy first-target fallback.
|
||||||
@@ -92,7 +134,10 @@ function create(container,initialBasemap="imagery",preferences=null) {
|
|||||||
map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}});
|
map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}});
|
||||||
map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
|
map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
|
||||||
map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}});
|
map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}});
|
||||||
map.addLayer(layer);flush();
|
map.addSource('fences',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
|
||||||
|
map.addLayer({id:'fence-fill',type:'fill',source:'fences',paint:{'fill-color':['case',['get','enabled'],'#5ba6ed','#8192a5'],'fill-opacity':['case',['get','enabled'],.18,.08]}});
|
||||||
|
map.addLayer({id:'fence-line',type:'line',source:'fences',paint:{'line-color':['case',['get','enabled'],'#9fd4ff','#8192a5'],'line-width':['case',['get','enabled'],2,1.5]}});
|
||||||
|
map.addLayer(layer);paintFences();flush();
|
||||||
});
|
});
|
||||||
map.on('click',event=>{
|
map.on('click',event=>{
|
||||||
if(!latest)return;let index=-1,distance=18;
|
if(!latest)return;let index=-1,distance=18;
|
||||||
@@ -108,16 +153,33 @@ function flush(){
|
|||||||
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=visible;map.triggerRepaint();
|
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=visible;map.triggerRepaint();
|
||||||
const index=ids.indexOf(selected);
|
const index=ids.indexOf(selected);
|
||||||
if(index>=0&&targetVisible(selected)){
|
if(index>=0&&targetVisible(selected)){
|
||||||
|
rawFocus=null;
|
||||||
const coordinate=[latest[index*4],latest[index*4+1]];
|
const coordinate=[latest[index*4],latest[index*4+1]];
|
||||||
if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);}
|
const kind=targetKind(selected);
|
||||||
marker.getElement().textContent=selected+(targetKind(selected)==="black"?" · 黑名单":targetKind(selected)==="white"?" · 白名单":"");marker.getElement().dataset.listKind=targetKind(selected);marker.setLngLat(coordinate);
|
placeMarker(coordinate,selected+(kind==="black"?" · 黑名单":kind==="white"?" · 白名单":""),kind);
|
||||||
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
|
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
|
||||||
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
|
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
|
||||||
}else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
|
}else if(rawFocus){placeMarker(rawFocus,selected+' · 定位待核实','');history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
|
||||||
|
else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
|
||||||
}
|
}
|
||||||
function update(positions,newIds,newGenerations){latest=positions;generations=newGenerations;if(newIds)ids=Array.from(newIds);const selectedIndex=ids.indexOf(selected);const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}}
|
function update(positions,newIds,newGenerations){latest=positions;generations=newGenerations;if(newIds)ids=Array.from(newIds);const selectedIndex=ids.indexOf(selected);const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}}
|
||||||
function select(id){if(selected!==id){selected=id;history=[];selectedGeneration=generations?.[ids.indexOf(id)]??null;flush();}const i=ids.indexOf(id);return located(id)?Array.from(latest.slice(i*4,i*4+4)):[];}
|
function placeMarker(coordinate,text,kind){
|
||||||
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&located(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {tileBuffer:tileBuffer?.metrics(),basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").length},renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
|
if(!marker){
|
||||||
|
const root=document.createElement('div');root.className='rt-target-pin';
|
||||||
|
const label=document.createElement('div');label.className='rt-target-label';
|
||||||
|
const icon=document.createElement('div');icon.className='rt-drone-icon';icon.innerHTML='<svg viewBox="0 0 32 32" width="22" height="22" aria-hidden="true"><path d="M7 7 L25 25 M25 7 L7 25" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><circle cx="7" cy="7" r="3.1" fill="currentColor"/><circle cx="25" cy="7" r="3.1" fill="currentColor"/><circle cx="7" cy="25" r="3.1" fill="currentColor"/><circle cx="25" cy="25" r="3.1" fill="currentColor"/><circle cx="16" cy="16" r="3.3" fill="#f7fbff" stroke="currentColor" stroke-width="1.4"/></svg>';
|
||||||
|
const point=document.createElement('i');point.className='rt-drone-point';
|
||||||
|
root.append(label,icon,point);
|
||||||
|
marker=new maplibre.Marker({element:root,anchor:'bottom'}).setLngLat(coordinate).addTo(map);
|
||||||
|
}
|
||||||
|
const el=marker.getElement();
|
||||||
|
const label=el.querySelector('.rt-target-label');
|
||||||
|
label.textContent=text;label.dataset.listKind=kind||'';el.dataset.listKind=kind||'';
|
||||||
|
marker.setLngLat(coordinate);
|
||||||
|
}
|
||||||
|
function focusRaw(point){const lon=Number(point?.[0]),lat=Number(point?.[1]);if(!map||!selected||!Number.isFinite(lon)||!Number.isFinite(lat)||Math.abs(lon)>180||Math.abs(lat)>90)return;rawFocus=[lon,lat];focusCoordinate(rawFocus);placeMarker(rawFocus,selected+' · 定位待核实','');}
|
||||||
|
function select(id){if(selected!==id){selected=id;history=[];rawFocus=null;selectedGeneration=generations?.[ids.indexOf(id)]??null;flush();}if(located(id)){rawFocus=null;centerSelected();}const i=ids.indexOf(id);return located(id)?Array.from(latest.slice(i*4,i*4+4)):[];}
|
||||||
|
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&located(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {tileBuffer:tileBuffer?.metrics(),basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").length},renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes,fences:fenceEntries.length};}
|
||||||
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
|
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
|
||||||
function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
|
function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
|
||||||
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}}
|
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}}
|
||||||
@@ -146,4 +208,4 @@ function focusCoordinate(center,animate=true){
|
|||||||
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
|
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
|
||||||
}
|
}
|
||||||
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);}
|
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);}
|
||||||
window.ridMap={setSources,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};
|
window.ridMap={setSources,setFences,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,focusRaw,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){clearFenceMarkers();fenceEntries=[];tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];rawFocus=null;generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};
|
||||||
|
|||||||
@@ -259,6 +259,28 @@ body {
|
|||||||
background-color: #060b14;
|
background-color: #060b14;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.rt-fence-label {
|
||||||
|
max-width: 160px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid rgba(159, 212, 255, 0.72);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(6, 18, 33, 0.86);
|
||||||
|
color: #e9f0fa;
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1.5;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rt-fence-label[data-enabled="false"] { opacity: 0.55; }
|
||||||
|
body.b.theme-white .rt-fence-label {
|
||||||
|
border-color: rgba(36, 93, 157, 0.45);
|
||||||
|
background: rgba(255, 255, 255, 0.92);
|
||||||
|
color: #1c3348;
|
||||||
|
}
|
||||||
|
|
||||||
.mc-map-infobar {
|
.mc-map-infobar {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 16px;
|
bottom: 16px;
|
||||||
|
|||||||
@@ -39,3 +39,58 @@
|
|||||||
#rx-raw{max-height:min(180px,25dvh);margin:12px 0 0}
|
#rx-raw{max-height:min(180px,25dvh);margin:12px 0 0}
|
||||||
@media(max-height:600px){.rx-drawer{padding:12px 16px}.rx-drawer-header{margin-bottom:10px}#rx-form{gap:8px}#rx-form input:not([type=checkbox]),#rx-form select{height:32px;min-height:32px}#rx-form .rx-note{padding:6px 8px}}
|
@media(max-height:600px){.rx-drawer{padding:12px 16px}.rx-drawer-header{margin-bottom:10px}#rx-form{gap:8px}#rx-form input:not([type=checkbox]),#rx-form select{height:32px;min-height:32px}#rx-form .rx-note{padding:6px 8px}}
|
||||||
@media(max-width:650px){.rx-toolbar label{flex-basis:100%}.rx-toolbar input{max-width:none}#rx-summary{margin-right:auto}.rx-surface{min-height:calc(100dvh - 195px)}}
|
@media(max-width:650px){.rx-toolbar label{flex-basis:100%}.rx-toolbar input{max-width:none}#rx-summary{margin-right:auto}.rx-surface{min-height:calc(100dvh - 195px)}}
|
||||||
|
|
||||||
|
/* Cards sit on a surface that is already translucent. The shared panel token is only 40% opaque, so the card and its buttons were the same wash and the warning text had nothing solid behind it. */
|
||||||
|
.rx-card{background:var(--glass-solid,#0c1c2cf0)}
|
||||||
|
.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}
|
||||||
|
.rx-card.rx-ok{border-left-color:var(--mc-success,#81d8af)}
|
||||||
|
.rx-card.rx-warn{border-left-color:var(--mc-warning,#ffd08a)}
|
||||||
|
.rx-card.rx-info{border-left-color:var(--mc-accent,#8bbdff)}
|
||||||
|
.rx-card.rx-idle{border-left-color:color-mix(in srgb,var(--work-muted,#9eb3c8) 55%,transparent)}
|
||||||
|
.rx-card:hover{border-top-color:color-mix(in srgb,var(--mc-accent,#8bbdff) 48%,var(--work-line,#bdd8ff22));border-right-color:color-mix(in srgb,var(--mc-accent,#8bbdff) 48%,var(--work-line,#bdd8ff22));border-bottom-color:color-mix(in srgb,var(--mc-accent,#8bbdff) 48%,var(--work-line,#bdd8ff22))}
|
||||||
|
.rx-card h2{margin:0;height:22px;font-size:15px;font-weight:650;line-height:22px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.rx-card .rx-place,.rx-card .rx-meta{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.rx-card .rx-place{height:16px;color:var(--work-muted,#9eb3c8);font-size:12px;line-height:16px}
|
||||||
|
.rx-card .rx-meta{display:flex;justify-content:space-between;gap:10px;height:20px;font-size:13px;line-height:20px}
|
||||||
|
.rx-card .rx-meta span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.rx-card .rx-protocol{flex:none;color:var(--work-muted,#9eb3c8)}
|
||||||
|
.rx-pills{display:flex;align-items:center;gap:6px;height:24px;min-width:0}
|
||||||
|
.rx-pill{max-width:100%;height:22px;padding:0 8px;border-radius:999px;font-size:12px;line-height:22px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.rx-pill.rx-ok{color:var(--mc-success,#81d8af);background:color-mix(in srgb,var(--mc-success,#81d8af) 16%,transparent)}
|
||||||
|
.rx-pill.rx-warn{color:var(--mc-warning,#ffd08a);background:color-mix(in srgb,var(--mc-warning,#ffd08a) 16%,transparent)}
|
||||||
|
.rx-pill.rx-info{color:var(--mc-accent,#8bbdff);background:color-mix(in srgb,var(--mc-accent,#8bbdff) 16%,transparent)}
|
||||||
|
.rx-pill.rx-idle{color:var(--work-muted,#9eb3c8);background:color-mix(in srgb,var(--work-muted,#9eb3c8) 12%,transparent)}
|
||||||
|
.rx-pill.rx-role{flex:none;color:var(--work-muted,#9eb3c8);background:transparent;border:1px solid var(--work-line,#bdd8ff22)}
|
||||||
|
.rx-alert{display:flex;align-items:center;gap:8px;height:22px;min-width:0;color:var(--mc-warning,#ffd08a);font-size:12px}
|
||||||
|
.rx-alert.quiet{color:var(--work-muted,#9eb3c8)}
|
||||||
|
.rx-alert-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.rx-card .rx-more{flex:none;height:20px;padding:0 6px;border-radius:6px;background:transparent;color:var(--mc-warning,#ffd08a);font-size:12px;line-height:18px;white-space:nowrap}
|
||||||
|
.rx-card .rx-metrics{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:0;padding-top:10px}
|
||||||
|
.rx-card .rx-metrics strong{font-size:22px}
|
||||||
|
.rx-card .rx-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:0}
|
||||||
|
.rx-card .rx-actions button{height:32px;padding:0 10px;white-space:nowrap}
|
||||||
|
.rx-pop{position:fixed;z-index:40;width:min(340px,calc(100vw - 24px));padding:10px 12px;border:1px solid var(--work-line,#bdd8ff22);border-radius:10px;background:#102033;color:var(--work-text,#e9f0fa);box-shadow:0 16px 40px #000a}
|
||||||
|
.theme-white .rx-pop{background:#f7fbff;color:#20384f}
|
||||||
|
.rx-pop p{margin:0 0 8px;font-size:12px;line-height:1.55}
|
||||||
|
.rx-pop p:last-child{margin:0}
|
||||||
|
.theme-white .rx-pill.rx-ok{color:#236647;background:#23664718}
|
||||||
|
.theme-white .rx-card.rx-ok{border-left-color:#236647}
|
||||||
|
.theme-white .rx-pill.rx-warn,.theme-white .rx-alert:not(.quiet),.theme-white .rx-card .rx-more{color:#875013}
|
||||||
|
.theme-white .rx-pill.rx-warn{background:#87501316}
|
||||||
|
.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}
|
||||||
|
|||||||
@@ -5,15 +5,61 @@ const defaults = {enabled:false,transport:'serial',format:'raw',serialPort:'',ba
|
|||||||
const protocols = {'raw':'原始诊断','uid-json':'UID JSON','rid-device-json':'RID / uav','json-lines':'约定 JSON','postcard':'Postcard'};
|
const protocols = {'raw':'原始诊断','uid-json':'UID JSON','rid-device-json':'RID / uav','json-lines':'约定 JSON','postcard':'Postcard'};
|
||||||
function state(row) {
|
function state(row) {
|
||||||
const s=row.status;
|
const s=row.status;
|
||||||
|
if(s?.notice)return s.notice;
|
||||||
|
if(!row.detector && row.deviceKind && !row.config.enabled)return '其他串口 · 未当作侦测机';
|
||||||
if(!row.config.enabled)return '未启用';
|
if(!row.config.enabled)return '未启用';
|
||||||
if(s.state==='disconnected')return '连接失败 · 自动重试';
|
if(s.state==='disconnected')return '连接失败 · 自动重试';
|
||||||
if(s.state==='connecting')return '正在连接';
|
if(s.state==='connecting')return '正在连接';
|
||||||
if(!s.receivedBytes)return '已连接 · 等待数据';
|
if(!s.receivedBytes)return row.detector?'侦测串口已连接 · 还没有数据':'已连接 · 等待数据';
|
||||||
if(Date.now()-(s.lastDataMs||0)>10000)return '连接中 · 暂无新数据';
|
if(Date.now()-(s.lastDataMs||0)>10000)return '连接中 · 暂无新数据';
|
||||||
if(row.config.format==='raw')return '接收中 · 原始诊断';
|
if(row.config.format==='raw')return '接收中 · 原始诊断';
|
||||||
if(s.rejectedFrames && !s.decodedFrames)return '收到数据 · 协议不匹配';
|
if(s.rejectedFrames && !s.decodedFrames)return '收到数据 · 协议不匹配';
|
||||||
if(!s.acceptedObservations)return '接收中 · 暂无有效目标';
|
if(!s.acceptedObservations)return '正在接收 · 暂无有效目标';
|
||||||
return '接收中 · 已解析目标';
|
return '正在接收 · 已解析目标';
|
||||||
|
}
|
||||||
|
const GB_NOTE='这台设备收到了报文,但帧头不符合它自己的 GB46750 要求,所以不会生成目标。';
|
||||||
|
const UID_NOTE='坐标系待核实 · 原始坐标在目标详情中查看';
|
||||||
|
let popFor=null;
|
||||||
|
function tone(row){
|
||||||
|
if(!row.config?.enabled)return 'idle';
|
||||||
|
const s=row.status||{};
|
||||||
|
if(s.notice||s.state==='disconnected')return 'warn';
|
||||||
|
if(s.state==='connecting'||s.state==='stopped'||!s.receivedBytes)return 'info';
|
||||||
|
if(Date.now()-(s.lastDataMs||0)>10000)return 'info';
|
||||||
|
if(row.config.format==='raw')return 'ok';
|
||||||
|
if(s.rejectedFrames&&!s.decodedFrames)return 'warn';
|
||||||
|
if(!s.acceptedObservations)return '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 identity(row){
|
||||||
|
const name=row.name||'未命名接收机',cut=name.indexOf(' · ');
|
||||||
|
const head=cut<0?name:name.slice(0,cut);
|
||||||
|
let place=cut<0?'':name.slice(cut+3);
|
||||||
|
if(!place)place=row.devicePlace||(row.config.transport==='serial'?'—':'网络 · 手动添加');
|
||||||
|
return {head,place};
|
||||||
|
}
|
||||||
|
function endpoint(row){const c=row.config;return c.transport==='serial'?`${c.serialPort||'尚未选择串口'} · ${c.baudRate}`:`${c.transport==='udp'?'UDP':'TCP'} · ${c.bindIp}:${c.port}`;}
|
||||||
|
function faults(row){const list=[];if(row.status?.lastError)list.push(row.status.lastError);if(row.status?.notice)list.push(GB_NOTE);if(row.config.format==='uid-json')list.push(UID_NOTE);return list;}
|
||||||
|
function closePop(){popFor=null;const pop=$('rx-pop');if(pop)pop.hidden=true;}
|
||||||
|
function placePop(anchor){
|
||||||
|
const pop=$('rx-pop');if(!pop||pop.hidden||!anchor)return;
|
||||||
|
const card=anchor.closest('.rx-card');
|
||||||
|
const bounds=(card||anchor).getBoundingClientRect();
|
||||||
|
pop.style.width=`${Math.max(200,Math.min(340,bounds.width))}px`;
|
||||||
|
const w=pop.offsetWidth,h=pop.offsetHeight;
|
||||||
|
let left=Math.min(Math.max(8,bounds.left),window.innerWidth-w-8);
|
||||||
|
let top=bounds.bottom+8;
|
||||||
|
if(top+h>window.innerHeight-8)top=Math.max(8,bounds.top-h-8);
|
||||||
|
pop.style.left=`${left}px`;pop.style.top=`${top}px`;
|
||||||
|
}
|
||||||
|
function openPop(row,anchor){const pop=$('rx-pop');if(!pop)return;pop.replaceChildren(...faults(row).map(text=>el('p',text)));pop.hidden=false;popFor=row.id;placePop(anchor);}
|
||||||
|
function syncPop(list){
|
||||||
|
if(!popFor)return;
|
||||||
|
const row=list.find(item=>item.id===popFor);
|
||||||
|
const anchor=$('rx-cards').querySelector(`[data-rx-alerts="${CSS.escape(popFor)}"]`);
|
||||||
|
if(!row||!anchor)closePop();else openPop(row,anchor);
|
||||||
}
|
}
|
||||||
async function api(url,method='GET',body) {
|
async function api(url,method='GET',body) {
|
||||||
const r=await fetch(url,{method,headers:body?{'Content-Type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});
|
const r=await fetch(url,{method,headers:body?{'Content-Type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});
|
||||||
@@ -23,17 +69,25 @@ function el(tag,text,className) {const e=document.createElement(tag);if(text!==u
|
|||||||
function render(){
|
function render(){
|
||||||
const focused=document.activeElement?.dataset.rxFocus;
|
const focused=document.activeElement?.dataset.rxFocus;
|
||||||
const query=$('rx-search').value.trim().toLowerCase();
|
const query=$('rx-search').value.trim().toLowerCase();
|
||||||
const list=rows.filter(r=>`${r.name} ${r.id} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
|
const list=rows.filter(r=>`${r.name} ${r.deviceKind||''} ${r.devicePlace||''} ${r.id} ${r.hardwareId||''} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
|
||||||
$('rx-summary').textContent=`${rows.length} 台接收机 · ${rows.filter(r=>r.config.enabled).length} 台已启用`;
|
const watching=rows.filter(r=>r.detector&&r.config.enabled).length;
|
||||||
|
$('rx-summary').textContent=`${rows.length} 个串口 · ${watching} 台侦测机已启用`;
|
||||||
$('rx-cards').replaceChildren(...list.map(row=>{
|
$('rx-cards').replaceChildren(...list.map(row=>{
|
||||||
const c=el('article',undefined,'rx-card');c.append(el('h2',row.name),el('p',state(row),'rx-badge'));
|
const idn=identity(row),toneName=tone(row),lines=faults(row);
|
||||||
c.append(el('p',row.config.transport==='serial'?`${row.config.serialPort||'尚未选择串口'} · ${row.config.baudRate}`:`${row.config.transport.toUpperCase()} · ${row.config.bindIp}:${row.config.port}`));
|
const c=el('article',undefined,`rx-card rx-${toneName}`);
|
||||||
c.append(el('p',protocols[row.config.format]||row.config.format,'rx-footnote'));
|
const title=el('h2',idn.head);title.title=row.name||idn.head;
|
||||||
if(row.status.lastError)c.append(el('p',row.status.lastError,'rx-warn'));
|
const place=el('p',idn.place,'rx-place');place.title=idn.place;
|
||||||
if(row.config.format==='uid-json')c.append(el('p','坐标系待核实 · 原始坐标在目标详情中查看','rx-warn'));
|
const pills=el('div',undefined,'rx-pills'),statusText=cardStatus(row);
|
||||||
const metrics=el('div',undefined,'rx-metrics');for(const [label,value] of [['接收字节',row.status.receivedBytes],['接受更新',row.status.acceptedObservations]]){const m=el('div');m.append(el('strong',Number(value).toLocaleString()),el('span',label));metrics.append(m);}c.append(metrics);
|
const status=el('span',statusText,`rx-pill rx-${toneName}`);status.title=statusText;
|
||||||
const actions=el('div',undefined,'rx-actions'),manage=el('button','配置与诊断'),toggle=el('button',row.config.enabled?'停用':'启用');manage.dataset.rxFocus=row.id+'-manage';toggle.dataset.rxFocus=row.id+'-toggle';manage.onclick=()=>open(row);toggle.disabled=busy;toggle.onclick=async()=>{await mutate(async()=>{await api(`/api/receivers/${row.id}`,'PUT',{name:row.name,config:{...row.config,enabled:!row.config.enabled}});});};actions.append(manage,toggle);c.append(actions);return c;
|
pills.append(status,el('span',roleLabel(row),'rx-pill rx-role'));
|
||||||
}));$('rx-empty').hidden=!!list.length;
|
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 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);
|
||||||
if(focused){for(const button of $('rx-cards').querySelectorAll('button')){if(button.dataset.rxFocus===focused){button.focus({preventScroll:true});break;}}}
|
if(focused){for(const button of $('rx-cards').querySelectorAll('button')){if(button.dataset.rxFocus===focused){button.focus({preventScroll:true});break;}}}
|
||||||
if(selected)diagnostics();
|
if(selected)diagnostics();
|
||||||
}
|
}
|
||||||
@@ -41,13 +95,17 @@ async function refresh(){if(pending||!$('rx-cards'))return;pending=true;try{cons
|
|||||||
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();}}
|
async function mutate(action){if(busy)return;busy=true;render();try{await action();await refresh();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;if($('rx-drawer').open)$('rx-message').textContent=e.message;}finally{busy=false;render();}}
|
||||||
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-protocol-note').textContent=f.elements.format.value==='uid-json'?'UID 报文中的坐标系代码尚未核实:显示原始坐标,不在地图落点、不参与围栏。':f.elements.format.value==='raw'?'原始诊断只接收字节,不生成无人机目标。':'协议必须与设备实际输出一致;未知报文不会猜测为位置。';}
|
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-protocol-note').textContent=f.elements.format.value==='uid-json'?'UID 报文中的坐标系代码尚未核实:显示原始坐标,不在地图落点、不参与围栏。':f.elements.format.value==='raw'?'原始诊断只接收字节,不生成无人机目标。':'协议必须与设备实际输出一致;未知报文不会猜测为位置。';}
|
||||||
function tab(diagnostic){$('rx-form').hidden=diagnostic;$('rx-diagnostic').hidden=!diagnostic;$('rx-config-tab').setAttribute('aria-pressed',String(!diagnostic));$('rx-diagnostic-tab').setAttribute('aria-pressed',String(diagnostic));diagnostics();}
|
function tab(diagnostic){$('rx-form').hidden=diagnostic;$('rx-diagnostic').hidden=!diagnostic;$('rx-config-tab').setAttribute('aria-pressed',String(!diagnostic));$('rx-diagnostic-tab').setAttribute('aria-pressed',String(diagnostic));diagnostics();}
|
||||||
function diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无']]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
function 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||'无']]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
||||||
function open(row){selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config=row?.config||defaults;f.elements.name.value=row?.name||'';for(const [key,value] of Object.entries(config)){if(key==='enabled')f.elements[key].checked=value;else f.elements[key].value=value;}$('rx-delete').hidden=!selected||selected==='default';fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
|
function 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=row?.config||defaults;f.elements.name.value=row?.name||'';for(const [key,value] of Object.entries(config)){if(key==='enabled')f.elements[key].checked=value;else f.elements[key].value=value;}$('rx-delete').hidden=!selected||selected==='default';fields();tab(false);$('rx-drawer').showModal();f.elements.name.focus();api('/api/receiver/ports').then(v=>$('rx-port-options').replaceChildren(...v.ports.map(p=>{const o=el('option');o.value=p;return o;}))).catch(()=>{});}
|
||||||
function close(){if(dirty&&!confirm('尚有未保存的配置,放弃修改并关闭?'))return;$('rx-drawer').close();selected=null;dirty=false;}
|
function 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);
|
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-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-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;}};
|
$('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;}};
|
||||||
|
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.body.dataset.screen==='receivers')refresh();},1500);
|
||||||
}
|
}
|
||||||
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
|
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
|
||||||
|
|||||||
@@ -75,3 +75,12 @@ body.b[data-screen=realtime] .live-panel-restores{top:64px;left:calc(var(--navig
|
|||||||
/* Keep location availability visible even when a long device identity is truncated. */
|
/* Keep location availability visible even when a long device identity is truncated. */
|
||||||
.rt-device-id { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.rt-device-id { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.rt-position-state { display: block; color: var(--work-muted); font-size: 11px; line-height: 1.5; }
|
.rt-position-state { display: block; color: var(--work-muted); font-size: 11px; line-height: 1.5; }
|
||||||
|
|
||||||
|
/* A backdrop-filter on the panel itself makes Chromium paint the native source menu inside the filtered layer, so the open list is clipped and transparent. Frost the panel from a pseudo-element instead. */
|
||||||
|
body.b .mc-layout-b .mc-floating-panel { background: transparent; backdrop-filter: none; -webkit-backdrop-filter: none; }
|
||||||
|
body.b .mc-layout-b .mc-floating-panel::before { content: ""; position: absolute; inset: 0; z-index: 0; border-radius: inherit; pointer-events: none; background: var(--glass-surface); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); }
|
||||||
|
body.b .mc-layout-b .mc-floating-panel > * { position: relative; z-index: 1; }
|
||||||
|
body.b .mc-layout-b .live-list-controls select { display: block; width: 100%; height: 34px; min-height: 34px; margin: 4px 0 0; padding: 0 8px; box-sizing: border-box; border: 1px solid var(--work-line); border-radius: 8px; background-color: var(--work-input); color: var(--work-text); font: inherit; font-size: 12px; font-weight: 400; line-height: 1.4; overflow-wrap: normal; white-space: nowrap; color-scheme: dark; }
|
||||||
|
body.b.theme-white .mc-layout-b .live-list-controls select { color-scheme: light; }
|
||||||
|
body.b .mc-layout-b .live-list-controls select option { background-color: #061221; color: #e9f0fa; font-weight: 400; line-height: normal; }
|
||||||
|
body.b.theme-white .mc-layout-b .live-list-controls select option { background-color: #f4f8ff; color: #243b57; }
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ body[data-screen=home] .home-launcher.homescreen {
|
|||||||
body[data-screen=home] :is(.reference-rail, #toggle-menu) { display: none; }
|
body[data-screen=home] :is(.reference-rail, #toggle-menu) { display: none; }
|
||||||
.home-space { width: 100%; max-width: 1170px; }
|
.home-space { width: 100%; max-width: 1170px; }
|
||||||
.home-heading { text-align: center; }
|
.home-heading { text-align: center; }
|
||||||
.home-kicker { color: var(--work-muted); font-size: 11px; letter-spacing: .14em; margin-bottom: 10px; }
|
|
||||||
.home-heading h1 { font-size: 27px; }
|
.home-heading h1 { font-size: 27px; }
|
||||||
.home-cards { gap: 20px; }
|
.home-cards { gap: 20px; }
|
||||||
.home-card { min-height: 370px; padding: 25px; }
|
.home-card { min-height: 370px; padding: 25px; }
|
||||||
@@ -72,10 +71,17 @@ body:is([data-screen=register], [data-screen=archives]) .registry-workspace .reg
|
|||||||
body:is([data-screen=register], [data-screen=archives]) .registry-workspace #registration-result {
|
body:is([data-screen=register], [data-screen=archives]) .registry-workspace #registration-result {
|
||||||
padding: 0; margin: 0; overflow: auto; scroll-padding-top: 60px; scrollbar-width: thin;
|
padding: 0; margin: 0; overflow: auto; scroll-padding-top: 60px; scrollbar-width: thin;
|
||||||
}
|
}
|
||||||
#registration-result > h2 {
|
#registration-result > .result-heading {
|
||||||
position: sticky; top: 0; z-index: 2; padding: 17px 20px; min-height: 54px;
|
position: sticky; top: 0; z-index: 2; padding: 17px 20px; min-height: 54px;
|
||||||
background: var(--glass-solid); border-bottom: 1px solid var(--work-line);
|
background: var(--glass-solid); border-bottom: 1px solid var(--work-line);
|
||||||
|
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||||
}
|
}
|
||||||
|
#registration-result > .result-heading h2 { margin: 0; font-size: 16px; }
|
||||||
|
#close-archive-detail {
|
||||||
|
height: 32px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--work-line);
|
||||||
|
background: transparent; color: var(--work-text); font-size: 12px; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.result-fpv-label { margin: 0; font-size: 11px; letter-spacing: .04em; color: var(--work-muted); }
|
||||||
.registry-workspace #registration-result .empty-state {
|
.registry-workspace #registration-result .empty-state {
|
||||||
display: flex; flex-direction: column; align-items: flex-start; padding: 24px 20px; gap: 16px;
|
display: flex; flex-direction: column; align-items: flex-start; padding: 24px 20px; gap: 16px;
|
||||||
}
|
}
|
||||||
@@ -175,7 +181,7 @@ body:is([data-screen=register], [data-screen=archives]) .registry-workspace #reg
|
|||||||
body:is([data-screen=register], [data-screen=archives]) .registry-workspace .registration-savebar { position: sticky; bottom: 0; padding: 14px 16px; z-index: 3; }
|
body:is([data-screen=register], [data-screen=archives]) .registry-workspace .registration-savebar { position: sticky; bottom: 0; padding: 14px 16px; z-index: 3; }
|
||||||
.registry-workspace #register-button { width: 100%; }
|
.registry-workspace #register-button { width: 100%; }
|
||||||
body:is([data-screen=register], [data-screen=archives]) .registry-workspace #registration-result { order: 2; flex-shrink: 0; overflow: visible; }
|
body:is([data-screen=register], [data-screen=archives]) .registry-workspace #registration-result { order: 2; flex-shrink: 0; overflow: visible; }
|
||||||
#registration-result > h2 { position: static; }
|
#registration-result > .result-heading { position: static; }
|
||||||
.registry-workspace #registration-result .empty-state { flex-direction: column; }
|
.registry-workspace #registration-result .empty-state { flex-direction: column; }
|
||||||
#appearance-view .settings-layout { display: flex; flex-direction: column; padding: 16px; gap: 16px; }
|
#appearance-view .settings-layout { display: flex; flex-direction: column; padding: 16px; gap: 16px; }
|
||||||
#appearance-view .settings-sidebar { display: flex; flex-wrap: wrap; gap: 6px; width: 100%; padding: 10px; flex-shrink: 0; }
|
#appearance-view .settings-sidebar { display: flex; flex-wrap: wrap; gap: 6px; width: 100%; padding: 10px; flex-shrink: 0; }
|
||||||
@@ -210,3 +216,31 @@ body[data-screen=archives] .registry-workspace .history-panel { grid-row: auto;
|
|||||||
body[data-screen=register] .registry-workspace #registration-result { grid-column: auto; }
|
body[data-screen=register] .registry-workspace #registration-result { grid-column: auto; }
|
||||||
body[data-screen=archives] .registry-workspace .history-panel { min-height: 420px; }
|
body[data-screen=archives] .registry-workspace .history-panel { min-height: 420px; }
|
||||||
}
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] .registry-workspace {
|
||||||
|
display: grid; grid-template-columns: minmax(300px, 400px) minmax(0, 1fr);
|
||||||
|
grid-template-rows: minmax(0, 1fr); height: 100%; max-height: 100%; overflow: hidden;
|
||||||
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] .registry-workspace :is(.history-panel, #registration-result) {
|
||||||
|
height: auto; max-height: none; min-height: 0; position: static;
|
||||||
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .record-result {
|
||||||
|
display: grid; grid-template-columns: 220px minmax(280px, 480px); justify-content: center; align-items: start;
|
||||||
|
column-gap: 36px; row-gap: 12px; padding: 28px 32px 36px;
|
||||||
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .qr-stage { grid-column: 1; grid-row: 1 / span 8; width: 200px; justify-self: center; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .record-result > :not(.qr-stage) { grid-column: 2; min-width: 0; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .result-fields { display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .result-fields dd { font-size: 15px; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .result-actions { flex-direction: row; flex-wrap: wrap; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .result-actions :is(button, a) { flex: 1 1 160px; width: auto; }
|
||||||
|
@container workbench (max-width: 860px) {
|
||||||
|
body[data-screen=archives][data-archive-detail=open] .registry-workspace {
|
||||||
|
display: flex; flex-direction: column; height: auto; max-height: none; overflow: visible;
|
||||||
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] .registry-workspace #registration-result { order: 0; flex: none; overflow: visible; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] .registry-workspace .history-panel {
|
||||||
|
order: 1; height: 320px; min-height: 0; max-height: 320px; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .record-result { display: flex; flex-direction: column; align-items: stretch; }
|
||||||
|
body[data-screen=archives][data-archive-detail=open] #registration-result .qr-stage { width: 180px; align-self: flex-start; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,6 +6,15 @@
|
|||||||
.mc-layout-b .mc-map-toolstrip{background:var(--work-panel);border-color:var(--work-line)}
|
.mc-layout-b .mc-map-toolstrip{background:var(--work-panel);border-color:var(--work-line)}
|
||||||
.mc-layout-b .mc-map-toolstrip button{color:var(--work-text)}
|
.mc-layout-b .mc-map-toolstrip button{color:var(--work-text)}
|
||||||
.rt-target-label{color:#e4f0ff!important;background:#10223ed9;border:1px solid #8aaccb50;border-radius:6px;padding:4px 7px;font-size:13px}
|
.rt-target-label{color:#e4f0ff!important;background:#10223ed9;border:1px solid #8aaccb50;border-radius:6px;padding:4px 7px;font-size:13px}
|
||||||
|
.rt-target-pin{display:flex;flex-direction:column;align-items:center;gap:4px;pointer-events:none}
|
||||||
|
.rt-target-pin .rt-target-label{max-width:220px}
|
||||||
|
.rt-drone-icon{display:grid;place-items:center;width:36px;height:36px;border-radius:50%;color:#d7f2ff;background:#0c2036ee;border:2px solid #7ec8ff;box-shadow:0 0 0 4px #38bdf833,0 8px 16px #0008}
|
||||||
|
.rt-drone-icon svg{display:block}
|
||||||
|
.rt-drone-point{width:8px;height:8px;margin-top:-2px;border-radius:50%;background:#fff;box-shadow:0 0 0 3px #38bdf8}
|
||||||
|
.rt-target-pin[data-list-kind=black] .rt-drone-icon{color:#ffd4ce;border-color:#ffb1a9;box-shadow:0 0 0 4px #ff6b6333,0 8px 16px #0008}
|
||||||
|
.rt-target-pin[data-list-kind=black] .rt-drone-point{box-shadow:0 0 0 3px #ffb1a9}
|
||||||
|
.rt-target-pin[data-list-kind=white] .rt-drone-icon{color:#dff8ee;border-color:#9edac1;box-shadow:0 0 0 4px #69bd9733,0 8px 16px #0008}
|
||||||
|
.rt-target-pin[data-list-kind=white] .rt-drone-point{box-shadow:0 0 0 3px #9edac1}
|
||||||
.setting-row label{color:var(--work-text)!important;font-size:14px}
|
.setting-row label{color:var(--work-text)!important;font-size:14px}
|
||||||
.live-events{display:flex;flex-wrap:wrap;gap:10px 28px;list-style:none;padding:10px 0;margin:0;font-size:12px;line-height:1.8;color:var(--work-muted)}
|
.live-events{display:flex;flex-wrap:wrap;gap:10px 28px;list-style:none;padding:10px 0;margin:0;font-size:12px;line-height:1.8;color:var(--work-muted)}
|
||||||
.live-events li{border-left:1px solid var(--work-line);padding-left:12px}
|
.live-events li{border-left:1px solid var(--work-line);padding-left:12px}
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
<div class="gf-stage"><div id="geofence-map" aria-label="电子围栏地图"></div><header class="gf-heading"><h1>电子围栏工作台</h1><p>二维本地监测 · 白名单免告警 · 不控制无人机</p><div class="gf-tools"><button type="button" id="gf-circle">+ 圆形</button><button type="button" id="gf-polygon">⌁ 多边形</button><button type="button" id="gf-finish" hidden>完成绘制</button><button type="button" id="gf-cancel" hidden>取消绘制</button><button type="button" id="gf-imagery">影像</button><button type="button" id="gf-road">路网</button></div><p id="gf-map-hint" role="status">选择围栏,或新建一个监测区域。</p></header><aside class="gf-drawer" aria-label="围栏管理"><header class="gf-drawer-heading"><h2>围栏管理</h2><button type="button" id="gf-new" disabled>+ 新建</button></header><div class="gf-scroll"><div class="gf-section-title"><span>已保存围栏</span><button type="button" id="gf-refresh">刷新</button></div><div id="gf-list" role="group" aria-label="围栏目录"><p>正在读取围栏…</p></div><form id="gf-form" hidden><div class="gf-section-title">编辑围栏</div><label for="gf-name">围栏名称</label><input id="gf-name" maxlength="40" required placeholder="例如:园区核心区"><label class="gf-switch"><input id="gf-enabled" type="checkbox" checked>启用监测</label><label for="gf-shape">范围形状</label><select id="gf-shape"><option value="circle">圆形</option><option value="polygon">多边形</option></select><div id="gf-circle-fields"><div class="gf-field-row"><label>中心经度<input id="gf-longitude" type="number" step="any" min="-180" max="180" required></label><label>中心纬度<input id="gf-latitude" type="number" step="any" min="-90" max="90" required></label></div><label for="gf-radius">半径(米)</label><input id="gf-radius" type="number" min="1" max="1000000" step="any" required></div><div id="gf-polygon-fields" hidden><label for="gf-vertices">顶点坐标(JSON 数组)</label><textarea id="gf-vertices" rows="4" spellcheck="false" aria-describedby="gf-vertices-help"></textarea><p id="gf-vertices-help">格式:[[经度,纬度],…],3–128点,不重复首点;也可在地图逐点绘制或拖动顶点。</p></div><p class="gf-explain">边界视为内部;首次观测已在区域内会告警。离开后再次进入可重新触发。停用只影响后续事件,历史记录保留。</p><div class="gf-editor-actions"><button type="submit" id="gf-save" class="primary">保存围栏</button><button type="button" id="gf-locate">定位</button><button type="button" id="gf-delete">删除</button></div></form><div class="gf-section-title"><h3>进入告警</h3><button type="button" id="gf-events-refresh">刷新</button></div><p class="gf-explain" id="gf-events-scope">显示全部围栏事件;选择围栏后仅显示该围栏。</p><ol id="gf-events"><li>正在读取历史事件…</li></ol><button type="button" id="gf-events-more" hidden>加载更早记录</button></div><footer class="gf-footer"><p id="gf-message" role="status">围栏及告警保存在本机服务端。</p></footer></aside><p class="gf-map-status" id="gf-map-status" role="status">正在读取地图状态…</p></div>
|
<div class="gf-stage"><div id="geofence-map" aria-label="电子围栏地图"></div><header class="gf-heading"><h1>电子围栏工作台</h1><p>二维本地监测 · 白名单免告警 · 不控制无人机</p><div class="gf-tools"><button type="button" id="gf-circle">+ 圆形</button><button type="button" id="gf-polygon">⌁ 多边形</button><button type="button" id="gf-finish" hidden>完成绘制</button><button type="button" id="gf-cancel" hidden>取消绘制</button><button type="button" id="gf-imagery">影像</button><button type="button" id="gf-road">路网</button></div><p id="gf-map-hint" role="status">选择围栏,或新建一个监测区域。</p></header><aside class="gf-drawer" aria-label="围栏管理"><header class="gf-drawer-heading"><h2>围栏管理</h2><button type="button" id="gf-new" disabled>+ 新建</button></header><div class="gf-scroll"><div class="gf-section-title"><span>已保存围栏</span><button type="button" id="gf-refresh">刷新</button></div><div id="gf-list" role="group" aria-label="围栏目录"><p>正在读取围栏…</p></div><form id="gf-form" hidden><div class="gf-section-title">编辑围栏</div><label for="gf-name">围栏名称</label><input id="gf-name" maxlength="40" required placeholder="例如:园区核心区"><label class="gf-switch"><input id="gf-enabled" type="checkbox" checked>启用监测</label><label for="gf-shape">范围形状</label><select id="gf-shape"><option value="circle">圆形</option><option value="polygon">多边形</option></select><div id="gf-circle-fields"><div class="gf-field-row"><label>中心经度<input id="gf-longitude" type="number" step="any" min="-180" max="180" required></label><label>中心纬度<input id="gf-latitude" type="number" step="any" min="-90" max="90" required></label></div><label for="gf-radius">半径(米)</label><input id="gf-radius" type="number" min="1" max="1000000" step="any" required></div><div id="gf-polygon-fields" hidden><label for="gf-vertices">顶点坐标(JSON 数组)</label><textarea id="gf-vertices" rows="4" spellcheck="false" aria-describedby="gf-vertices-help"></textarea><p id="gf-vertices-help">格式:[[经度,纬度],…],3–128点,不重复首点;也可在地图逐点绘制或拖动顶点。</p></div><div class="gf-editor-actions"><button type="submit" id="gf-save" class="primary">保存围栏</button><button type="button" id="gf-locate">定位</button><button type="button" id="gf-delete">删除</button></div></form><div class="gf-section-title"><h3>进入告警</h3><button type="button" id="gf-events-refresh">刷新</button></div><ol id="gf-events"><li>正在读取历史事件…</li></ol><button type="button" id="gf-events-more" hidden>加载更早记录</button></div><footer class="gf-footer"><p id="gf-message" role="status">围栏及告警保存在本机服务端。</p></footer></aside><p class="gf-map-status" id="gf-map-status" role="status">正在读取地图状态…</p></div>
|
||||||
@@ -18,6 +18,7 @@ struct State {
|
|||||||
before: Option<u64>,
|
before: Option<u64>,
|
||||||
events: Vec<Alert>,
|
events: Vec<Alert>,
|
||||||
drawing: bool,
|
drawing: bool,
|
||||||
|
draw_mode: String,
|
||||||
}
|
}
|
||||||
type Shared = Rc<RefCell<State>>;
|
type Shared = Rc<RefCell<State>>;
|
||||||
thread_local! {static STATE:RefCell<Option<Shared>>=const{RefCell::new(None)};}
|
thread_local! {static STATE:RefCell<Option<Shared>>=const{RefCell::new(None)};}
|
||||||
@@ -83,6 +84,13 @@ fn visible() -> bool {
|
|||||||
.body()
|
.body()
|
||||||
.is_some_and(|b| b.get_attribute("data-screen").as_deref() == Some("geofences"))
|
.is_some_and(|b| b.get_attribute("data-screen").as_deref() == Some("geofences"))
|
||||||
}
|
}
|
||||||
|
fn fences_changed() {
|
||||||
|
if let Some(window) = web_sys::window()
|
||||||
|
&& let Ok(event) = web_sys::Event::new("rid-fences-changed")
|
||||||
|
{
|
||||||
|
let _ = window.dispatch_event(&event);
|
||||||
|
}
|
||||||
|
}
|
||||||
fn message(value: &str, error: bool) {
|
fn message(value: &str, error: bool) {
|
||||||
text("gf-message", value);
|
text("gf-message", value);
|
||||||
if let Some(e) = el("gf-message") {
|
if let Some(e) = el("gf-message") {
|
||||||
@@ -113,10 +121,14 @@ fn buttons(s: &Shared) {
|
|||||||
for id in ["gf-new", "gf-circle", "gf-polygon"] {
|
for id in ["gf-new", "gf-circle", "gf-polygon"] {
|
||||||
disabled(id, s.busy || s.snapshot.is_none());
|
disabled(id, s.busy || s.snapshot.is_none());
|
||||||
}
|
}
|
||||||
|
let polygon_drawing = s.draw_mode == "polygon";
|
||||||
for id in ["gf-save", "gf-delete", "gf-locate"] {
|
for id in ["gf-save", "gf-delete", "gf-locate"] {
|
||||||
disabled(
|
disabled(
|
||||||
id,
|
id,
|
||||||
s.busy || s.draft.is_none() || s.snapshot.is_none() || (id == "gf-save" && s.drawing),
|
s.busy
|
||||||
|
|| s.draft.is_none()
|
||||||
|
|| s.snapshot.is_none()
|
||||||
|
|| (id == "gf-save" && polygon_drawing),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for id in ["gf-name", "gf-enabled", "gf-shape", "gf-vertices"] {
|
for id in ["gf-name", "gf-enabled", "gf-shape", "gf-vertices"] {
|
||||||
@@ -445,7 +457,7 @@ fn read_fields(s: &Shared) -> Result<Fence, String> {
|
|||||||
Ok(draft)
|
Ok(draft)
|
||||||
}
|
}
|
||||||
async fn save(s: Shared) {
|
async fn save(s: Shared) {
|
||||||
if s.borrow().busy {
|
if s.borrow().busy || s.borrow().draw_mode == "polygon" {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let draft = match read_fields(&s) {
|
let draft = match read_fields(&s) {
|
||||||
@@ -456,6 +468,7 @@ async fn save(s: Shared) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let revision = s.borrow().draft_revision;
|
let revision = s.borrow().draft_revision;
|
||||||
|
map("tool", json!(""));
|
||||||
s.borrow_mut().busy = true;
|
s.borrow_mut().busy = true;
|
||||||
buttons(&s);
|
buttons(&s);
|
||||||
let result = request(
|
let result = request(
|
||||||
@@ -477,6 +490,7 @@ async fn save(s: Shared) {
|
|||||||
paint_list(&s);
|
paint_list(&s);
|
||||||
render_map(&s);
|
render_map(&s);
|
||||||
message("围栏已保存,服务端监测已生效。", false);
|
message("围栏已保存,服务端监测已生效。", false);
|
||||||
|
fences_changed();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => message(
|
Err(e) => message(
|
||||||
@@ -537,6 +551,7 @@ async fn delete(s: Shared) {
|
|||||||
render_map(&s);
|
render_map(&s);
|
||||||
spawn_local(events(s.clone(), false));
|
spawn_local(events(s.clone(), false));
|
||||||
message("围栏已删除,历史告警保留。", false);
|
message("围栏已删除,历史告警保留。", false);
|
||||||
|
fences_changed();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => message(&format!("{e};草稿已保留。"), true),
|
Err(e) => message(&format!("{e};草稿已保留。"), true),
|
||||||
@@ -761,14 +776,19 @@ pub fn init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"rid-fence-mode" => {
|
"rid-fence-mode" => {
|
||||||
let active = v["mode"].as_str().is_some_and(|v| !v.is_empty());
|
let mode = v["mode"].as_str().unwrap_or("").to_owned();
|
||||||
s.borrow_mut().drawing = active;
|
let active = !mode.is_empty();
|
||||||
|
{
|
||||||
|
let mut state = s.borrow_mut();
|
||||||
|
state.drawing = active;
|
||||||
|
state.draw_mode = mode.clone();
|
||||||
|
}
|
||||||
hidden("gf-cancel", !active);
|
hidden("gf-cancel", !active);
|
||||||
hidden("gf-finish", v["mode"] != "polygon");
|
hidden("gf-finish", mode != "polygon");
|
||||||
text(
|
text(
|
||||||
"gf-map-hint",
|
"gf-map-hint",
|
||||||
if v["mode"] == "circle" {
|
if mode == "circle" {
|
||||||
"点击地图设置圆心;也可取消绘制。"
|
"点击地图可移动圆心;当前圆形可直接保存。"
|
||||||
} else if active {
|
} else if active {
|
||||||
"逐点点击地图,至少3点后完成;Escape取消。"
|
"逐点点击地图,至少3点后完成;Escape取消。"
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -12,6 +12,36 @@ use std::{
|
|||||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||||
use wasm_bindgen_futures::spawn_local;
|
use wasm_bindgen_futures::spawn_local;
|
||||||
|
|
||||||
|
fn publish_fences(entries: &Value) -> bool {
|
||||||
|
if !entries.is_array() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Ok(text) = serde_json::to_string(entries) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Ok(parsed) = js_sys::JSON::parse(&text) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
map_call("setFences", &[parsed]).is_ok()
|
||||||
|
}
|
||||||
|
async fn sync_fences(seen: &Cell<Option<u64>>) {
|
||||||
|
let Ok(response) = gloo_net::http::Request::get("/api/geofences").send().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if !response.ok() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Ok(value) = response.json::<Value>().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let revision = value["revision"].as_u64();
|
||||||
|
if seen.get() == revision {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if publish_fences(&value["entries"]) {
|
||||||
|
seen.set(revision);
|
||||||
|
}
|
||||||
|
}
|
||||||
pub(super) fn map_call(method: &str, values: &[JsValue]) -> Result<JsValue, JsValue> {
|
pub(super) fn map_call(method: &str, values: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||||
let window = web_sys::window().ok_or("browser unavailable")?;
|
let window = web_sys::window().ok_or("browser unavailable")?;
|
||||||
let map = js_sys::Reflect::get(&window, &"ridMap".into())?;
|
let map = js_sys::Reflect::get(&window, &"ridMap".into())?;
|
||||||
@@ -208,7 +238,7 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
|||||||
if selected.get_untracked() != id {
|
if selected.get_untracked() != id {
|
||||||
selected.set(id.clone());
|
selected.set(id.clone());
|
||||||
}
|
}
|
||||||
let coords = map_call("select", &[id.into()])
|
let coords = map_call("select", &[id.clone().into()])
|
||||||
.ok()
|
.ok()
|
||||||
.map(|v| js_sys::Array::from(&v));
|
.map(|v| js_sys::Array::from(&v));
|
||||||
position.set(coords.and_then(|a| {
|
position.set(coords.and_then(|a| {
|
||||||
@@ -223,6 +253,14 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
|||||||
];
|
];
|
||||||
p[..2].iter().all(|x| x.is_finite()).then_some(p)
|
p[..2].iter().all(|x| x.is_finite()).then_some(p)
|
||||||
}));
|
}));
|
||||||
|
if position.get_untracked().is_none()
|
||||||
|
&& let Some([lon, lat]) = details.with(|d| raw_focus(d.get(&id)))
|
||||||
|
{
|
||||||
|
let point = js_sys::Array::new();
|
||||||
|
point.push(&JsValue::from_f64(lon));
|
||||||
|
point.push(&JsValue::from_f64(lat));
|
||||||
|
let _ = map_call("focusRaw", &[point.into()]);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let active_black = Memo::new(move |_| {
|
let active_black = Memo::new(move |_| {
|
||||||
let kinds = classification.get();
|
let kinds = classification.get();
|
||||||
@@ -249,7 +287,9 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
let stopped = Rc::new(Cell::new(false));
|
let stopped = Rc::new(Cell::new(false));
|
||||||
|
let fence_seen = Rc::new(Cell::new(None));
|
||||||
let alert_stop = stopped.clone();
|
let alert_stop = stopped.clone();
|
||||||
|
let fence_poll = fence_seen.clone();
|
||||||
spawn_local(async move {
|
spawn_local(async move {
|
||||||
let mut cursor = 0u64;
|
let mut cursor = 0u64;
|
||||||
let mut failed = false;
|
let mut failed = false;
|
||||||
@@ -327,9 +367,25 @@ pub fn Realtime(lists: Lists) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
last_health = warning;
|
last_health = warning;
|
||||||
}
|
}
|
||||||
|
sync_fences(&fence_poll).await;
|
||||||
TimeoutFuture::new(1000).await;
|
TimeoutFuture::new(1000).await;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
let fence_refresh = fence_seen;
|
||||||
|
let refresh = Closure::<dyn FnMut(web_sys::Event)>::new(move |_| {
|
||||||
|
let seen = fence_refresh.clone();
|
||||||
|
spawn_local(async move {
|
||||||
|
seen.set(None);
|
||||||
|
sync_fences(&seen).await;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if let Some(window) = web_sys::window() {
|
||||||
|
let _ = window.add_event_listener_with_callback(
|
||||||
|
"rid-fences-changed",
|
||||||
|
refresh.as_ref().unchecked_ref(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
refresh.forget();
|
||||||
let worker_holder: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
|
let worker_holder: Rc<RefCell<Option<web_sys::Worker>>> = Rc::new(RefCell::new(None));
|
||||||
let stop = stopped.clone();
|
let stop = stopped.clone();
|
||||||
let workers = worker_holder.clone();
|
let workers = worker_holder.clone();
|
||||||
@@ -761,6 +817,19 @@ fn device_detail_rows(observation: Option<&Value>) -> Vec<(&'static str, String)
|
|||||||
rows
|
rows
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn raw_focus(observation: Option<&Value>) -> Option<[f64; 2]> {
|
||||||
|
let point = observation?
|
||||||
|
.get("telemetry")?
|
||||||
|
.get("raw_position")?
|
||||||
|
.as_array()?;
|
||||||
|
let lon = point.first()?.as_f64()?;
|
||||||
|
let lat = point.get(1)?.as_f64()?;
|
||||||
|
(lon.is_finite()
|
||||||
|
&& lat.is_finite()
|
||||||
|
&& (-180.0..=180.0).contains(&lon)
|
||||||
|
&& (-90.0..=90.0).contains(&lat))
|
||||||
|
.then_some([lon, lat])
|
||||||
|
}
|
||||||
fn position_label(observation: Option<&Value>) -> &'static str {
|
fn position_label(observation: Option<&Value>) -> &'static str {
|
||||||
match observation {
|
match observation {
|
||||||
Some(o) if o["longitude"].is_number() && o["latitude"].is_number() => "已定位",
|
Some(o) if o["longitude"].is_number() && o["latitude"].is_number() => "已定位",
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
<div class="rx-page">
|
<div class="rx-page">
|
||||||
<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>
|
<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="接收机列表区域">
|
<section class="rx-surface" aria-label="接收机列表区域">
|
||||||
<p id="rx-error" class="rx-error" role="alert" hidden></p><div id="rx-cards" class="rx-cards"></div><p id="rx-empty" hidden>没有匹配的接收机。</p>
|
<p id="rx-error" class="rx-error" role="alert" hidden></p>
|
||||||
<p class="rx-footnote">切换菜单不停止后台接收。停用、修改连接或删除只影响当前接收机。</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>
|
||||||
</section>
|
</section>
|
||||||
|
<div id="rx-pop" class="rx-pop" role="dialog" aria-label="其余提示" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
<dialog id="rx-drawer" class="rx-drawer" aria-labelledby="rx-title">
|
<dialog id="rx-drawer" class="rx-drawer" aria-labelledby="rx-title">
|
||||||
<header class="rx-drawer-header"><h2 id="rx-title" hidden>接收机</h2><div class="rx-tabs" role="group" aria-label="设备详情内容"><button id="rx-config-tab" type="button" aria-pressed="true">连接配置</button><button id="rx-diagnostic-tab" type="button" aria-pressed="false">接收诊断</button></div><button id="rx-close" type="button" aria-label="关闭设备详情">×</button></header>
|
<header class="rx-drawer-header"><h2 id="rx-title" hidden>接收机</h2><div class="rx-tabs" role="group" aria-label="设备详情内容"><button id="rx-config-tab" type="button" aria-pressed="true">连接配置</button><button id="rx-diagnostic-tab" type="button" aria-pressed="false">接收诊断</button></div><button id="rx-close" type="button" aria-label="关闭设备详情">×</button></header>
|
||||||
|
|||||||
@@ -11,12 +11,13 @@
|
|||||||
<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>
|
<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>
|
||||||
<section class="registry-group"><div class="registry-group-heading"><h2>登记编号</h2><span>留空,保存成功后生成</span></div><div class="registration-number"><div class="registration-field"><label for="uas-code">FPV 编号 <small>选填</small></label><div class="registration-prefix"><span aria-hidden="true">FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" aria-describedby="fpv-hint uas-code-error" placeholder="选填 8 位数字 · 保存后生成"></div><p id="uas-code-error" class="form-message error" role="alert" hidden></p></div><p id="fpv-hint" class="registry-help">已有编号仅填写后 8 位数字。<br>留空时,保存成功后自动生成并回填;相同 SN 沿用原编号。</p></div></section>
|
<section class="registry-group"><div class="registry-group-heading"><h2>登记编号</h2><span>留空,保存成功后生成</span></div><div class="registration-number"><div class="registration-field"><label for="uas-code">FPV 编号 <small>选填</small></label><div class="registration-prefix"><span aria-hidden="true">FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" aria-describedby="fpv-hint uas-code-error" placeholder="选填 8 位数字 · 保存后生成"></div><p id="uas-code-error" class="form-message error" role="alert" hidden></p></div><p id="fpv-hint" class="registry-help">已有编号仅填写后 8 位数字。<br>留空时,保存成功后自动生成并回填;相同 SN 沿用原编号。</p></div></section>
|
||||||
<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>
|
<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"><h2 id="result-title">二维码与核验</h2>
|
<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 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>
|
<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>
|
<div class="uas-display" id="display-uas"></div>
|
||||||
<dl class="result-fields"><div><dt>Serial No.</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人</dt><dd id="display-owner"></dd></div></dl>
|
<dl class="result-fields"><div><dt>模块 SN</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人 / 备注</dt><dd id="display-owner"></dd></div></dl>
|
||||||
<div class="saved-photos" id="saved-photos" hidden>
|
<div class="saved-photos" id="saved-photos" hidden>
|
||||||
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
|
<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>
|
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
|
||||||
|
|||||||
@@ -292,9 +292,67 @@ async fn load(state: Shared, mut page: u64) -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fn on_screen(name: &str) -> bool {
|
||||||
|
document()
|
||||||
|
.body()
|
||||||
|
.and_then(|body| body.get_attribute("data-screen"))
|
||||||
|
.as_deref()
|
||||||
|
== Some(name)
|
||||||
|
}
|
||||||
|
fn archive_detail_open() -> bool {
|
||||||
|
document()
|
||||||
|
.body()
|
||||||
|
.and_then(|body| body.get_attribute("data-archive-detail"))
|
||||||
|
.as_deref()
|
||||||
|
== Some("open")
|
||||||
|
}
|
||||||
|
fn conceal_registration_form() {
|
||||||
|
let Ok(nodes) = document().query_selector_all(".registration-editor") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for index in 0..nodes.length() {
|
||||||
|
if let Some(node) = nodes.item(index) {
|
||||||
|
let _ = node.unchecked_into::<Element>().set_attribute("hidden", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn open_saved_archive(state: &Shared, row: Value) {
|
||||||
|
if !on_screen("archives") {
|
||||||
|
crate::workspace::navigate("archives");
|
||||||
|
}
|
||||||
|
conceal_registration_form();
|
||||||
|
hidden("registration-result", false);
|
||||||
|
if let Some(body) = document().body() {
|
||||||
|
let _ = body.set_attribute("data-archive-detail", "open");
|
||||||
|
}
|
||||||
|
draw(state, row);
|
||||||
|
}
|
||||||
|
fn close_archive_detail(state: &Shared) {
|
||||||
|
hidden("registration-result", true);
|
||||||
|
if let Some(body) = document().body() {
|
||||||
|
let _ = body.remove_attribute("data-archive-detail");
|
||||||
|
}
|
||||||
|
let id = state
|
||||||
|
.borrow()
|
||||||
|
.active
|
||||||
|
.as_ref()
|
||||||
|
.map(|row| format!("view-{}", field(row, "id")));
|
||||||
|
if let Some(id) = id {
|
||||||
|
focus(&id);
|
||||||
|
}
|
||||||
|
}
|
||||||
fn draw(state: &Shared, record: Value) {
|
fn draw(state: &Shared, record: Value) {
|
||||||
hidden("empty-result", true);
|
hidden("empty-result", true);
|
||||||
hidden("record-result", false);
|
hidden("record-result", false);
|
||||||
|
text(
|
||||||
|
"result-title",
|
||||||
|
if archive_detail_open() {
|
||||||
|
"档案详情"
|
||||||
|
} else {
|
||||||
|
"二维码与核验"
|
||||||
|
},
|
||||||
|
);
|
||||||
|
hidden("close-archive-detail", !archive_detail_open());
|
||||||
text(
|
text(
|
||||||
"result-context",
|
"result-context",
|
||||||
&format!("正在查看:{} · 已保存档案", field(&record, "serialNo")),
|
&format!("正在查看:{} · 已保存档案", field(&record, "serialNo")),
|
||||||
@@ -306,7 +364,15 @@ fn draw(state: &Shared, record: Value) {
|
|||||||
("display-owner", "ownerName"),
|
("display-owner", "ownerName"),
|
||||||
("display-url", "qrUrl"),
|
("display-url", "qrUrl"),
|
||||||
] {
|
] {
|
||||||
text(id, field(&record, key));
|
let value = field(&record, key);
|
||||||
|
text(
|
||||||
|
id,
|
||||||
|
if value.is_empty() && matches!(key, "modelName" | "ownerName") {
|
||||||
|
"—"
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (id, key) in [
|
for (id, key) in [
|
||||||
("open-card", "archiveUrl"),
|
("open-card", "archiveUrl"),
|
||||||
@@ -661,13 +727,14 @@ pub fn init() {
|
|||||||
for event in ["rid-workspace-view", "focus"] {
|
for event in ["rid-workspace-view", "focus"] {
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
let refresh = Closure::<dyn FnMut(Event)>::new(move |_| {
|
let refresh = Closure::<dyn FnMut(Event)>::new(move |_| {
|
||||||
if state.borrow().busy
|
let screen = document()
|
||||||
|| document()
|
|
||||||
.body()
|
.body()
|
||||||
.and_then(|body| body.get_attribute("data-screen"))
|
.and_then(|body| body.get_attribute("data-screen"));
|
||||||
.as_deref()
|
if screen.as_deref() == Some("register") {
|
||||||
!= Some("archives")
|
text("result-title", "二维码与核验");
|
||||||
{
|
hidden("close-archive-detail", true);
|
||||||
|
}
|
||||||
|
if state.borrow().busy || screen.as_deref() != Some("archives") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
@@ -952,6 +1019,10 @@ pub fn init() {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if id == "close-archive-detail" {
|
||||||
|
close_archive_detail(&state);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if let Some(action) = t.get_attribute("data-action") {
|
if let Some(action) = t.get_attribute("data-action") {
|
||||||
let Some(card) = t.closest("[data-id]").ok().flatten() else {
|
let Some(card) = t.closest("[data-id]").ok().flatten() else {
|
||||||
return;
|
return;
|
||||||
@@ -975,13 +1046,11 @@ pub fn init() {
|
|||||||
close_menu(&state, true);
|
close_menu(&state, true);
|
||||||
if action == "edit" {
|
if action == "edit" {
|
||||||
state.borrow_mut().edit_return = format!("more-{record_id}");
|
state.borrow_mut().edit_return = format!("more-{record_id}");
|
||||||
crate::workspace::navigate("register");
|
|
||||||
edit(&state, row);
|
edit(&state, row);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if action == "qr" || action == "view" {
|
if action == "qr" || action == "view" {
|
||||||
crate::workspace::navigate("register");
|
open_saved_archive(&state, row);
|
||||||
draw(&state, row);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if action == "delete" {
|
if action == "delete" {
|
||||||
@@ -1007,8 +1076,15 @@ pub fn init() {
|
|||||||
if is_active {
|
if is_active {
|
||||||
state.borrow_mut().active = None;
|
state.borrow_mut().active = None;
|
||||||
hidden("record-result", true);
|
hidden("record-result", true);
|
||||||
|
if on_screen("archives") {
|
||||||
|
hidden("registration-result", true);
|
||||||
|
if let Some(body) = document().body() {
|
||||||
|
let _ = body.remove_attribute("data-archive-detail");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
hidden("empty-result", false);
|
hidden("empty-result", false);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
let page = state.borrow().page;
|
let page = state.borrow().page;
|
||||||
if let Err(e) = load(state, page).await {
|
if let Err(e) = load(state, page).await {
|
||||||
message("history-message", &e, true);
|
message("history-message", &e, true);
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -425,6 +425,7 @@ fn show(view: &str, realtime: bool) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
if let Some(body) = document().body() {
|
if let Some(body) = document().body() {
|
||||||
|
let _ = body.remove_attribute("data-archive-detail");
|
||||||
let _ = body.set_attribute("data-screen", view);
|
let _ = body.set_attribute("data-screen", view);
|
||||||
}
|
}
|
||||||
if let Some(window) = web_sys::window()
|
if let Some(window) = web_sys::window()
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ try{
|
|||||||
let fences=await(await fetch(base+'/api/geofences')).json();const circleId=fences.entries[0].id;
|
let fences=await(await fetch(base+'/api/geofences')).json();const circleId=fences.entries[0].id;
|
||||||
let seq=0;async function ingest(target_id,lon,lat){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify([{target_id,receiver_id:'TEST',source_epoch:1,sequence:++seq,longitude:lon,latitude:lat,altitude_m:100,heading_deg:30}])});assert.equal(r.status,200);}
|
let seq=0;async function ingest(target_id,lon,lat){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify([{target_id,receiver_id:'TEST',source_epoch:1,sequence:++seq,longitude:lon,latitude:lat,altitude_m:100,heading_deg:30}])});assert.equal(r.status,200);}
|
||||||
await save('WHITE-FENCE','white');await ingest('WHITE-FENCE',120,30);await ingest('OTHER-FENCE',120,30);await wait(400);await page.locator('#gf-events-refresh').click();await page.locator('#gf-events li').filter({hasText:'OTHER-FENCE'}).waitFor();assert.equal(await page.locator('#gf-events li').filter({hasText:'WHITE-FENCE'}).count(),0);
|
await save('WHITE-FENCE','white');await ingest('WHITE-FENCE',120,30);await ingest('OTHER-FENCE',120,30);await wait(400);await page.locator('#gf-events-refresh').click();await page.locator('#gf-events li').filter({hasText:'OTHER-FENCE'}).waitFor();assert.equal(await page.locator('#gf-events li').filter({hasText:'WHITE-FENCE'}).count(),0);
|
||||||
await page.locator('#gf-circle').click();await page.locator('#geofence-map canvas').first().click({position:{x:600,y:300}});await page.waitForFunction(()=>window.ridGeofences.metrics().mode==='');assert.notEqual(await page.locator('#gf-longitude').inputValue(),'120');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();
|
await page.locator('#gf-circle').click();assert.equal(await page.evaluate(()=>window.ridGeofences.metrics().mode),'circle');assert.equal(await page.locator('#gf-save').isDisabled(),false,'绘制中的圆形必须可以保存');await page.locator('#geofence-map canvas').first().click({position:{x:600,y:300}});await page.waitForFunction(()=>window.ridGeofences.metrics().mode==='');assert.notEqual(await page.locator('#gf-longitude').inputValue(),'120');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();
|
||||||
await page.locator('#gf-new').click();await page.locator('#gf-name').fill('多边形区域');await page.locator('#gf-polygon').click();for(const p of [{x:620,y:350},{x:820,y:350},{x:720,y:520}])await page.locator('#geofence-map canvas').first().click({position:p});await page.locator('#gf-finish').click();assert.equal(await page.locator('#gf-shape').inputValue(),'polygon');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();assert.equal(await page.locator('#gf-list .gf-entry').count(),2);
|
await page.locator('#gf-new').click();await page.locator('#gf-name').fill('多边形区域');await page.locator('#gf-polygon').click();for(const p of [{x:620,y:350},{x:820,y:350},{x:720,y:520}])await page.locator('#geofence-map canvas').first().click({position:p});await page.locator('#gf-finish').click();assert.equal(await page.locator('#gf-shape').inputValue(),'polygon');await page.locator('#gf-save').click();await page.locator('#gf-message').filter({hasText:'已保存'}).waitFor();assert.equal(await page.locator('#gf-list .gf-entry').count(),2);
|
||||||
// Invalid vertex drag restores the handle and never changes persisted geometry.
|
// Invalid vertex drag restores the handle and never changes persisted geometry.
|
||||||
const beforeDrag=await page.locator('#gf-vertices').inputValue();const h1=await page.locator('.gf-handle').nth(0).boundingBox(),h2=await page.locator('.gf-handle').nth(1).boundingBox();
|
const beforeDrag=await page.locator('#gf-vertices').inputValue();const h1=await page.locator('.gf-handle').nth(0).boundingBox(),h2=await page.locator('.gf-handle').nth(1).boundingBox();
|
||||||
@@ -45,6 +45,6 @@ try{
|
|||||||
await page.locator('#gf-list .gf-entry').filter({hasText:'远端更新'}).click();
|
await page.locator('#gf-list .gf-entry').filter({hasText:'远端更新'}).click();
|
||||||
for(const [width,height]of [[1600,1000],[1366,768],[900,700],[390,844],[1200,560]]){await page.setViewportSize({width,height});await wait(200);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.locator('#gf-save').scrollIntoViewIfNeeded();const b=await page.locator('#gf-save').boundingBox();assert.ok(b.width>20&&b.x>=0&&b.x+b.width<=width);await page.screenshot({path:path.join(root,'fence-'+width+'x'+height+'.png'),fullPage:true});}
|
for(const [width,height]of [[1600,1000],[1366,768],[900,700],[390,844],[1200,560]]){await page.setViewportSize({width,height});await wait(200);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.locator('#gf-save').scrollIntoViewIfNeeded();const b=await page.locator('#gf-save').boundingBox();assert.ok(b.width>20&&b.x>=0&&b.x+b.width<=width);await page.screenshot({path:path.join(root,'fence-'+width+'x'+height+'.png'),fullPage:true});}
|
||||||
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#gf-save').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.screenshot({path:path.join(root,'fence-200percent.png'),fullPage:true});await page.evaluate(()=>document.documentElement.style.zoom='');await page.locator('#gf-delete').click();await page.locator('#gf-message').filter({hasText:'已删除'}).waitFor();assert.equal((await(await fetch(base+'/api/geofences')).json()).entries.length,1);
|
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#gf-save').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await page.screenshot({path:path.join(root,'fence-200percent.png'),fullPage:true});await page.evaluate(()=>document.documentElement.style.zoom='');await page.locator('#gf-delete').click();await page.locator('#gf-message').filter({hasText:'已删除'}).waitFor();assert.equal((await(await fetch(base+'/api/geofences')).json()).entries.length,1);
|
||||||
await page.getByRole('button',{name:'实时目标工作台',exact:true}).click();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);assert.equal(await page.locator('.mc-map-toolstrip').count(),0);
|
await page.getByRole('button',{name:'实时目标工作台',exact:true}).click();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);await page.waitForFunction(()=>window.ridMap.metrics().fences>=1);const fenceLabels=await page.locator('.rt-fence-label').allTextContents();assert.ok(fenceLabels.length>=1,JSON.stringify(fenceLabels));assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);assert.equal(await page.locator('.mc-map-toolstrip').count(),0);
|
||||||
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);report={status:'PASS',root,exe,checks:['A sidebar navigation','default15','circle numeric and map edit','polygon drawing','invalid drag restores vertex','safe names','white exemption','persistent events','Escape','invalid geometry','enable/disable','conflict preserves draft','page change preserves draft','failed save preserves draft','five viewports','delete','realtime preserved'],errors,csp};console.log(JSON.stringify(report));
|
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);report={status:'PASS',root,exe,checks:['A sidebar navigation','default15','circle numeric and map edit','circle save while drawing','polygon drawing','invalid drag restores vertex','safe names','white exemption','persistent events','Escape','invalid geometry','enable/disable','conflict preserves draft','page change preserves draft','failed save preserves draft','five viewports','delete','realtime shows saved fence'],errors,csp};console.log(JSON.stringify(report));
|
||||||
}catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify(errors));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png'),fullPage:true}).catch(()=>{});}throw error;}finally{if(browser)await browser.close();await stop();await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output);}
|
}catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify(errors));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png'),fullPage:true}).catch(()=>{});}throw error;}finally{if(browser)await browser.close();await stop();await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output);}
|
||||||
|
|||||||
@@ -43,8 +43,8 @@ try {
|
|||||||
await open('register');assert.equal(await page.locator('#serial-no').inputValue(),'NAV-123456');
|
await open('register');assert.equal(await page.locator('#serial-no').inputValue(),'NAV-123456');
|
||||||
await page.locator('#register-button').click();await page.locator('#record-result').waitFor();
|
await page.locator('#register-button').click();await page.locator('#record-result').waitFor();
|
||||||
await open('archives');await page.locator('#history-query').fill('NAV-123456');await page.locator('.archive-card').waitFor();
|
await open('archives');await page.locator('#history-query').fill('NAV-123456');await page.locator('.archive-card').waitFor();
|
||||||
await page.locator('[data-action=view]').click();assert.equal(await page.locator('#reference-title').innerText(),'设备登记');assert.equal(await page.locator('#record-result').isVisible(),true);
|
await page.locator('[data-action=view]').click();assert.equal(await page.locator('#reference-title').innerText(),'本地档案');assert.equal(await page.locator('body').getAttribute('data-screen'),'archives');assert.equal(await page.locator('#register-form').isVisible(),false);assert.equal(await page.locator('#register-title').isVisible(),false);assert.equal(await page.locator('#record-result').isVisible(),true);assert.equal(await page.locator('#result-title').innerText(),'档案详情');assert.equal(await page.locator('#display-sn').innerText(),'NAV-123456');assert.equal(await page.locator('#display-model').innerText(),'导航验收');assert.match(await page.locator('#display-uas').innerText(),/^FPV\d{8}$/);await page.locator('#close-archive-detail').click();assert.equal(await page.locator('#registration-result').isVisible(),false);await open('register');assert.equal(await page.locator('#serial-no').inputValue(),'NAV-123456');assert.equal(await page.locator('#result-title').innerText(),'二维码与核验');await open('archives');await page.locator('#history-query').fill('NAV-123456');await page.locator('.archive-card').waitFor();
|
||||||
await open('archives');await page.locator('[data-action=more]').click();await page.locator('[data-action=edit]').click();await page.locator('#edit-dialog').waitFor();await page.locator('#edit-owner').fill('导航编辑验证');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});await page.locator('body[data-screen=archives]').waitFor();assert.equal(await page.locator('#reference-title').innerText(),'本地档案');
|
await page.locator('[data-action=more]').click();await page.locator('[data-action=edit]').click();await page.locator('#edit-dialog').waitFor();assert.equal(await page.locator('body').getAttribute('data-screen'),'archives');assert.equal(await page.locator('#register-form').isVisible(),false);await page.locator('#edit-owner').fill('导航编辑验证');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});await page.locator('body[data-screen=archives]').waitFor();assert.equal(await page.locator('#reference-title').innerText(),'本地档案');
|
||||||
await page.locator('#selection-toggle').click();await page.locator('[data-action=select]').check();await page.locator('#export-toggle').click();
|
await page.locator('#selection-toggle').click();await page.locator('[data-action=select]').check();await page.locator('#export-toggle').click();
|
||||||
const download=page.waitForEvent('download');await page.locator('#export-excel').click();assert.ok((await download).suggestedFilename().endsWith('.xlsx'));
|
const download=page.waitForEvent('download');await page.locator('#export-excel').click();assert.ok((await download).suggestedFilename().endsWith('.xlsx'));
|
||||||
await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');
|
await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');
|
||||||
|
|||||||
@@ -4,16 +4,18 @@ import vm from 'node:vm';
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
const source=(await readFile(new URL('../crates/web-ui/public/map-adapter.js',import.meta.url),'utf8')).replace(/^import .*;$/gm,'');
|
const source=(await readFile(new URL('../crates/web-ui/public/map-adapter.js',import.meta.url),'utf8')).replace(/^import .*;$/gm,'');
|
||||||
let markers=0,drawCount=0,trail=[];
|
let markers=0,drawCount=0,trail=[];
|
||||||
const gl={ARRAY_BUFFER:1,bindBuffer(){},bufferSubData(_t,_o,data){assert.ok([...data].every(Number.isFinite));}};
|
const gl={ARRAY_BUFFER:1,bindBuffer(){},bufferSubData(_t,_o,data){assert.ok([...data].every(Number.isFinite));},getExtension(){return null;}};
|
||||||
const map={getSource(){return{setData(data){trail=data.features;}};},triggerRepaint(){},getCanvas(){return{clientWidth:1000,clientHeight:700};},project(p){assert.ok(p.every(Number.isFinite));return{x:1,y:2};},getCenter(){return{toArray(){return[120,30];}};},getZoom(){return 15;},getPitch(){return 0;},getBearing(){return 0;},easeTo(){},isStyleLoaded(){return true;}};
|
let flights=[];
|
||||||
class Marker{constructor(){markers++;this.element={dataset:{}};}setLngLat(p){assert.ok(p.every(Number.isFinite));return this;}addTo(){return this;}getElement(){return this.element;}remove(){markers--;}}
|
const map={getSource(){return{setData(data){trail=data.features;}};},triggerRepaint(){},getCanvas(){return{clientWidth:1000,clientHeight:700};},project(p){assert.ok(p.every(Number.isFinite));return{x:1,y:2};},getCenter(){return{toArray(){return[120,30];}};},getZoom(){return 15;},getPitch(){return 0;},getBearing(){return 0;},easeTo(){},flyTo(options){flights.push(options.center);},isStyleLoaded(){return true;}};
|
||||||
|
class Marker{constructor(opts){markers++;this.element=opts?.element||{dataset:{},querySelector(){return{dataset:{}};}};}setLngLat(p){assert.ok(p.every(Number.isFinite));return this;}addTo(){return this;}getElement(){return this.element;}remove(){markers--;}}
|
||||||
|
function domNode(){const node={dataset:{},className:'',textContent:'',innerHTML:'',children:[],append(...items){this.children.push(...items);},querySelector(sel){const name=sel.slice(1);const walk=item=>item.className===name?item:(item.children||[]).map(walk).find(Boolean);return walk(node)||null;}};return node;}
|
||||||
let now=1000;
|
let now=1000;
|
||||||
const context=vm.createContext({window:{},document:{createElement(){return{};},getElementById(){return null;}},performance:{now:()=>now},requestAnimationFrame(){},maplibre:{setWorkerUrl(){},Marker,MercatorCoordinate:{fromLngLat(p){assert.ok(p.every(Number.isFinite));return{x:p[0],y:p[1]};}}},console,Float32Array,Map,Number,Array,Math,mockMap:map,mockGl:gl});
|
const context=vm.createContext({window:{},document:{createElement:domNode,getElementById(){return null;}},performance:{now:()=>now},requestAnimationFrame(){},maplibre:{setWorkerUrl(){},Marker,MercatorCoordinate:{fromLngLat(p){assert.ok(p.every(Number.isFinite));return{x:p[0],y:p[1]};}}},console,Float32Array,Map,Number,Array,Math,mockMap:map,mockGl:gl});
|
||||||
vm.runInContext(source,context);
|
vm.runInContext(source,context);
|
||||||
vm.runInContext('map=mockMap;layer={gl:mockGl,instances:{},origin:{x:0,y:0}};centered=true;',context);
|
vm.runInContext('map=mockMap;layer={gl:mockGl,instances:{},origin:{x:0,y:0}};centered=true;',context);
|
||||||
const update=(positions,generation)=>{context.input=new Float64Array(positions);context.generation=generation;vm.runInContext('window.ridMap.update(input,["TEST"],[generation]);flush();',context);drawCount=vm.runInContext('layer.count',context);};
|
const update=(positions,generation)=>{context.input=new Float64Array(positions);context.generation=generation;vm.runInContext('window.ridMap.update(input,["TEST"],[generation]);flush();',context);drawCount=vm.runInContext('layer.count',context);};
|
||||||
update([NaN,NaN,NaN,90],0);assert.equal(drawCount,0);assert.equal(vm.runInContext('window.ridMap.select("TEST").length',context),0);
|
update([NaN,NaN,NaN,90],0);assert.equal(drawCount,0);assert.equal(vm.runInContext('window.ridMap.select("TEST").length',context),0);assert.equal(flights.length,0);
|
||||||
update([120,30,NaN,NaN],1);assert.equal(drawCount,1);vm.runInContext('window.ridMap.select("TEST");flush();',context);assert.equal(markers,1);
|
update([120,30,NaN,NaN],1);assert.equal(drawCount,1);vm.runInContext('window.ridMap.select("TEST");flush();',context);assert.equal(markers,1);assert.deepEqual([...flights.at(-1)],[120,30]);
|
||||||
now+=200;update([120.01,30.01,NaN,90],1);assert.equal(trail.length,1);
|
now+=200;update([120.01,30.01,NaN,90],1);assert.equal(trail.length,1);
|
||||||
now+=200;update([NaN,NaN,NaN,90],2);assert.equal(drawCount,0);assert.equal(markers,0);assert.equal(trail.length,0);
|
now+=200;update([NaN,NaN,NaN,90],2);assert.equal(drawCount,0);assert.equal(markers,0);assert.equal(trail.length,0);
|
||||||
now+=200;update([121,31,NaN,90],3);assert.equal(markers,1);assert.equal(trail.length,0);
|
now+=200;update([121,31,NaN,90],3);assert.equal(markers,1);assert.equal(trail.length,0);
|
||||||
@@ -24,4 +26,16 @@ assert.equal(vm.runInContext('layer.count',context),0,'source filter hides map i
|
|||||||
vm.runInContext('window.ridMap.setSources(["TEST"]);',context);
|
vm.runInContext('window.ridMap.setSources(["TEST"]);',context);
|
||||||
assert.equal(vm.runInContext('layer.count',context),1,'source filter restores matching targets');assert.equal(markers,1);
|
assert.equal(vm.runInContext('layer.count',context),1,'source filter restores matching targets');assert.equal(markers,1);
|
||||||
vm.runInContext('window.ridMap.setSources(null);',context);
|
vm.runInContext('window.ridMap.setSources(null);',context);
|
||||||
console.log(JSON.stringify({status:'PASS',scenarios:['unknown position excluded from GPU and selection','unknown altitude/heading do not block valid position','loss removes marker and trail','recovery starts new trail','coalesced loss breaks trail','source filter hides and restores targets']}));
|
const beforeRaw=flights.length;
|
||||||
|
vm.runInContext('window.ridMap.focusRaw([118.5768,31.9547]);',context);
|
||||||
|
assert.deepEqual([...flights.at(-1)],[118.5768,31.9547]);
|
||||||
|
vm.runInContext('window.ridMap.focusRaw([200,0]);',context);
|
||||||
|
assert.equal(flights.length,beforeRaw+1);
|
||||||
|
vm.runInContext('window.ridMap.setFences([{id:"F1",name:"园区",enabled:true,geometry:{type:"circle",center:[120.15,30.28],radius_m:400}}]);',context);
|
||||||
|
assert.equal(vm.runInContext('window.ridMap.metrics().fences',context),1);
|
||||||
|
assert.equal(trail[0].geometry.type,'Polygon');
|
||||||
|
assert.ok(trail[0].geometry.coordinates[0].length>8);
|
||||||
|
assert.equal(markers,2);
|
||||||
|
vm.runInContext('window.ridMap.setFences([{id:"BAD",geometry:{type:"circle",center:[999,0],radius_m:10}}]);',context);
|
||||||
|
assert.equal(trail.length,0);
|
||||||
|
console.log(JSON.stringify({status:'PASS',scenarios:['unknown position excluded from GPU and selection','unknown altitude/heading do not block valid position','loss removes marker and trail','recovery starts new trail','coalesced loss breaks trail','source filter hides and restores targets','saved geofence renders on the realtime map']}));
|
||||||
|
|||||||
+11
-1
@@ -20,6 +20,7 @@ use tokio::sync::Semaphore;
|
|||||||
|
|
||||||
const MAX_TILE_BYTES: usize = 2 * 1024 * 1024;
|
const MAX_TILE_BYTES: usize = 2 * 1024 * 1024;
|
||||||
const LAYERS: &[&str] = &["vec_w", "cva_w", "img_w", "cia_w"];
|
const LAYERS: &[&str] = &["vec_w", "cva_w", "img_w", "cia_w"];
|
||||||
|
const DEFAULT_TIANDITU_TOKEN: &str = "759bdda106dd9375168ad8b79bfbf02a";
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Maps {
|
struct Maps {
|
||||||
root: PathBuf,
|
root: PathBuf,
|
||||||
@@ -63,7 +64,7 @@ fn load_key(
|
|||||||
}
|
}
|
||||||
let path = root.join("maps/config.json");
|
let path = root.join("maps/config.json");
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
return (None, None);
|
return (Some(DEFAULT_TIANDITU_TOKEN.to_owned()), None);
|
||||||
}
|
}
|
||||||
if !allowed(&root.join("maps"), &path)
|
if !allowed(&root.join("maps"), &path)
|
||||||
|| std::fs::metadata(&path).is_ok_and(|m| m.len() > 16384)
|
|| std::fs::metadata(&path).is_ok_and(|m| m.len() > 16384)
|
||||||
@@ -767,6 +768,15 @@ mod tests {
|
|||||||
(None, Some("invalid-config"))
|
(None, Some("invalid-config"))
|
||||||
);
|
);
|
||||||
assert_eq!(std::fs::read(&path).unwrap(), b"broken config");
|
assert_eq!(std::fs::read(&path).unwrap(), b"broken config");
|
||||||
|
let unconfigured = tempfile::tempdir().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
load_key(unconfigured.path(), None, None),
|
||||||
|
(Some(DEFAULT_TIANDITU_TOKEN.into()), None)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
load_key(unconfigured.path(), None, Some(" ".into())),
|
||||||
|
(Some(DEFAULT_TIANDITU_TOKEN.into()), None)
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
load_key(temp.path(), Some("override".into()), None),
|
load_key(temp.path(), Some("override".into()), None),
|
||||||
(Some("override".into()), None)
|
(Some("override".into()), None)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
//! Receive-only transports. Unknown vendor formats remain raw bytes, never guessed positions.
|
//! Receive-only transports. Unknown vendor formats remain raw bytes, never guessed positions.
|
||||||
mod device;
|
mod device;
|
||||||
|
mod gb46750;
|
||||||
mod manager;
|
mod manager;
|
||||||
mod uid;
|
mod uid;
|
||||||
|
mod usb_ports;
|
||||||
|
|
||||||
use crate::realtime::{TargetStore, now_ms};
|
use crate::realtime::{TargetStore, now_ms};
|
||||||
use axum::{
|
use axum::{
|
||||||
@@ -112,6 +114,8 @@ struct Status {
|
|||||||
invalid_targets: u64,
|
invalid_targets: u64,
|
||||||
last_data_ms: Option<u64>,
|
last_data_ms: Option<u64>,
|
||||||
last_error: Option<String>,
|
last_error: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
notice: Option<String>,
|
||||||
capture_hex: String,
|
capture_hex: String,
|
||||||
}
|
}
|
||||||
struct Monitor {
|
struct Monitor {
|
||||||
@@ -205,6 +209,11 @@ impl Receiver {
|
|||||||
let mut monitor = self.monitor.lock().unwrap();
|
let mut monitor = self.monitor.lock().unwrap();
|
||||||
let result: Result<Vec<Observation>, ()> = match format {
|
let result: Result<Vec<Observation>, ()> = match format {
|
||||||
Format::RidDeviceJson | Format::UidJson => {
|
Format::RidDeviceJson | Format::UidJson => {
|
||||||
|
if let Some(notice) = gb46750::notice(bytes) {
|
||||||
|
monitor.status.ignored_lines += 1;
|
||||||
|
monitor.status.notice = Some(notice);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let epoch = monitor.source_epoch;
|
let epoch = monitor.source_epoch;
|
||||||
match if format == Format::UidJson {
|
match if format == Format::UidJson {
|
||||||
uid::decode(bytes, epoch, &mut monitor.sequence)
|
uid::decode(bytes, epoch, &mut monitor.sequence)
|
||||||
@@ -515,6 +524,22 @@ mod tests {
|
|||||||
task: Arc::new(tokio::sync::Mutex::new(None)),
|
task: Arc::new(tokio::sync::Mutex::new(None)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[test]
|
||||||
|
fn gb46750_diagnostic_is_not_a_protocol_mismatch() {
|
||||||
|
let receiver = receiver();
|
||||||
|
receiver.decode(
|
||||||
|
Format::RidDeviceJson,
|
||||||
|
b"[GB46750] Invalid: format_header=0xF1, expect 0xFF\r\n",
|
||||||
|
);
|
||||||
|
let status = receiver.monitor.lock().unwrap().status.clone();
|
||||||
|
assert_eq!(status.rejected_frames, 0);
|
||||||
|
assert_eq!(status.ignored_lines, 1);
|
||||||
|
assert_eq!(status.accepted_observations, 0);
|
||||||
|
assert_eq!(
|
||||||
|
status.notice.as_deref(),
|
||||||
|
Some("GB46750 帧头 0xF1,设备要求 0xFF")
|
||||||
|
);
|
||||||
|
}
|
||||||
fn observation() -> Observation {
|
fn observation() -> Observation {
|
||||||
Observation {
|
Observation {
|
||||||
target_id: "TEST-USB".into(),
|
target_id: "TEST-USB".into(),
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
//! Diagnostic lines from the Espressif GB 46750 receiver. These are not positions.
|
||||||
|
pub(super) fn notice(bytes: &[u8]) -> Option<String> {
|
||||||
|
let line = std::str::from_utf8(bytes).ok()?;
|
||||||
|
let start = line.find("[GB46750]")?;
|
||||||
|
let rest = line[start + "[GB46750]".len()..].trim();
|
||||||
|
let rest = rest.strip_prefix("Invalid:")?.trim();
|
||||||
|
let rest = rest.strip_prefix("format_header=")?;
|
||||||
|
let (got, rest) = rest.split_once(',')?;
|
||||||
|
let expect = rest.trim().strip_prefix("expect")?.trim();
|
||||||
|
let got = hex_byte(got.trim())?;
|
||||||
|
let expect = hex_byte(expect.trim_end_matches(['\r', '\n']).trim())?;
|
||||||
|
Some(format!("GB46750 帧头 0x{got:02X},设备要求 0x{expect:02X}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_byte(value: &str) -> Option<u8> {
|
||||||
|
let hex = value
|
||||||
|
.strip_prefix("0x")
|
||||||
|
.or_else(|| value.strip_prefix("0X"))?;
|
||||||
|
if hex.len() != 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
u8::from_str_radix(hex, 16).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gb46750_header_mismatch_is_a_diagnostic_not_a_position() {
|
||||||
|
let line = b"[GB46750] Invalid: format_header=0xF1, expect 0xFF\r\n";
|
||||||
|
assert_eq!(
|
||||||
|
notice(line).as_deref(),
|
||||||
|
Some("GB46750 帧头 0xF1,设备要求 0xFF")
|
||||||
|
);
|
||||||
|
let glued = b"0xF[GB46750] Invalid: format_header=0xf1, expect 0xff";
|
||||||
|
assert_eq!(
|
||||||
|
notice(glued).as_deref(),
|
||||||
|
Some("GB46750 帧头 0xF1,设备要求 0xFF")
|
||||||
|
);
|
||||||
|
assert!(notice(br#"{"message":"RID","uav":[]}"#).is_none());
|
||||||
|
assert!(notice(b"[GB46750] something else").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
+371
-34
@@ -9,6 +9,49 @@ struct Entry {
|
|||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
config: Config,
|
config: Config,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
rename = "hardwareId",
|
||||||
|
skip_serializing_if = "String::is_empty"
|
||||||
|
)]
|
||||||
|
hardware_id: String,
|
||||||
|
#[serde(default, rename = "autoSuspended", skip_serializing_if = "is_false")]
|
||||||
|
auto_suspended: bool,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
rename = "deviceKind",
|
||||||
|
skip_serializing_if = "String::is_empty"
|
||||||
|
)]
|
||||||
|
device_kind: String,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
rename = "devicePlace",
|
||||||
|
skip_serializing_if = "String::is_empty"
|
||||||
|
)]
|
||||||
|
device_place: String,
|
||||||
|
#[serde(default, rename = "detector", skip_serializing_if = "is_false")]
|
||||||
|
detector: bool,
|
||||||
|
#[serde(default, rename = "nameLocked", skip_serializing_if = "is_false")]
|
||||||
|
name_locked: bool,
|
||||||
|
#[serde(default, rename = "userConfigured", skip_serializing_if = "is_false")]
|
||||||
|
user_configured: bool,
|
||||||
|
}
|
||||||
|
fn blank_entry(id: impl Into<String>, name: impl Into<String>, config: Config) -> Entry {
|
||||||
|
Entry {
|
||||||
|
id: id.into(),
|
||||||
|
name: name.into(),
|
||||||
|
config,
|
||||||
|
hardware_id: String::new(),
|
||||||
|
auto_suspended: false,
|
||||||
|
device_kind: String::new(),
|
||||||
|
device_place: String::new(),
|
||||||
|
detector: false,
|
||||||
|
name_locked: false,
|
||||||
|
user_configured: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn is_false(value: &bool) -> bool {
|
||||||
|
!*value
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Manager {
|
struct Manager {
|
||||||
@@ -17,6 +60,7 @@ struct Manager {
|
|||||||
targets: TargetStore,
|
targets: TargetStore,
|
||||||
entries: Arc<tokio::sync::Mutex<BTreeMap<String, (Entry, Receiver)>>>,
|
entries: Arc<tokio::sync::Mutex<BTreeMap<String, (Entry, Receiver)>>>,
|
||||||
error: Arc<Mutex<Option<String>>>,
|
error: Arc<Mutex<Option<String>>>,
|
||||||
|
scan: Arc<tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>>,
|
||||||
}
|
}
|
||||||
fn receiver(id: &str, targets: TargetStore) -> Receiver {
|
fn receiver(id: &str, targets: TargetStore) -> Receiver {
|
||||||
Receiver {
|
Receiver {
|
||||||
@@ -62,6 +106,18 @@ fn validate(entries: &[Entry]) -> Result<(), &'static str> {
|
|||||||
if entry.name.trim().is_empty() || entry.name.len() > 120 {
|
if entry.name.trim().is_empty() || entry.name.len() > 120 {
|
||||||
return Err("请填写有效设备名称(最多 120 字节)");
|
return Err("请填写有效设备名称(最多 120 字节)");
|
||||||
}
|
}
|
||||||
|
if !entry.hardware_id.is_empty()
|
||||||
|
&& (entry.hardware_id.len() > 40
|
||||||
|
|| !entry
|
||||||
|
.hardware_id
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||||
|
|| entries[..index]
|
||||||
|
.iter()
|
||||||
|
.any(|e| e.hardware_id == entry.hardware_id))
|
||||||
|
{
|
||||||
|
return Err("设备硬件 ID 无效或重复");
|
||||||
|
}
|
||||||
entry.config.validate()?;
|
entry.config.validate()?;
|
||||||
if entries[..index]
|
if entries[..index]
|
||||||
.iter()
|
.iter()
|
||||||
@@ -89,6 +145,10 @@ impl Shutdown {
|
|||||||
self.0
|
self.0
|
||||||
.stopping
|
.stopping
|
||||||
.store(true, std::sync::atomic::Ordering::Release);
|
.store(true, std::sync::atomic::Ordering::Release);
|
||||||
|
if let Some(task) = self.0.scan.lock().await.take() {
|
||||||
|
task.abort();
|
||||||
|
let _ = task.await;
|
||||||
|
}
|
||||||
let entries = self.0.entries.lock().await;
|
let entries = self.0.entries.lock().await;
|
||||||
for (_, receiver) in entries.values() {
|
for (_, receiver) in entries.values() {
|
||||||
if let Some(task) = receiver.task.lock().await.take() {
|
if let Some(task) = receiver.task.lock().await.take() {
|
||||||
@@ -106,6 +166,7 @@ pub(super) async fn start(root: PathBuf, targets: TargetStore) -> (Router, Shutd
|
|||||||
targets,
|
targets,
|
||||||
entries: Default::default(),
|
entries: Default::default(),
|
||||||
error: Default::default(),
|
error: Default::default(),
|
||||||
|
scan: Default::default(),
|
||||||
};
|
};
|
||||||
let path = manager.root.join("receivers.json");
|
let path = manager.root.join("receivers.json");
|
||||||
let loaded: Result<Vec<Entry>, String> = (|| {
|
let loaded: Result<Vec<Entry>, String> = (|| {
|
||||||
@@ -126,11 +187,7 @@ pub(super) async fn start(root: PathBuf, targets: TargetStore) -> (Router, Shutd
|
|||||||
} else {
|
} else {
|
||||||
Config::default()
|
Config::default()
|
||||||
};
|
};
|
||||||
Ok(vec![Entry {
|
Ok(vec![blank_entry("default", "接收机 01", config)])
|
||||||
id: "default".into(),
|
|
||||||
name: "接收机 01".into(),
|
|
||||||
config,
|
|
||||||
}])
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
match loaded.and_then(|entries| validate(&entries).map(|()| entries).map_err(str::to_owned)) {
|
match loaded.and_then(|entries| validate(&entries).map(|()| entries).map_err(str::to_owned)) {
|
||||||
@@ -157,6 +214,11 @@ pub(super) async fn start(root: PathBuf, targets: TargetStore) -> (Router, Shutd
|
|||||||
Some(format!("配置无效,原文件已保留,未启动接收:{e}"));
|
Some(format!("配置无效,原文件已保留,未启动接收:{e}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !cfg!(test) {
|
||||||
|
let watched = manager.clone();
|
||||||
|
let task = tokio::spawn(async move { watch_ports(watched).await });
|
||||||
|
*manager.scan.lock().await = Some(task);
|
||||||
|
}
|
||||||
let shutdown = Shutdown(manager.clone());
|
let shutdown = Shutdown(manager.clone());
|
||||||
let router = Router::new()
|
let router = Router::new()
|
||||||
.route("/api/receivers", get(list).post(create))
|
.route("/api/receivers", get(list).post(create))
|
||||||
@@ -179,7 +241,7 @@ async fn list(State(m): State<Manager>, headers: HeaderMap) -> Response {
|
|||||||
return StatusCode::FORBIDDEN.into_response();
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
}
|
}
|
||||||
let entries = m.entries.lock().await;
|
let entries = m.entries.lock().await;
|
||||||
let rows: Vec<_> = entries.values().map(|(entry, receiver)| json!({"id":entry.id,"name":entry.name,"config":entry.config,"status":receiver.monitor.lock().unwrap().status})).collect();
|
let rows: Vec<_> = entries.values().map(|(entry, receiver)| json!({"id":entry.id,"name":entry.name,"hardwareId":entry.hardware_id,"deviceKind":entry.device_kind,"devicePlace":entry.device_place,"detector":entry.detector,"config":entry.config,"status":receiver.monitor.lock().unwrap().status})).collect();
|
||||||
Json(json!({"receivers":rows,"error":*m.error.lock().unwrap()})).into_response()
|
Json(json!({"receivers":rows,"error":*m.error.lock().unwrap()})).into_response()
|
||||||
}
|
}
|
||||||
async fn detail(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
async fn detail(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
||||||
@@ -221,6 +283,18 @@ async fn write(m: Manager, mut entry: Entry, creating: bool) -> Response {
|
|||||||
if creating == entries.contains_key(&entry.id) {
|
if creating == entries.contains_key(&entry.id) {
|
||||||
return error(StatusCode::CONFLICT, "接收机不存在或 ID 已存在");
|
return error(StatusCode::CONFLICT, "接收机不存在或 ID 已存在");
|
||||||
}
|
}
|
||||||
|
if !creating && let Some((prev, _)) = entries.get(&entry.id) {
|
||||||
|
entry.hardware_id = prev.hardware_id.clone();
|
||||||
|
entry.device_kind = prev.device_kind.clone();
|
||||||
|
entry.device_place = prev.device_place.clone();
|
||||||
|
entry.detector = prev.detector;
|
||||||
|
entry.name_locked = prev.name_locked || entry.name != prev.name;
|
||||||
|
entry.user_configured = true;
|
||||||
|
entry.auto_suspended = !entry.config.enabled && !prev.config.enabled && prev.auto_suspended;
|
||||||
|
} else if creating {
|
||||||
|
entry.user_configured = true;
|
||||||
|
entry.name_locked = true;
|
||||||
|
}
|
||||||
let mut next: Vec<_> = entries
|
let mut next: Vec<_> = entries
|
||||||
.values()
|
.values()
|
||||||
.filter(|(e, _)| e.id != entry.id)
|
.filter(|(e, _)| e.id != entry.id)
|
||||||
@@ -257,11 +331,11 @@ async fn create(
|
|||||||
}
|
}
|
||||||
write(
|
write(
|
||||||
m,
|
m,
|
||||||
Entry {
|
blank_entry(
|
||||||
id: format!("rx-{:016x}", rand::random::<u64>()),
|
format!("rx-{:016x}", rand::random::<u64>()),
|
||||||
name: input.name,
|
input.name,
|
||||||
config: input.config,
|
input.config,
|
||||||
},
|
),
|
||||||
true,
|
true,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -275,16 +349,7 @@ async fn update(
|
|||||||
if !local(&headers) {
|
if !local(&headers) {
|
||||||
return StatusCode::FORBIDDEN.into_response();
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
}
|
}
|
||||||
write(
|
write(m, blank_entry(id, input.name, input.config), false).await
|
||||||
m,
|
|
||||||
Entry {
|
|
||||||
id,
|
|
||||||
name: input.name,
|
|
||||||
config: input.config,
|
|
||||||
},
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
async fn remove(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
async fn remove(State(m): State<Manager>, Path(id): Path<String>, headers: HeaderMap) -> Response {
|
||||||
if !local(&headers) {
|
if !local(&headers) {
|
||||||
@@ -376,16 +441,168 @@ async fn legacy_save(
|
|||||||
.get("default")
|
.get("default")
|
||||||
.map(|(e, _)| e.name.clone())
|
.map(|(e, _)| e.name.clone())
|
||||||
.unwrap_or_else(|| "接收机 01".into());
|
.unwrap_or_else(|| "接收机 01".into());
|
||||||
write(
|
write(m, blank_entry("default", name, config), false).await
|
||||||
m,
|
}
|
||||||
Entry {
|
|
||||||
id: "default".into(),
|
fn plan(entries: &[Entry], ports: &[super::usb_ports::ObservedPort]) -> Option<Vec<Entry>> {
|
||||||
name,
|
let mut next = entries.to_vec();
|
||||||
config,
|
let mut changed = false;
|
||||||
|
let present: std::collections::HashSet<&str> =
|
||||||
|
ports.iter().map(|port| port.hardware_id.as_str()).collect();
|
||||||
|
for port in ports {
|
||||||
|
if let Some(holder) = next.iter_mut().find(|entry| {
|
||||||
|
entry.config.transport == Transport::Serial
|
||||||
|
&& entry.config.serial_port.eq_ignore_ascii_case(&port.port)
|
||||||
|
&& !entry.hardware_id.is_empty()
|
||||||
|
&& entry.hardware_id != port.hardware_id
|
||||||
|
&& !present.contains(entry.hardware_id.as_str())
|
||||||
|
}) && holder.config.enabled
|
||||||
|
{
|
||||||
|
holder.config.enabled = false;
|
||||||
|
holder.auto_suspended = true;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for port in ports {
|
||||||
|
if let Some(entry) = next
|
||||||
|
.iter_mut()
|
||||||
|
.find(|entry| entry.hardware_id == port.hardware_id)
|
||||||
|
{
|
||||||
|
if entry.config.transport == Transport::Serial
|
||||||
|
&& !entry.config.serial_port.eq_ignore_ascii_case(&port.port)
|
||||||
|
{
|
||||||
|
entry.config.serial_port = port.port.clone();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if entry.auto_suspended {
|
||||||
|
entry.config.enabled = true;
|
||||||
|
entry.auto_suspended = false;
|
||||||
|
entry.config.transport = Transport::Serial;
|
||||||
|
entry.config.serial_port = port.port.clone();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if describe(entry, port) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(entry) = next.iter_mut().find(|entry| {
|
||||||
|
entry.hardware_id.is_empty()
|
||||||
|
&& entry.config.transport == Transport::Serial
|
||||||
|
&& entry.config.serial_port.eq_ignore_ascii_case(&port.port)
|
||||||
|
}) {
|
||||||
|
if describe(entry, port) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let occupied = next.iter().any(|entry| {
|
||||||
|
entry.config.enabled
|
||||||
|
&& entry.config.transport == Transport::Serial
|
||||||
|
&& entry.config.serial_port.eq_ignore_ascii_case(&port.port)
|
||||||
|
});
|
||||||
|
if occupied || next.len() >= 32 || next.iter().any(|entry| entry.id == port.hardware_id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut created = blank_entry(
|
||||||
|
port.hardware_id.clone(),
|
||||||
|
String::new(),
|
||||||
|
Config {
|
||||||
|
enabled: port.detector,
|
||||||
|
transport: Transport::Serial,
|
||||||
|
format: Format::RidDeviceJson,
|
||||||
|
serial_port: port.port.clone(),
|
||||||
|
baud_rate: 115200,
|
||||||
|
..Config::default()
|
||||||
},
|
},
|
||||||
false,
|
);
|
||||||
)
|
created.hardware_id = port.hardware_id.clone();
|
||||||
|
describe(&mut created, port);
|
||||||
|
next.push(created);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
changed.then_some(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn describe(entry: &mut Entry, port: &super::usb_ports::ObservedPort) -> bool {
|
||||||
|
let mut changed = false;
|
||||||
|
if entry.hardware_id.is_empty() {
|
||||||
|
entry.hardware_id = port.hardware_id.clone();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if entry.device_kind != port.kind {
|
||||||
|
entry.device_kind = port.kind.clone();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if entry.device_place != port.place {
|
||||||
|
entry.device_place = port.place.clone();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if entry.detector != port.detector {
|
||||||
|
entry.detector = port.detector;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if !entry.name_locked {
|
||||||
|
let name = super::usb_ports::display_name(&port.kind, &port.place, &port.port);
|
||||||
|
if entry.name != name {
|
||||||
|
entry.name = name;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !port.detector && !entry.user_configured && entry.config.enabled {
|
||||||
|
entry.config.enabled = false;
|
||||||
|
entry.auto_suspended = false;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn adopt(manager: &Manager, ports: Vec<super::usb_ports::ObservedPort>) {
|
||||||
|
if manager.stopping.load(std::sync::atomic::Ordering::Acquire) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut entries = manager.entries.lock().await;
|
||||||
|
if entries.is_empty() || manager.stopping.load(std::sync::atomic::Ordering::Acquire) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let current: Vec<_> = entries.values().map(|(entry, _)| entry.clone()).collect();
|
||||||
|
let Some(next) = plan(¤t, &ports) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if validate(&next).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if persist(manager, next.clone()).await.is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for entry in next {
|
||||||
|
let existing = entries
|
||||||
|
.get(&entry.id)
|
||||||
|
.map(|(stored, instance)| (stored.config.clone(), instance.clone()));
|
||||||
|
if let Some((config, instance)) = existing {
|
||||||
|
if config != entry.config {
|
||||||
|
instance.start(entry.config.clone()).await;
|
||||||
|
}
|
||||||
|
entries.insert(entry.id.clone(), (entry, instance));
|
||||||
|
} else {
|
||||||
|
let instance = receiver(&entry.id, manager.targets.clone());
|
||||||
|
instance.start(entry.config.clone()).await;
|
||||||
|
entries.insert(entry.id.clone(), (entry, instance));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn watch_ports(manager: Manager) {
|
||||||
|
loop {
|
||||||
|
if manager.stopping.load(std::sync::atomic::Ordering::Acquire) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let ports = tokio::task::spawn_blocking(super::usb_ports::observed_ports)
|
||||||
.await
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
adopt(&manager, ports).await;
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -402,16 +619,17 @@ mod tests {
|
|||||||
let probe = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
let probe = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
let address = probe.local_addr().unwrap();
|
let address = probe.local_addr().unwrap();
|
||||||
drop(probe);
|
drop(probe);
|
||||||
let entry = Entry {
|
let mut entry = blank_entry(
|
||||||
id: "default".into(),
|
"default",
|
||||||
name: "test".into(),
|
"test",
|
||||||
config: Config {
|
Config {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
transport: Transport::Udp,
|
transport: Transport::Udp,
|
||||||
port: address.port(),
|
port: address.port(),
|
||||||
..Config::default()
|
..Config::default()
|
||||||
},
|
},
|
||||||
};
|
);
|
||||||
|
entry.user_configured = true;
|
||||||
let bytes = serde_json::to_vec(&vec![entry]).unwrap();
|
let bytes = serde_json::to_vec(&vec![entry]).unwrap();
|
||||||
let path = root.path().join("receivers.json");
|
let path = root.path().join("receivers.json");
|
||||||
std::fs::write(&path, &bytes).unwrap();
|
std::fs::write(&path, &bytes).unwrap();
|
||||||
@@ -603,4 +821,123 @@ mod tests {
|
|||||||
200
|
200
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn serial(id: &str, port: &str, hardware: &str, enabled: bool, suspended: bool) -> Entry {
|
||||||
|
let mut entry = blank_entry(
|
||||||
|
id,
|
||||||
|
"设备",
|
||||||
|
Config {
|
||||||
|
enabled,
|
||||||
|
transport: Transport::Serial,
|
||||||
|
format: Format::RidDeviceJson,
|
||||||
|
serial_port: port.into(),
|
||||||
|
..Config::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
entry.hardware_id = hardware.into();
|
||||||
|
entry.auto_suspended = suspended;
|
||||||
|
entry.detector = true;
|
||||||
|
entry
|
||||||
|
}
|
||||||
|
fn port(name: &str, id: &str) -> super::super::usb_ports::ObservedPort {
|
||||||
|
super::super::usb_ports::ObservedPort {
|
||||||
|
port: name.into(),
|
||||||
|
hardware_id: id.into(),
|
||||||
|
kind: "沁恒 CH340".into(),
|
||||||
|
place: String::new(),
|
||||||
|
detector: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugged_ports_join_existing_devices_without_duplicating_hardware() {
|
||||||
|
let saved = vec![
|
||||||
|
serial("default", "COM21", "", true, false),
|
||||||
|
serial("rx-existing", "COM10", "", true, false),
|
||||||
|
];
|
||||||
|
let ports = vec![
|
||||||
|
port("COM21", "usb-1a86-7523-6-26ef9c29-0-2"),
|
||||||
|
port("COM10", "usb-1a86-7523-7-c54388d-0-1"),
|
||||||
|
port("COM17", "usb-303a-1001-mi00-8-270cf0c5-0-0000"),
|
||||||
|
];
|
||||||
|
let next = plan(&saved, &ports).unwrap();
|
||||||
|
assert_eq!(next.len(), 3);
|
||||||
|
assert_eq!(next[0].id, "default");
|
||||||
|
assert_eq!(next[0].hardware_id, "usb-1a86-7523-6-26ef9c29-0-2");
|
||||||
|
assert_eq!(next[1].hardware_id, "usb-1a86-7523-7-c54388d-0-1");
|
||||||
|
assert_eq!(next[2].id, "usb-303a-1001-mi00-8-270cf0c5-0-0000");
|
||||||
|
assert!(next[2].config.enabled);
|
||||||
|
assert!(validate(&next).is_ok());
|
||||||
|
assert!(plan(&next, &ports).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_same_device_keeps_its_id_when_the_com_number_changes() {
|
||||||
|
let saved = vec![serial(
|
||||||
|
"default",
|
||||||
|
"COM16",
|
||||||
|
"usb-1a86-7523-6-26ef9c29-0-2",
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
)];
|
||||||
|
let next = plan(&saved, &[port("COM21", "usb-1a86-7523-6-26ef9c29-0-2")]).unwrap();
|
||||||
|
assert_eq!(next.len(), 1);
|
||||||
|
assert_eq!(next[0].id, "default");
|
||||||
|
assert_eq!(next[0].hardware_id, "usb-1a86-7523-6-26ef9c29-0-2");
|
||||||
|
assert_eq!(next[0].config.serial_port, "COM21");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unplugged_device_releases_a_reused_port_and_returns_with_the_same_id() {
|
||||||
|
let saved = vec![serial("default", "COM21", "usb-old", true, false)];
|
||||||
|
let replaced = plan(&saved, &[port("COM21", "usb-new")]).unwrap();
|
||||||
|
assert!(!replaced[0].config.enabled);
|
||||||
|
assert!(replaced[0].auto_suspended);
|
||||||
|
assert_eq!(replaced[1].id, "usb-new");
|
||||||
|
assert!(replaced[1].config.enabled);
|
||||||
|
let returned = plan(
|
||||||
|
&replaced,
|
||||||
|
&[port("COM22", "usb-old"), port("COM21", "usb-new")],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let old = returned
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.hardware_id == "usb-old")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(old.id, "default");
|
||||||
|
assert_eq!(old.config.serial_port, "COM22");
|
||||||
|
assert!(old.config.enabled);
|
||||||
|
assert!(!old.auto_suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_manually_stopped_device_stays_stopped_when_it_is_still_plugged_in() {
|
||||||
|
let saved = vec![serial("default", "COM21", "usb-old", false, false)];
|
||||||
|
let next = plan(&saved, &[port("COM22", "usb-old")]).unwrap();
|
||||||
|
assert!(!next[0].config.enabled);
|
||||||
|
assert!(!next[0].auto_suspended);
|
||||||
|
assert_eq!(next[0].config.serial_port, "COM22");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_debug_port_is_labeled_by_its_socket_and_not_left_running_as_a_detector() {
|
||||||
|
let mut saved = serial("default", "COM17", "usb-debug", true, false);
|
||||||
|
saved.detector = false;
|
||||||
|
let seen = super::super::usb_ports::ObservedPort {
|
||||||
|
port: "COM17".into(),
|
||||||
|
hardware_id: "usb-debug".into(),
|
||||||
|
kind: "乐鑫调试口".into(),
|
||||||
|
place: "USB 位置 6-4-1-2".into(),
|
||||||
|
detector: false,
|
||||||
|
};
|
||||||
|
let next = plan(&[saved], &[seen.clone()]).unwrap();
|
||||||
|
assert!(!next[0].config.enabled);
|
||||||
|
assert_eq!(next[0].name, "乐鑫调试口 · USB 位置 6-4-1-2");
|
||||||
|
let mut kept = next[0].clone();
|
||||||
|
kept.user_configured = true;
|
||||||
|
kept.name_locked = true;
|
||||||
|
kept.name = "我的调试口".into();
|
||||||
|
kept.config.enabled = true;
|
||||||
|
assert!(plan(&[kept], &[seen]).is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,345 @@
|
|||||||
|
//! USB serial identity. COM numbers are endpoints; the hardware instance is the device id.
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(super) struct ObservedPort {
|
||||||
|
pub port: String,
|
||||||
|
pub hardware_id: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub place: String,
|
||||||
|
pub detector: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn device_id(vid_pid: &str, instance: &str) -> String {
|
||||||
|
let vid = hex_field(vid_pid, "VID_").unwrap_or_else(|| "0000".into());
|
||||||
|
let pid = hex_field(vid_pid, "PID_").unwrap_or_else(|| "0000".into());
|
||||||
|
let instance = token(instance);
|
||||||
|
let id = if let Some(interface) = hex_field(vid_pid, "MI_") {
|
||||||
|
format!("usb-{vid}-{pid}-mi{interface}-{instance}")
|
||||||
|
} else {
|
||||||
|
format!("usb-{vid}-{pid}-{instance}")
|
||||||
|
};
|
||||||
|
if valid_identity(&id) {
|
||||||
|
id
|
||||||
|
} else {
|
||||||
|
format!("usb-{:016x}", fnv64(id.as_bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn chip(vid: &str, pid: &str) -> (&'static str, bool) {
|
||||||
|
match (vid, pid) {
|
||||||
|
("1a86", "7523" | "5523") => ("沁恒 CH340", true),
|
||||||
|
("1a86", "55d4") => ("沁恒 CH9102", true),
|
||||||
|
("10c4", "ea60" | "ea70") => ("芯科 CP210x", true),
|
||||||
|
("0403", "6001" | "6015") => ("FTDI 串口", true),
|
||||||
|
("303a", "1001") => ("乐鑫调试口", false),
|
||||||
|
("303a", _) => ("乐鑫 USB 串口", false),
|
||||||
|
_ => ("其他 USB 串口", false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn place_label(location: &str) -> String {
|
||||||
|
if let Some(rest) = location.strip_prefix("Port_#")
|
||||||
|
&& let Some((port, hub)) = rest.split_once(".Hub_#")
|
||||||
|
{
|
||||||
|
return format!("集线器 {} · 端口 {}", number(hub), number(port));
|
||||||
|
}
|
||||||
|
let parts: Vec<_> = location
|
||||||
|
.split(['.', '#'])
|
||||||
|
.filter_map(|part| {
|
||||||
|
let trimmed = part.trim_start_matches('0');
|
||||||
|
(!trimmed.is_empty() && trimmed.bytes().all(|b| b.is_ascii_digit())).then_some(trimmed)
|
||||||
|
})
|
||||||
|
.take(4)
|
||||||
|
.collect();
|
||||||
|
if parts.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("USB 位置 {}", parts.join("-"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn display_name(kind: &str, place: &str, port: &str) -> String {
|
||||||
|
let name = if place.is_empty() {
|
||||||
|
format!("{kind} · {port}")
|
||||||
|
} else {
|
||||||
|
format!("{kind} · {place}")
|
||||||
|
};
|
||||||
|
if name.len() <= 120 {
|
||||||
|
name
|
||||||
|
} else {
|
||||||
|
format!("{kind} · {port}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number(value: &str) -> &str {
|
||||||
|
let trimmed = value.trim_start_matches('0');
|
||||||
|
if trimmed.is_empty() { "0" } else { trimmed }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn observed_ports() -> Vec<ObservedPort> {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
windows_ports()
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_identity(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_field(value: &str, key: &str) -> Option<String> {
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
let key = key.to_ascii_lowercase();
|
||||||
|
let rest = value.get(value.find(&key)? + key.len()..)?;
|
||||||
|
let hex: String = rest.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
|
||||||
|
(!hex.is_empty()).then(|| hex.to_ascii_lowercase())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token(value: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut hyphen = false;
|
||||||
|
for c in value.chars() {
|
||||||
|
if c.is_ascii_alphanumeric() {
|
||||||
|
out.push(c.to_ascii_lowercase());
|
||||||
|
hyphen = false;
|
||||||
|
} else if !hyphen && !out.is_empty() {
|
||||||
|
out.push('-');
|
||||||
|
hyphen = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out.ends_with('-') {
|
||||||
|
out.pop();
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fnv64(bytes: &[u8]) -> u64 {
|
||||||
|
let mut hash = 0xcbf29ce484222325u64;
|
||||||
|
for byte in bytes {
|
||||||
|
hash ^= u64::from(*byte);
|
||||||
|
hash = hash.wrapping_mul(0x100000001b3);
|
||||||
|
}
|
||||||
|
hash
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn windows_ports() -> Vec<ObservedPort> {
|
||||||
|
let present = match tokio_serial::available_ports() {
|
||||||
|
Ok(ports) => ports
|
||||||
|
.into_iter()
|
||||||
|
.map(|port| port.port_name.to_ascii_uppercase())
|
||||||
|
.collect::<HashSet<_>>(),
|
||||||
|
Err(_) => return Vec::new(),
|
||||||
|
};
|
||||||
|
let Some(root) = open(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Enum\\USB") else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut found = Vec::new();
|
||||||
|
for vid_pid in subkeys(root.0) {
|
||||||
|
let Some(vendor) = open(root.0, &vid_pid) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for instance in subkeys(vendor.0) {
|
||||||
|
let Some(device) = open(vendor.0, &instance) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(params) = open(device.0, "Device Parameters") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(port) = query_port(params.0) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !present.contains(&port) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let hardware_id = device_id(&vid_pid, &instance);
|
||||||
|
if found
|
||||||
|
.iter()
|
||||||
|
.any(|item: &ObservedPort| item.port == port || item.hardware_id == hardware_id)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let vid = hex_field(&vid_pid, "VID_").unwrap_or_else(|| "0000".into());
|
||||||
|
let pid = hex_field(&vid_pid, "PID_").unwrap_or_else(|| "0000".into());
|
||||||
|
let (kind, detector) = chip(&vid, &pid);
|
||||||
|
let place =
|
||||||
|
place_label(&query_text(device.0, "LocationInformation").unwrap_or_default());
|
||||||
|
found.push(ObservedPort {
|
||||||
|
port,
|
||||||
|
hardware_id,
|
||||||
|
kind: kind.into(),
|
||||||
|
place,
|
||||||
|
detector,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found.sort_by(|a, b| a.port.cmp(&b.port));
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::ERROR_SUCCESS,
|
||||||
|
System::Registry::{
|
||||||
|
HKEY, HKEY_LOCAL_MACHINE, KEY_READ, REG_SZ, RegCloseKey, RegEnumKeyExW, RegOpenKeyExW,
|
||||||
|
RegQueryValueExW,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
struct RegKey(HKEY);
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
impl Drop for RegKey {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.0 != 0 {
|
||||||
|
// SAFETY: the handle was opened by RegOpenKeyExW and is closed once.
|
||||||
|
unsafe { RegCloseKey(self.0) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn wide(value: &str) -> Vec<u16> {
|
||||||
|
value.encode_utf16().chain(Some(0)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn open(parent: HKEY, path: &str) -> Option<RegKey> {
|
||||||
|
let mut handle: HKEY = 0;
|
||||||
|
let path = wide(path);
|
||||||
|
// SAFETY: parent is a live registry key, path is null-terminated, and the output pointer is valid.
|
||||||
|
let status = unsafe { RegOpenKeyExW(parent, path.as_ptr(), 0, KEY_READ, &mut handle) };
|
||||||
|
(status == ERROR_SUCCESS).then_some(RegKey(handle))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn subkeys(key: HKEY) -> Vec<String> {
|
||||||
|
let mut names = Vec::new();
|
||||||
|
for index in 0..2048u32 {
|
||||||
|
let mut buf = [0u16; 256];
|
||||||
|
let mut len = (buf.len() - 1) as u32;
|
||||||
|
// SAFETY: buf and len refer to the same writable buffer; unused class and time pointers are null.
|
||||||
|
let status = unsafe {
|
||||||
|
RegEnumKeyExW(
|
||||||
|
key,
|
||||||
|
index,
|
||||||
|
buf.as_mut_ptr(),
|
||||||
|
&mut len,
|
||||||
|
std::ptr::null(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if status != ERROR_SUCCESS {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
names.push(String::from_utf16_lossy(&buf[..len as usize]));
|
||||||
|
}
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn query_port(key: HKEY) -> Option<String> {
|
||||||
|
let port = query_text(key, "PortName")?.to_ascii_uppercase();
|
||||||
|
port.strip_prefix("COM")
|
||||||
|
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||||
|
.then_some(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn query_text(key: HKEY, value: &str) -> Option<String> {
|
||||||
|
let name = wide(value);
|
||||||
|
let mut kind = 0u32;
|
||||||
|
let mut bytes = 0u32;
|
||||||
|
// SAFETY: name is null-terminated; the size query uses a null data pointer as documented.
|
||||||
|
let status = unsafe {
|
||||||
|
RegQueryValueExW(
|
||||||
|
key,
|
||||||
|
name.as_ptr(),
|
||||||
|
std::ptr::null(),
|
||||||
|
&mut kind,
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
&mut bytes,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if status != ERROR_SUCCESS || kind != REG_SZ || !(2..=512).contains(&bytes) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut buf = vec![0u16; bytes as usize / 2];
|
||||||
|
// SAFETY: buf is writable and bytes is its size in bytes.
|
||||||
|
let status = unsafe {
|
||||||
|
RegQueryValueExW(
|
||||||
|
key,
|
||||||
|
name.as_ptr(),
|
||||||
|
std::ptr::null(),
|
||||||
|
&mut kind,
|
||||||
|
buf.as_mut_ptr().cast(),
|
||||||
|
&mut bytes,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if status != ERROR_SUCCESS {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let end = buf.iter().position(|unit| *unit == 0).unwrap_or(buf.len());
|
||||||
|
let text = String::from_utf16_lossy(&buf[..end]).trim().to_owned();
|
||||||
|
(!text.is_empty()).then_some(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_ids_stay_stable_and_distinct_inside_receiver_id_limits() {
|
||||||
|
let first = device_id("VID_1A86&PID_7523", "6&26EF9C29&0&2");
|
||||||
|
let second = device_id("VID_1A86&PID_7523", "7&C54388D&0&1");
|
||||||
|
let interface = device_id("VID_303A&PID_1001&MI_00", "8&270CF0C5&0&0000");
|
||||||
|
assert_eq!(first, "usb-1a86-7523-6-26ef9c29-0-2");
|
||||||
|
assert_eq!(first, device_id("vid_1a86&pid_7523", "6&26ef9c29&0&2"));
|
||||||
|
assert_ne!(first, second);
|
||||||
|
assert_ne!(first, interface);
|
||||||
|
assert_eq!(interface, "usb-303a-1001-mi00-8-270cf0c5-0-0000");
|
||||||
|
let long = device_id("VID_1209&PID_5741", &"A".repeat(80));
|
||||||
|
assert!(long.len() <= 40, "{long}");
|
||||||
|
assert_eq!(long, device_id("VID_1209&PID_5741", &"A".repeat(80)));
|
||||||
|
for id in [first, second, interface, long] {
|
||||||
|
assert!(valid_identity(&id), "{id}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observed_ports_only_include_distinct_present_usb_devices() {
|
||||||
|
let ports = observed_ports();
|
||||||
|
let mut ids = HashSet::new();
|
||||||
|
let mut names = HashSet::new();
|
||||||
|
for port in ports {
|
||||||
|
assert!(port.port.starts_with("COM"), "{}", port.port);
|
||||||
|
assert!(valid_identity(&port.hardware_id), "{}", port.hardware_id);
|
||||||
|
assert!(ids.insert(port.hardware_id));
|
||||||
|
assert!(names.insert(port.port));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chips_and_usb_places_are_readable() {
|
||||||
|
assert_eq!(chip("1a86", "7523"), ("沁恒 CH340", true));
|
||||||
|
assert_eq!(chip("303a", "1001"), ("乐鑫调试口", false));
|
||||||
|
assert_eq!(place_label("Port_#0002.Hub_#0002"), "集线器 2 · 端口 2");
|
||||||
|
assert_eq!(place_label("Port_#0001.Hub_#0003"), "集线器 3 · 端口 1");
|
||||||
|
assert_eq!(
|
||||||
|
place_label("0006.0000.0004.001.002.000.000.000.000"),
|
||||||
|
"USB 位置 6-4-1-2"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
display_name("沁恒 CH340", "集线器 2 · 端口 2", "COM21"),
|
||||||
|
"沁恒 CH340 · 集线器 2 · 端口 2"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user