Files

454 lines
22 KiB
JavaScript

(function () {
'use strict';
// Translate the authorized reference view's shapes at one boundary. Business
// rules, session checks, persistence, and receiver ownership stay in RID.
async function request(path, method = 'GET', body, options = {}) {
const response = await fetch(path, {
...options, method, cache: 'no-store', credentials: 'same-origin',
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
});
if (response.status === 401) {
location.replace('/workbench/');
throw new Error('会话已结束,请重新登录');
}
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const error = new Error(data.error || data.message || `RID 服务返回 HTTP ${response.status}`);
error.status = response.status;
throw error;
}
return data;
}
let receivers;
let receiverRequest;
let receiversAt = -Infinity;
async function receiverRows(refresh = false) {
if (!refresh && receivers && performance.now() - receiversAt < 900) return receivers;
if (!receiverRequest) {
receiverRequest = request('/api/receivers').then(data => {
if (data.error) throw new Error(data.error);
receiversAt = performance.now();
return receivers = data.receivers;
}).finally(() => { receiverRequest = null; });
}
return receiverRequest;
}
const stateLabels = {
'serial-open': '串口已打开', 'udp-listening': 'UDP 正在监听', 'tcp-listening': 'TCP 正在监听',
'connecting': '正在连接', 'disconnected': '连接中断', 'stopped': '未连接'
};
function link(row) {
const state = row?.status?.state;
const serial = row?.config.transport === 'serial';
const lastData = serial ? row.status?.lastValidFrameMs : row?.status?.lastDataMs;
const connected = Boolean(row?.config.enabled && ['serial-open', 'udp-listening', 'tcp-listening'].includes(state));
const receiving = connected && lastData != null && Date.now() - lastData <= 15000;
const tcp = row?.config.transport === 'tcp-listen';
let message = row?.status?.lastError || stateLabels[state] || '未连接';
if (connected && tcp) {
const peer = row.status.lastPeerIp;
message = receiving && peer ? '接收中 · ' + peer : 'TCP 监听中 · 等待数据';
}
if (connected && serial) message = receiving ? '串口接收中' : '串口已打开 · 等待有效报文';
return { connected, receiving, message };
}
function isStation(row) {
if (row.config.transport !== 'serial') return true;
return row.status.lastValidFrameMs != null || Boolean(row.userConfigured && row.config.serialPort);
}
async function sourceStatus() {
const rows = await receiverRows();
const serial = rows.filter(row => row.config.transport === 'serial');
const tcp = rows.filter(row => row.config.transport === 'tcp-listen');
const udp = rows.filter(row => row.config.transport === 'udp');
const collection = list => list.find(row => link(row).connected) || list[0];
return {
usb: link(collection(serial)), ble: { connected: false, message: '本阶段未接入 BLE' },
tcp: link(collection(tcp)), udp: link(collection(udp)), tcpDevices: tcp.map(link)
};
}
async function changeSerial(body, enabled) {
if (!/^COM[1-9]\d*$/i.test(body.port || '')) throw new Error('请先选择串口');
const port = body.port.toUpperCase();
const rows = await receiverRows(true);
const serial = rows.find(row => row.config.transport === 'serial' && row.config.serialPort === port);
if (!serial && !enabled) return { ok: true, connected: false, message: '该串口未被本平台打开' };
const code = serial ? `/api/receivers/${encodeURIComponent(serial.id)}` : '/api/receivers';
const config = { ...(serial?.config || { transport: 'serial', format: 'raw' }), enabled, serialPort: port };
if (enabled) config.baudRate = Number(body.baud);
await request(code, serial ? 'PUT' : 'POST', { name: serial?.name || `USB 串口 ${port}`, config });
receiversAt = -Infinity;
return { ok: true, connected: false, message: enabled ? '已启动串口接收任务,等待设备状态' : '串口已断开' };
}
const targets = new Map();
let ownership = new Map();
let lastFrame = -Infinity;
let stream;
let retry;
let stopped = false;
function applyFrame(frame) {
if (frame.snapshot) targets.clear();
for (const id of frame.removed) targets.delete(id);
for (const target of frame.targets) targets.set(target.observation.target_id, target);
lastFrame = performance.now();
if (frame.snapshot || frame.targets.length || frame.removed.length) {
window.dispatchEvent(new Event('rid-live-frame'));
}
}
function connectStream() {
if (stopped || stream) return;
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
stream = new WebSocket(`${protocol}//${location.host}/api/realtime/ws?format=json`);
stream.onmessage = ({ data }) => {
try {
const frame = JSON.parse(data);
applyFrame(frame);
stream.send(String(frame.sequence));
} catch (_) {
stream.close();
}
};
stream.onclose = () => {
stream = null;
if (!stopped) retry = setTimeout(connectStream, 2500);
};
}
window.addEventListener('pagehide', () => { stopped = true; clearTimeout(retry); stream?.close(); });
window.addEventListener('pageshow', () => { stopped = false; connectStream(); });
let rules = [];
let rulesExpires = 0;
let pendingRules;
function modelRules(refresh = false) {
if (!refresh && performance.now() < rulesExpires) return Promise.resolve(rules);
return pendingRules ??= request('/api/workbench/models').then(data => {
rulesExpires = performance.now() + 10000;
return rules = data.entries;
}).finally(() => { pendingRules = null; });
}
const modelRuleIndexes = new WeakMap();
function indexModelRules(entries) {
let index = modelRuleIndexes.get(entries);
if (index) return index;
const prefixes = new Map();
const keywords = [];
for (const rule of entries) {
if (!rule.enabled) continue;
if (rule.field === 'serial') prefixes.set(rule.pattern.toUpperCase(), rule);
else if (rule.field === 'target' || rule.field === 'model') keywords.push(rule);
}
const lengths = [...new Set([...prefixes.keys()].map(prefix => prefix.length))].sort((a, b) => b - a);
index = {prefixes, lengths, keywords};
modelRuleIndexes.set(entries, index);
return index;
}
function resolveModel(targetId, reported, entries = rules, serial) {
const {prefixes, lengths, keywords} = indexModelRules(entries);
const sn = (serial || '').trim().toUpperCase();
let match;
for (const length of lengths) {
if (length > sn.length) continue;
match = prefixes.get(sn.slice(0, length));
if (match) break;
}
if (!match) {
const ident = (targetId || '').toLowerCase();
const model = (reported || '').toLowerCase();
match = keywords.find(rule => (rule.field === 'target' ? ident : model).includes(rule.pattern));
}
if (!match) return reported;
const vendor = match.vendor.toLowerCase();
const name = match.model.toLowerCase();
if (match.field === 'serial' && (name === vendor || name.startsWith(vendor + ' '))) {
return match.model;
}
return [match.vendor, match.model].filter(Boolean).join(' ');
}
function detectionReceiver(id) {
const row = receivers?.find(receiver => receiver.id === id);
if (!row) return null;
// A network receiver with no peer restriction cannot identify which sender owns its last GNSS fix.
const identified = row.config.transport === 'serial'
|| (row.config.transport === 'tcp-listen' && !!row.config.peerIp);
const fresh = performance.now() - receiversAt <= 5000;
return {name: row.name, gnss: identified && fresh ? row.status.gnss : null};
}
async function liveRows() {
if (performance.now() - lastFrame > 2000) {
const frame = await request('/api/realtime/snapshot');
if (performance.now() - lastFrame > 2000) applyFrame(frame);
}
await Promise.all([modelRules().catch(() => rules), refreshOwnership()]);
return cachedLiveRows();
}
async function registrations(ids) {
const unique = [...new Set(ids)];
const batches = [];
for (let start = 0; start < unique.length; start += 96) {
const params = new URLSearchParams({ids: unique.slice(start, start + 96).join(',')});
batches.push(request('/api/target-registration-status?' + params));
}
const rows = (await Promise.all(batches)).flatMap(response => response.entries);
return new Map(rows.map(row => [row.targetId, row]));
}
let ownershipRequest;
let flightAssessments = new Map();
function refreshOwnership() {
return ownershipRequest ??= Promise.all([registrations(targets.keys()),request("/api/flight-status")]).then(([rows,status]) => {
ownership = rows;
flightAssessments = new Map(status.entries.map(row=>[row.targetId,row]));
}).catch(error => {flightAssessments.clear();console.warn('飞行状态暂不可用', error.message);})
.finally(() => { ownershipRequest = null; });
}
function registrationInfo(status) {
if (!status) return {};
const registryClass = status.listKind === 'black' ? 'blacklist'
: status.listKind === 'white' ? 'whitelist' : status.registered ? 'registered' : 'unregistered';
return { registered: status.registered, registryClass };
}
function cachedLiveRows() {
return [...targets.values()].map(target => {
const observation = target.observation;
const telemetry = observation.telemetry || {};
const source = target.sources?.find(source => source.observation.receiver_id === observation.receiver_id);
return {
uasId: observation.target_id, model: resolveModel(observation.target_id, telemetry.model || telemetry.name, rules, telemetry.serial) || 'RID 目标', bssid: telemetry.mac,
lat: observation.latitude, lng: observation.longitude, alt: observation.altitude_m,
pilotLat: telemetry.pilot_position?.[1], pilotLng: telemetry.pilot_position?.[0],
geometricAltitude: telemetry.geometric_altitude_m, pressureAltitude: telemetry.pressure_altitude_m,
heightAgl: telemetry.height_agl_m, relativeHeight: telemetry.relative_height_m,
speed: telemetry.speed_mps, rssi: telemetry.rssi, heading: observation.heading_deg,
source: observation.receiver_id, time: timestamp(target.received_at_ms), online: true,
sourceCount: target.sources?.length || 1,
receivedAtMs: source?.received_at_ms ?? target.received_at_ms, positionGeneration: target.position_generation,
sampleId: [observation.receiver_id, observation.source_epoch, observation.sequence].join(':'),
...registrationInfo(ownership.get(observation.target_id)),
flightClass: flightAssessments.get(observation.target_id)?.class || "unknown",
flightReason: flightAssessments.get(observation.target_id)?.reason,
positionUnverified: telemetry.position_unverified === true
};
});
}
function projectFence(fence) {
const geometry = fence.geometry;
const point = ([lng, lat]) => ({ lat, lng });
let type = geometry.type;
let points = geometry.vertices?.map(point);
if (type === 'circle') points = [{ ...point(geometry.center), radius: geometry.radius_m }];
if (type === 'polygon' && points.length === 4
&& new Set(points.map(point => point.lat)).size === 2
&& new Set(points.map(point => point.lng)).size === 2) {
type = 'rectangle';
points = [points[0], points[2]];
}
return { id: fence.id, name: fence.name, enabled: fence.enabled, type, points };
}
async function saveZone(method, id, body) {
const snapshot = await request('/api/geofences');
const existing = snapshot.entries.find(zone => zone.id === id);
if (id && !existing) throw new Error('防控区已变更,请刷新后重试');
if (method === 'DELETE') {
await request(`/api/geofences/${encodeURIComponent(id)}?revision=${snapshot.revision}`, method);
return { ok: true };
}
if (!id) id = `zone-${crypto.randomUUID()}`;
const coord = point => [point.lng, point.lat];
let geometry = existing?.geometry;
if (!geometry && body.type === 'circle') {
geometry = { type: 'circle', center: coord(body.points[0]), radius_m: body.points[0].radius };
} else if (!geometry && body.type === 'rectangle') {
const [a, b] = body.points;
geometry = { type: 'polygon', vertices: [coord(a), [a.lng, b.lat], coord(b), [b.lng, a.lat]] };
} else if (!geometry) {
geometry = { type: 'polygon', vertices: body.points.map(coord) };
}
await request(`/api/geofences/${encodeURIComponent(id)}`, 'PUT', {
expected_revision: snapshot.revision, fence: { id, name: body.name, enabled: body.enabled === true, geometry }
});
return { ok: true, id };
}
function timestamp(ms) {
return new Date(ms).toLocaleString('sv-SE', { hourCycle: 'h23' });
}
function dateArgument(value, fallback) {
if (!value) return fallback;
const result = new Date(value.replace(' ', 'T')).getTime();
if (!Number.isSafeInteger(result) || result < 0) throw new Error('日期范围无效');
return result;
}
function range(query) {
return {
fromMs: dateArgument(query.get('start'), 0),
toMs: dateArgument(query.get('end'), Date.now()),
q: query.get('keyword') || ''
};
}
async function events(query, limit = 100, offset, center = false) {
const { fromMs, toMs, q } = range(query);
const params = new URLSearchParams({ limit, from_ms: fromMs, to_ms: toMs, q: q === '未登记' || q === '未登记无人机告警' ? '' : q });
if (q === '未登记' || q === '未登记无人机告警') params.set('type','unregistered');
if (query.get('type')) params.set('type',query.get('type'));
if (query.get('handled')) params.set('handled', query.get('handled') === '1' ? '1' : '0');
if (offset !== undefined) params.set('offset', offset);
if (query.has('before')) params.set('before', query.get('before'));
if (query.has('after')) params.set('after', query.get('after'));
if (query.has('counts')) params.set('counts', '1');
const data = await request(`/api/monitoring/${center ? 'center' : 'events'}?${params}`);
const alerts = data.entries.map(event => ({
id: event.id, time: timestamp(event.occurred_at_ms), timeMs: event.occurred_at_ms,
uasId: event.target_id, lat: event.latitude, lng: event.longitude, kind: event.event_type,
type: window.ridFlightStatus.meta(event.event_type).label,
message: event.event_type === 'unregistered' ? '设备登记中未找到该目标' : event.fence_name || event.target_id,
handled: event.acknowledged_at_ms != null,
acknowledgedBy: event.acknowledged_by
}));
return { alerts, count: data.total ?? alerts.length, read: data.read, unread: data.unread };
}
async function getFlights(query) {
const params = new URLSearchParams({ ...range(query), limit: 120 });
const response = await request('/api/workbench/observations?' + params);
const flights = response.entries.map(row => ({
uasId: row.targetId, flightId: row.flightKey, model: row.model || row.targetId,
start: timestamp(row.timeMs), end: row.endMs == null ? '接收中' : timestamp(row.endMs),
lastLat: row.latitude, lastLng: row.longitude
}));
return { flights, total: response.total };
}
async function getPoints(flightKey) {
const points = [];
let after = 0;
do {
const params = new URLSearchParams({ flightKey, after, limit: 5000 });
const row = await request('/api/history/flight-points?' + params);
points.push(...row.entries);
after = row.nextAfter;
} while (after);
return window.ridDroneMap.prepareTrack(points).points.map(point => {
const osd = point.osd || {};
return {
lat: point.latitude, lng: point.longitude, alt: point.altitudeM,
heading: point.headingDeg, time: timestamp(point.timeMs), timeMs: point.timeMs, segmentStart: point.segmentStart,
speed: osd.speedMps, verticalSpeed: osd.verticalSpeedMps, rssi: osd.rssi,
height: osd.heightAglM, relativeHeight: osd.relativeHeightM,
geometricAltitude: osd.geometricAltitudeM, pressureAltitude: osd.pressureAltitudeM,
pilotLat: osd.pilotPosition?.[1], pilotLng: osd.pilotPosition?.[0]
};
});
}
async function summary() {
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
const [live, links, rows, fences, lists, recentAlerts, historyStats, alertStats] = await Promise.all([
liveRows(), sourceStatus(), receiverRows(), request('/api/geofences'), request('/api/target-lists'),
events(new URLSearchParams(), 6).then(result => result.alerts), request(`/api/history/summary?fromMs=${midnight.getTime()}`),
request(`/api/monitoring/summary?from_ms=${midnight.getTime()}`)
]);
const userData = await request('/api/auth/users').catch(error => {
if (error.status !== 403) throw error;
});
return {
...links, onlineCount: live.length, targetCount: live.length, zones: fences.entries.length,
deviceTotal: rows.length, userTotal: userData?.entries.length, registryTotal: lists.entries.length,
recentAlerts, recentRecords: historyStats.recent.map(point => ({ time: timestamp(point.timeMs), uasId: point.targetId, lat: point.latitude, lng: point.longitude })),
recordsToday: historyStats.since, recordsTotal: historyStats.total, alertsToday: alertStats.since, alertsTotal: alertStats.total
};
}
async function read(route, params) {
switch (route) {
case '/api/current_user': {
const account = await request('/api/auth/status');
if (!account.authenticated) { location.replace('/workbench/'); throw new Error('请重新登录'); }
return { user: { displayName: account.username, role: roleLabel(account.role), canAcknowledge: ['admin', 'operator'].includes(account.role) } };
}
case '/api/platform_configs': {
const prefs = await request('/api/maps/preferences');
return { configs: [{ key: 'default_map', value: prefs.basemap === 'road' ? 'tdt-vector' : 'tdt-satellite' }] };
}
case '/api/status': return sourceStatus();
case '/api/drones': {
const [drones, status] = await Promise.all([liveRows(), sourceStatus()]);
return { drones, count: drones.length, onlineCount: drones.length, status };
}
case '/api/ports': return (await request('/api/receiver/ports')).ports.map(device => ({ device }));
case '/api/zones': return (await request('/api/geofences')).entries.map(projectFence);
case '/api/alerts': params.set('counts', '1'); return events(params, 50, undefined, true);
case '/api/alerts_query': return events(params, 50, params.get('offset') ?? 0);
case '/api/local_stations': return { stations: (await receiverRows()).filter(isStation).map(row => {
const { connected, receiving, message } = link(row);
return {
id: row.id, name: row.name, sn: row.hardwareId, endpoint: row.status.endpoint,
transport: row.config.transport,
deviceIp: row.status.lastPeerIp || row.config.peerIp,
gnss: row.status.gnss,
status: message, linkState: receiving ? 'online' : connected ? 'waiting' : 'offline'
};
}) };
case '/api/local_fusion_info': return { sources: await sourceStatus() };
case '/api/flights': return getFlights(params);
case '/api/flight_track': return { points: await getPoints(params.get('flightId')) };
case '/api/monitor_summary': return summary();
case '/api/map_cache/status': {
const state = await request('/api/maps/status');
return { enabled: true, offlineOnly: state.mode === 'offline', hasTdtKey: state.keyConfigured };
}
default: throw new Error('此功能尚未接入本阶段');
}
}
async function mutate(route, method, body) {
if (route === '/api/zones' || route.startsWith('/api/zones/')) return saveZone(method, route.split('/')[3], body);
switch (route) {
case '/api/logout': return request('/api/auth/logout', 'POST');
case '/api/connect': return changeSerial(body, true);
case '/api/disconnect':
case '/api/release_port': return changeSerial(body, false);
case '/api/alerts_query':
return request(`/api/monitoring/events/${encodeURIComponent(body.id)}/acknowledgement`, 'PUT', {});
default: throw new Error('此功能尚未接入本阶段');
}
}
function roleLabel(role) {
return ({ admin: '管理员', operator: '操作员', viewer: '只读用户' })[role] || '未知角色';
}
window.ridWorkbenchApi = Object.freeze({
request, modelRules, resolveModel, roleLabel, getRecordPoints: getPoints, cachedLiveRows, detectionReceiver,
async registration(target) { return registrationInfo((await registrations([target])).get(target)); },
preferences: () => request('/api/maps/preferences'),
async fetch(path, options = {}) {
const url = new URL(path, location.origin);
try {
if (url.origin !== location.origin) throw new Error('仅允许访问本机 RID 接口');
const method = options.method || 'GET';
const body = typeof options.body === 'string' ? JSON.parse(options.body) : {};
return Response.json(method === 'GET' ? await read(url.pathname, url.searchParams) : await mutate(url.pathname, method, body));
} catch (error) {
return Response.json({ ok: false, message: error.message, error: error.message }, { status: error.status || 400 });
}
}
});
})();