perf(simulation): push current previews and streamline native sensor startup
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { lazy, Suspense, useEffect, useState } from "react";
|
||||
import { LoadingRegion } from "@nodedc/ui-react";
|
||||
import { polygonRequest } from "../../core/simulation/aiPolygon";
|
||||
import { connectPreviewStream } from "../../core/simulation/previewStream";
|
||||
const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview})));
|
||||
export interface InferencePreview {
|
||||
frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban";
|
||||
@@ -12,17 +12,7 @@ export function useInferencePreview(runId:string|undefined,active:boolean) {
|
||||
const [preview,setPreview]=useState<InferencePreview|null>(null);
|
||||
useEffect(()=>{
|
||||
setPreview(null);if(!runId || !active)return;
|
||||
const abort=new AbortController();let timer=0;
|
||||
const poll=async()=>{
|
||||
try {
|
||||
if(document.visibilityState==="visible") {
|
||||
const value=await polygonRequest<InferencePreview|null>(`/runs/${runId}/inference-preview`,{signal:abort.signal});
|
||||
if(!abort.signal.aborted)setPreview(value);
|
||||
}
|
||||
} catch { /* Main status owns connection errors; retain the dated last frame. */ }
|
||||
if(!abort.signal.aborted)timer=window.setTimeout(()=>void poll(),500);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
return connectPreviewStream<InferencePreview>(runId,setPreview);
|
||||
},[runId,active]);
|
||||
return preview;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** One visible subscriber; reconnect reads the latest frame, never a backlog. */
|
||||
export function connectPreviewStream<T>(runId:string,receive:(value:T)=>void,
|
||||
create:(url:string)=>EventSource=url=>new EventSource(url),
|
||||
visibility:Pick<Document,'visibilityState'|'addEventListener'|'removeEventListener'>=document) {
|
||||
let events:EventSource|null=null, disposed=false, ended=false;
|
||||
const close=()=>{events?.close();events=null;};
|
||||
const update=()=>{
|
||||
close();
|
||||
if(disposed || ended || visibility.visibilityState!=='visible')return;
|
||||
const stream=create(`/api/v1/ai-polygon/runs/${encodeURIComponent(runId)}/inference-preview/events`);
|
||||
events=stream;
|
||||
stream.onmessage=event=>{
|
||||
if(events!==stream)return;
|
||||
try {receive(JSON.parse(event.data) as T);}catch {/* Retain the dated last valid frame. */}
|
||||
};
|
||||
stream.addEventListener('end',()=>{if(events===stream){ended=true;close();}});
|
||||
};
|
||||
visibility.addEventListener('visibilitychange',update);
|
||||
update();
|
||||
return()=>{disposed=true;close();visibility.removeEventListener('visibilitychange',update);};
|
||||
}
|
||||
Reference in New Issue
Block a user