feat(simulation): add Polygon live worker gateway
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
GlassSurface,
|
||||
StatusBadge,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
fetchPolygonVehicleState,
|
||||
fetchPolygonWorkerStatus,
|
||||
startPolygonWorker,
|
||||
stopPolygonWorker,
|
||||
type PolygonVehicleState,
|
||||
type PolygonWorkerStatus,
|
||||
} from "../core/polygon/liveWorker";
|
||||
|
||||
function message(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
return "Simulation Worker не подтвердил операцию.";
|
||||
}
|
||||
|
||||
function yawDegrees(state: PolygonVehicleState): number {
|
||||
const { x, y, z, w } = state.orientation;
|
||||
return Math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) * 180 / Math.PI;
|
||||
}
|
||||
|
||||
function trajectoryPoints(states: PolygonVehicleState[]): {
|
||||
points: string;
|
||||
roverX: number;
|
||||
roverY: number;
|
||||
} {
|
||||
if (!states.length) return { points: "", roverX: 50, roverY: 50 };
|
||||
const xs = states.map(({ position }) => position.x);
|
||||
const ys = states.map(({ position }) => position.y);
|
||||
const minimumX = Math.min(...xs);
|
||||
const maximumX = Math.max(...xs);
|
||||
const minimumY = Math.min(...ys);
|
||||
const maximumY = Math.max(...ys);
|
||||
const span = Math.max(maximumX - minimumX, maximumY - minimumY, 4);
|
||||
const centerX = (minimumX + maximumX) / 2;
|
||||
const centerY = (minimumY + maximumY) / 2;
|
||||
const project = (state: PolygonVehicleState) => ({
|
||||
x: 50 + ((state.position.x - centerX) / span) * 80,
|
||||
y: 50 - ((state.position.y - centerY) / span) * 80,
|
||||
});
|
||||
const projected = states.map(project);
|
||||
const rover = projected[projected.length - 1];
|
||||
return {
|
||||
points: projected.map(({ x, y }) => `${x.toFixed(2)},${y.toFixed(2)}`).join(" "),
|
||||
roverX: rover.x,
|
||||
roverY: rover.y,
|
||||
};
|
||||
}
|
||||
|
||||
export function PolygonLivePanel() {
|
||||
const [worker, setWorker] = useState<PolygonWorkerStatus | null>(null);
|
||||
const [live, setLive] = useState<PolygonVehicleState | null>(null);
|
||||
const [trajectory, setTrajectory] = useState<PolygonVehicleState[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [actionBusy, setActionBusy] = useState(false);
|
||||
const [generation, setGeneration] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionBusy) return;
|
||||
const controller = new AbortController();
|
||||
let timer: number | null = null;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const status = await fetchPolygonWorkerStatus({ signal: controller.signal });
|
||||
if (controller.signal.aborted) return;
|
||||
setWorker(status);
|
||||
setError(null);
|
||||
if (status.available && status.activeRunId && status.runState === "running") {
|
||||
const state = await fetchPolygonVehicleState({ signal: controller.signal });
|
||||
if (controller.signal.aborted) return;
|
||||
setLive(state);
|
||||
setTrajectory((current) => {
|
||||
const sameRun = current[0]?.runId === state.runId;
|
||||
const next = sameRun ? [...current, state] : [state];
|
||||
return next.slice(-120);
|
||||
});
|
||||
} else {
|
||||
setLive(null);
|
||||
if (!status.activeRunId) setTrajectory([]);
|
||||
}
|
||||
} catch (pollError) {
|
||||
if (controller.signal.aborted) return;
|
||||
setError(message(pollError));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
timer = window.setTimeout(() => void poll(), 1_000);
|
||||
}
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
return () => {
|
||||
controller.abort();
|
||||
if (timer !== null) window.clearTimeout(timer);
|
||||
};
|
||||
}, [actionBusy, generation]);
|
||||
|
||||
const projected = useMemo(() => trajectoryPoints(trajectory), [trajectory]);
|
||||
const runActive = Boolean(worker?.activeRunId);
|
||||
|
||||
const runAction = async () => {
|
||||
if (!worker?.controlAvailable || actionBusy) return;
|
||||
setActionBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
const next = worker.activeRunId
|
||||
? await stopPolygonWorker(worker.activeRunId, { idempotencyKey })
|
||||
: await startPolygonWorker({ idempotencyKey });
|
||||
setWorker(next);
|
||||
if (!next.activeRunId) {
|
||||
setLive(null);
|
||||
setTrajectory([]);
|
||||
}
|
||||
setGeneration((value) => value + 1);
|
||||
} catch (actionError) {
|
||||
setError(message(actionError));
|
||||
} finally {
|
||||
setActionBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<GlassSurface className="polygon-live-panel" padding="lg">
|
||||
<header className="polygon-live-heading">
|
||||
<div>
|
||||
<span className="section-eyebrow">ПОЛИГОН / LIVE</span>
|
||||
<h2>Stock Ackermann Rover</h2>
|
||||
<p>PX4/Gazebo исполняются на отдельном worker; браузер показывает канонический срез.</p>
|
||||
</div>
|
||||
<div>
|
||||
<StatusBadge
|
||||
tone={worker?.available ? (runActive ? "accent" : "success") : "neutral"}
|
||||
>
|
||||
{worker?.available ? (runActive ? "Симуляция идёт" : "Worker готов") : "Worker offline"}
|
||||
</StatusBadge>
|
||||
<Button
|
||||
size="compact"
|
||||
variant={runActive ? "secondary" : "primary"}
|
||||
disabled={!worker?.controlAvailable || actionBusy}
|
||||
onClick={() => void runAction()}
|
||||
>
|
||||
{actionBusy ? "Ожидаем PX4/Gazebo…" : runActive ? "Остановить" : "Запустить"}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="polygon-live-layout">
|
||||
<div className="polygon-live-map" aria-label="Live-траектория ровера в ENU">
|
||||
<svg viewBox="0 0 100 100" role="img">
|
||||
<defs>
|
||||
<pattern id="polygon-grid" width="10" height="10" patternUnits="userSpaceOnUse">
|
||||
<path d="M 10 0 L 0 0 0 10" />
|
||||
</pattern>
|
||||
<radialGradient id="polygon-rover-glow">
|
||||
<stop offset="0" stopColor="rgb(var(--nodedc-accent-rgb))" stopOpacity="0.9" />
|
||||
<stop offset="1" stopColor="rgb(var(--nodedc-accent-rgb))" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<rect width="100" height="100" fill="url(#polygon-grid)" />
|
||||
<line x1="8" y1="92" x2="25" y2="92" className="polygon-live-axis-x" />
|
||||
<line x1="8" y1="92" x2="8" y2="75" className="polygon-live-axis-y" />
|
||||
<text x="27" y="94">E</text>
|
||||
<text x="5" y="72">N</text>
|
||||
{projected.points && (
|
||||
<polyline points={projected.points} className="polygon-live-trajectory" />
|
||||
)}
|
||||
{live && (
|
||||
<g
|
||||
transform={
|
||||
`translate(${projected.roverX} ${projected.roverY}) rotate(${-yawDegrees(live)})`
|
||||
}
|
||||
>
|
||||
<circle r="7" fill="url(#polygon-rover-glow)" />
|
||||
<path d="M -3 -2.5 L 4 0 L -3 2.5 Z" className="polygon-live-rover" />
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
{!live && (
|
||||
<div>
|
||||
<strong>{worker?.available ? "Ровер не запущен" : "Нет связи с worker"}</strong>
|
||||
<span>После старта здесь появится ground-truth траектория из Gazebo.</span>
|
||||
</div>
|
||||
)}
|
||||
<small>map_enu · base_link_flu · diagnostic ground truth</small>
|
||||
</div>
|
||||
|
||||
<div className="polygon-live-telemetry">
|
||||
<div>
|
||||
<span>Прогон</span>
|
||||
<strong>{worker?.activeRunId ?? "—"}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Sim time</span>
|
||||
<strong>{live ? `${(live.simTimeNs / 1e9).toFixed(2)} s` : "—"}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Позиция ENU</span>
|
||||
<strong>
|
||||
{live
|
||||
? `${live.position.x.toFixed(2)} · ${live.position.y.toFixed(2)} · ${live.position.z.toFixed(2)} m`
|
||||
: "—"}
|
||||
</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Провайдеры</span>
|
||||
<strong>{worker?.providerIds.join(" · ") || "—"}</strong>
|
||||
</div>
|
||||
<div className="polygon-live-boundary">
|
||||
<StatusBadge tone="success">Virtual only</StatusBadge>
|
||||
<p>
|
||||
Нет actuator authority. Live-поза диагностическая и пока не доказывает
|
||||
приёмку PX4/ROS 2 telemetry, navigation или safety.
|
||||
</p>
|
||||
</div>
|
||||
{error && <p className="polygon-live-error">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</GlassSurface>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type PolygonRunRoute,
|
||||
type PolygonRunState,
|
||||
} from "../core/polygon/runArchive";
|
||||
import { PolygonLivePanel } from "./PolygonLivePanel";
|
||||
|
||||
interface PolygonRunWorkspaceProps {
|
||||
route: PolygonRunRoute;
|
||||
@@ -113,6 +114,7 @@ export function PolygonRunWorkspace({ route }: PolygonRunWorkspaceProps) {
|
||||
if (loading && !detail) {
|
||||
return (
|
||||
<div className="standard-workspace polygon-run-workspace">
|
||||
<PolygonLivePanel />
|
||||
<GlassSurface className="polygon-run-message" padding="lg">
|
||||
<StatusBadge tone="accent">Только чтение</StatusBadge>
|
||||
<h2>Проверяем журнал прогона</h2>
|
||||
@@ -125,6 +127,7 @@ export function PolygonRunWorkspace({ route }: PolygonRunWorkspaceProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<div className="standard-workspace polygon-run-workspace">
|
||||
<PolygonLivePanel />
|
||||
<GlassSurface className="polygon-run-message" padding="lg">
|
||||
<StatusBadge tone="danger">Данные недоступны</StatusBadge>
|
||||
<h2>UI-0 не может открыть прогон</h2>
|
||||
@@ -144,6 +147,7 @@ export function PolygonRunWorkspace({ route }: PolygonRunWorkspaceProps) {
|
||||
if (!detail) {
|
||||
return (
|
||||
<div className="standard-workspace polygon-run-workspace">
|
||||
<PolygonLivePanel />
|
||||
<GlassSurface className="polygon-run-message" padding="lg">
|
||||
<StatusBadge tone="neutral">Журнал пуст</StatusBadge>
|
||||
<h2>Квалификационных прогонов пока нет</h2>
|
||||
@@ -156,13 +160,14 @@ export function PolygonRunWorkspace({ route }: PolygonRunWorkspaceProps) {
|
||||
const { run } = detail;
|
||||
return (
|
||||
<div className="standard-workspace polygon-run-workspace">
|
||||
<PolygonLivePanel />
|
||||
<section className="workspace-lead workspace-lead--compact">
|
||||
<div>
|
||||
<span className="section-eyebrow">ПОЛИГОН / КВАЛИФИКАЦИОННЫЙ ПРОГОН</span>
|
||||
<h2>{run.runId}</h2>
|
||||
<p>
|
||||
Канонический журнал Mission Core. Экран не содержит lifecycle-операций,
|
||||
команд управления или доступа к физическим актуаторам.
|
||||
Канонический архив Mission Core. Lifecycle live-контура отделён от истории;
|
||||
команд физическим актуаторам и реального управления здесь нет.
|
||||
</p>
|
||||
</div>
|
||||
<div className="polygon-run-lead-status">
|
||||
|
||||
Reference in New Issue
Block a user