- 在 geofence-map-adapter.js 中添加了处理围栏顶点和圆心的拖动功能,提升用户交互体验。 - 实现了计算两点间距离的函数,以支持动态调整围栏半径。 - 更新了 receivers.js 中的状态显示逻辑,优化了设备状态的反馈信息,确保更准确的连接状态提示。 - 修改了 CSS 文件以改善界面样式,确保在不同主题下的视觉一致性。
128 lines
13 KiB
JavaScript
128 lines
13 KiB
JavaScript
// Device management is a view of server-owned receiver tasks, never their lifecycle owner.
|
|
const $ = id => document.getElementById(id);
|
|
let rows = [], selected = null, busy = false, pending = false, dirty = false, initialized = false;
|
|
const defaults = {enabled:false,transport:'serial',format:'raw',serialPort:'',baudRate:115200,bindIp:'127.0.0.1',port:8788};
|
|
const protocols = {'raw':'原始诊断','uid-json':'UID JSON','rid-device-json':'RID / uav','json-lines':'约定 JSON','postcard':'Postcard'};
|
|
function state(row) {
|
|
const s=row.status||{};
|
|
if(!row.config?.enabled)return !row.detector&&row.deviceKind?'其他串口 · 未当作侦测机':'未启用';
|
|
if(s.state==='disconnected')return '连接失败 · 自动重试';
|
|
if(s.state==='connecting'||s.state==='stopped')return '正在连接';
|
|
if(s.notice)return s.notice;
|
|
if(!s.receivedBytes)return row.detector?'侦测串口已连接 · 还没有数据':'已连接 · 等待数据';
|
|
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return '连接中 · 暂无新数据';
|
|
if(row.config.format==='raw')return '接收中 · 原始诊断';
|
|
if(s.rejectedFrames&&!s.decodedFrames)return '收到数据 · 协议不匹配';
|
|
if(!s.acceptedObservations)return '正在接收 · 暂无有效目标';
|
|
return '正在接收 · 已解析目标';
|
|
}
|
|
const GB_NOTE='这台设备收到了报文,但帧头不符合它自己的 GB46750 要求,所以不会生成目标。';
|
|
const UID_NOTE='坐标系待核实 · 原始坐标在目标详情中查看';
|
|
let popFor=null;
|
|
function linkUp(row){const state=row.status?.state;return state==='serial-open'||state==='udp-listening'||state==='tcp-listening';}
|
|
function tone(row){
|
|
if(!row.config?.enabled)return 'idle';
|
|
const s=row.status||{};
|
|
if(s.state==='disconnected')return 'warn';
|
|
if(s.state==='connecting'||s.state==='stopped')return 'info';
|
|
if(s.notice)return 'warn';
|
|
if(!s.receivedBytes)return 'info';
|
|
if(typeof s.lastDataMs==='number'&&Date.now()-s.lastDataMs>10000)return 'info';
|
|
if(row.config.format==='raw')return 'ok';
|
|
if(s.rejectedFrames&&!s.decodedFrames)return 'warn';
|
|
if(!s.acceptedObservations)return 'info';
|
|
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||'未命名接收机',socket=row.devicePlace||'';
|
|
if(socket&&(name===socket||name.endsWith(` · ${socket}`))){
|
|
const head=name===socket?name:name.slice(0,name.length-socket.length-3);
|
|
return {head:head||name,place:socket};
|
|
}
|
|
if(row.deviceKind&&(name===row.deviceKind||name.startsWith(`${row.deviceKind} · `))){
|
|
const rest=name===row.deviceKind?'':name.slice(row.deviceKind.length+3);
|
|
return {head:row.deviceKind,place:socket||rest||'—'};
|
|
}
|
|
if(socket)return {head:name,place:socket};
|
|
if(row.config.transport!=='serial')return {head:name,place:'网络 · 手动添加'};
|
|
const cut=name.indexOf(' · ');
|
|
return cut<0?{head:name,place:'—'}:{head:name.slice(0,cut),place:name.slice(cut+3)};
|
|
}
|
|
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=[],s=row.status||{},enabled=!!row.config?.enabled;
|
|
if(enabled&&s.lastError&&!linkUp(row))list.push(s.lastError);
|
|
if(enabled&&s.notice)list.push(linkUp(row)?GB_NOTE:`${s.notice}。${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) {
|
|
const r=await fetch(url,{method,headers:body?{'Content-Type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});
|
|
const v=await r.json().catch(()=>({}));if(!r.ok)throw new Error(v.error||`请求失败 (${r.status})`);return v;
|
|
}
|
|
function el(tag,text,className) {const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(className)e.className=className;return e;}
|
|
function render(){
|
|
const focused=document.activeElement?.dataset.rxFocus;
|
|
const query=$('rx-search').value.trim().toLowerCase();
|
|
const list=rows.filter(r=>`${r.name} ${r.deviceKind||''} ${r.devicePlace||''} ${r.id} ${r.hardwareId||''} ${r.config.serialPort} ${r.config.bindIp}`.toLowerCase().includes(query));
|
|
const watching=rows.filter(r=>r.detector&&r.config.enabled).length;
|
|
$('rx-summary').textContent=`${rows.length} 个串口 · ${watching} 台侦测机已启用`;
|
|
$('rx-cards').replaceChildren(...list.map(row=>{
|
|
const idn=identity(row),toneName=tone(row),lines=faults(row);
|
|
const c=el('article',undefined,`rx-card rx-${toneName}`);
|
|
const title=el('h2',idn.head);title.title=row.name||idn.head;
|
|
const place=el('p',idn.place,'rx-place');place.title=idn.place;
|
|
const pills=el('div',undefined,'rx-pills'),statusText=cardStatus(row);
|
|
const status=el('span',statusText,`rx-pill rx-${toneName}`);status.title=statusText;
|
|
pills.append(status,el('span',roleLabel(row),'rx-pill rx-role'));
|
|
const meta=el('p',undefined,'rx-meta'),portText=endpoint(row),protocolText=protocols[row.config.format]||row.config.format;
|
|
const port=el('span',portText);port.title=portText;meta.append(port,el('span',protocolText,'rx-protocol'));
|
|
const 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(selected)diagnostics();
|
|
}
|
|
async function refresh(){if(pending||!$('rx-cards'))return;pending=true;try{const v=await api('/api/receivers');rows=v.receivers||[];$('rx-error').textContent=v.error||'';$('rx-error').hidden=!v.error;render();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;}finally{pending=false;}}
|
|
async function mutate(action){if(busy)return;busy=true;render();try{await action();await refresh();}catch(e){$('rx-error').hidden=false;$('rx-error').textContent=e.message;if($('rx-drawer').open)$('rx-message').textContent=e.message;}finally{busy=false;render();}}
|
|
function fields(){const f=$('rx-form');$('rx-serial-fields').hidden=f.elements.transport.value!=='serial';$('rx-network-fields').hidden=f.elements.transport.value==='serial';$('rx-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 diagnostics(){const row=rows.find(r=>r.id===selected);$('rx-status-label').textContent=row?state(row):'保存接收机后可查看诊断';const s=row?.status;const stats=s?[['设备种类',row.deviceKind||'—'],['插口位置',row.devicePlace||'—'],['设备 ID',row.hardwareId||row.id],['接收字节',s.receivedBytes],['解码帧',s.decodedFrames],['接受更新',s.acceptedObservations],['拒绝帧',s.rejectedFrames],['忽略日志',s.ignoredLines],['无效目标',s.invalidTargets],['最近接收',s.lastDataMs?new Date(s.lastDataMs).toLocaleTimeString():'—'],['连接错误',s.lastError||'无'],...(s.notice?[['帧头提示',s.notice]]:[])]:[];$('rx-stats').replaceChildren(...stats.flatMap(([k,v])=>[el('dt',k),el('dd',String(v))]));$('rx-capture').disabled=!row;}
|
|
function open(row){closePop();selected=row?.id||null;dirty=false;$('rx-title').textContent=row?.name||'添加接收机';$('rx-message').textContent='';$('rx-raw').textContent='尚未读取。最多显示最近 4 KiB。';const f=$('rx-form'),config=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 init(){if(initialized||!$('rx-cards'))return;initialized=true;$('rx-add').onclick=()=>open(null);$('rx-refresh').onclick=refresh;$('rx-search').oninput=render;$('rx-close').onclick=close;$('rx-drawer').addEventListener('cancel',e=>{e.preventDefault();close();});$('rx-form').oninput=()=>{dirty=true;fields();};$('rx-form').onchange=()=>{dirty=true;fields();};$('rx-config-tab').onclick=()=>tab(false);$('rx-diagnostic-tab').onclick=()=>tab(true);
|
|
$('rx-form').onsubmit=async e=>{e.preventDefault();if(busy)return;const f=e.target,config={};for(const key of Object.keys(defaults))config[key]=key==='enabled'?f.elements[key].checked:['baudRate','port'].includes(key)?Number(f.elements[key].value):f.elements[key].value;await mutate(async()=>{const v=await api(selected?`/api/receivers/${selected}`:'/api/receivers',selected?'PUT':'POST',{name:f.elements.name.value,config});selected=v.receiver.id;dirty=false;$('rx-message').textContent='配置已保存。接收状态以实时诊断为准。';$('rx-title').textContent=v.receiver.name;$('rx-delete').hidden=selected==='default';});};
|
|
$('rx-delete').onclick=()=>{if(!selected||!confirm('删除此接收机配置并停止该接收任务?其他接收机不受影响。'))return;mutate(async()=>{await api(`/api/receivers/${selected}`,'DELETE');dirty=false;close();});};
|
|
$('rx-capture').onclick=async()=>{if(!selected)return;try{const v=await api(`/api/receivers/${selected}/capture`);const bytes=Uint8Array.from((v.data.match(/[0-9a-f]{2}/ig)||[]).map(x=>parseInt(x,16)));$('rx-raw').textContent=`UTF-8(损坏字节以替代符显示)\n${new TextDecoder().decode(bytes)}\n\nHEX\n${v.data||'尚无数据'}`;}catch(e){$('rx-message').textContent=e.message;}};
|
|
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);
|
|
}
|
|
document.addEventListener('DOMContentLoaded',init);window.addEventListener('rid-workspace-view',()=>{init();if(document.body.dataset.screen==='receivers')refresh();});init();
|