Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d3329f608 | ||
|
|
399af98841 | ||
|
|
71a648fec8 | ||
|
|
dad11b47d7 | ||
|
|
e627500295 | ||
|
|
f01bd39037 | ||
|
|
a7c64e009d | ||
|
|
6bbbd5bf7d | ||
|
|
bc55901d4d | ||
|
|
6d772b29fe | ||
|
|
63cbb08ea0 | ||
|
|
53818230f9 | ||
|
|
45fb14b206 | ||
|
|
24bbaefb00 |
@@ -11,3 +11,4 @@
|
||||
*.lcc binary
|
||||
apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
|
||||
apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
|
||||
apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
@@ -49,3 +49,10 @@ mqtt.summary.json
|
||||
# Small synthetic/redacted fixtures under tests/fixtures are allowed.
|
||||
!tests/fixtures/**/*.pcap
|
||||
!tests/fixtures/**/*.pcapng
|
||||
|
||||
# Dependency caches may be links into an existing local checkout.
|
||||
.venv
|
||||
node_modules
|
||||
|
||||
# Private experiment evidence and generated build archives.
|
||||
/outputs/
|
||||
|
||||
@@ -62,6 +62,24 @@ and the boundary between Mission Core and vendor-specific integration code.
|
||||
- Synthetic or explicitly redacted fixtures may be committed under
|
||||
`tests/fixtures/`.
|
||||
|
||||
## Onboard environment ownership — owner requirement, 2026-09-24
|
||||
|
||||
- Every onboard OS change belongs to the shipped, versioned installer or the
|
||||
application's environment/device preparation workflow from the first test.
|
||||
The operator installs the build and configures it in the application; never
|
||||
require hand-written service files, USB rules, permission fixes or commands.
|
||||
- This applies to all Node features, including GUI/service autostart and USB
|
||||
recovery, not just individual camera drivers. Read-only SSH inspection and
|
||||
bounded artifact-owned build staging remain allowed.
|
||||
- Detect the distribution, architecture and required capabilities. Maintain
|
||||
explicit supported environment profiles; do not claim arbitrary Linux
|
||||
compatibility from a qualified Ubuntu build. Preserve foreign configuration,
|
||||
report unsupported features, make preparation repeatable, and ship rollback.
|
||||
- Do not add USB administration controls or port resets to inventory refresh.
|
||||
Automatic startup recovery may retry terminal enumeration failures only;
|
||||
preserve enumerated devices and active companion ports. Device identity and
|
||||
assignments must survive changes of USB port and tty number.
|
||||
|
||||
## Insta360 and clean-host installation — owner requirement, 2026-09-08
|
||||
|
||||
- The current X4 starting point is USB enumeration only. SDK installation,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
@nvidia:registry=https://edge.urm.nvidia.com/artifactory/api/npm/omniverse-client-npm/
|
||||
Generated
+23
@@ -15,6 +15,7 @@
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
"@nodedc/ui-core": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core",
|
||||
"@nodedc/ui-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
|
||||
"@nvidia/ov-web-rtc": "6.7.0",
|
||||
"@rerun-io/web-viewer": "0.36.3",
|
||||
"meshoptimizer": "1.1.1",
|
||||
"playcanvas": "2.21.4",
|
||||
@@ -899,6 +900,19 @@
|
||||
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@nvidia/ov-web-rtc": {
|
||||
"version": "6.7.0",
|
||||
"resolved": "https://edge.urm.nvidia.com/artifactory/api/npm/omniverse-client-npm/@nvidia/ov-web-rtc/-/@nvidia/ov-web-rtc-6.7.0.tgz",
|
||||
"integrity": "sha512-Knt393yvuI1tFmQgJM7VuMlVKDh5GyuKq8fAIarNLyY7Ucxw+lSY/72ceWR+3HyCnNtL39J0DZ27dn9riqpGWw==",
|
||||
"license": "SEE LICENSE IN LICENSE.txt",
|
||||
"dependencies": {
|
||||
"is-plain-object": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rerun-io/web-viewer": {
|
||||
"version": "0.36.3",
|
||||
"resolved": "https://registry.npmjs.org/@rerun-io/web-viewer/-/web-viewer-0.36.3.tgz",
|
||||
@@ -1615,6 +1629,15 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-plain-object": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz",
|
||||
"integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
"@nodedc/ui-core": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core",
|
||||
"@nodedc/ui-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
|
||||
"@nvidia/ov-web-rtc": "6.7.0",
|
||||
"@rerun-io/web-viewer": "0.36.3",
|
||||
"meshoptimizer": "1.1.1",
|
||||
"playcanvas": "2.21.4",
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"source": "DCD-006_rover_v020.blend",
|
||||
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
|
||||
"model": "DCD-006 v020 complete rover",
|
||||
"source_object_count": 1426,
|
||||
"render_mesh_count": 1,
|
||||
"original_bounds": [
|
||||
[
|
||||
-0.527999997138977,
|
||||
-0.45249998569488525,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.6350000500679016,
|
||||
0.45249998569488525,
|
||||
0.734000027179718
|
||||
]
|
||||
],
|
||||
"dimensions_m": [
|
||||
1.1630001068115234,
|
||||
0.9049999713897705,
|
||||
0.734000027179718
|
||||
],
|
||||
"translation_m": [
|
||||
-0.05350002646446228,
|
||||
-0.0,
|
||||
-0.0
|
||||
],
|
||||
"glb_bytes": 54960576,
|
||||
"glb_sha256": "15f17f5b5b014e0f65273aa1565b7fb8e46381ca389a3c3d3ca89a32806bfb79",
|
||||
"material_source_sha256": "ac50e29fe9fe7ab4012628c52fce30e262e9e0bba4a4d49abe59a90c84391b2e",
|
||||
"material_rules": {
|
||||
"metal": 1,
|
||||
"rubber": 2,
|
||||
"steel": 6,
|
||||
"paint": 3
|
||||
},
|
||||
"source_saved": false
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 251 KiB |
@@ -822,7 +822,7 @@ export default function App() {
|
||||
/>
|
||||
) : activeDefinition.kind === "missions" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "vehicles" ? null : activeDefinition.kind === "datasets" ? (
|
||||
) : activeDefinition.kind === "vehicles" ? <div ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
|
||||
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
|
||||
) : activeDefinition.kind === "lab-archive" ? (
|
||||
laboratoryAnnotation.control
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {RoverState} from '../../core/fleet/useRoverControl';
|
||||
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
|
||||
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
|
||||
export function RoverTelemetry({state}:{state:RoverState}){
|
||||
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
|
||||
const positions=drivePositions(profile?.layout??null);
|
||||
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
|
||||
id:binding.device_id,uuid:binding.uuid,label:positions[slot]??slot,
|
||||
reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid),
|
||||
}));
|
||||
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
|
||||
return <div className="rover-telemetry">
|
||||
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{
|
||||
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined;
|
||||
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span>
|
||||
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div>
|
||||
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div>
|
||||
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div>
|
||||
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div>
|
||||
<div><dt>Контроллер</dt><dd>{number(v?.mos_temperature_c)} °C</dd></div>
|
||||
<div><dt>Ошибка VESC</dt><dd>{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}</dd></div></dl>
|
||||
</section>;
|
||||
})}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './rover.css';
|
||||
const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer'));
|
||||
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
|
||||
|
||||
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
|
||||
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||
useEffect(()=>{if(!active)stop();},[active,stop]);
|
||||
useEffect(()=>{
|
||||
if(!c.ready||!active||open||!stage.current)return;
|
||||
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
|
||||
input.current=binding;c.setInputGuard(binding.valid);
|
||||
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
|
||||
},[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
|
||||
const showSettings=()=>{stop();setOpen(true);};
|
||||
const preparing=c.pending||(c.armed&&!c.ready);
|
||||
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
|
||||
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||
return <>
|
||||
{createPortal(<IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton>,header.actionsTarget)}
|
||||
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
|
||||
<Suspense fallback={null}><Scene modelUrl="/rover-scene/dcd006-v020.glb" cameraAutoRotate={false} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
<div className="rover-view__status"><StatusBadge tone={tone}>{status}</StatusBadge></div>
|
||||
{c.ready&&<div className="rover-view__controls">
|
||||
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
|
||||
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
|
||||
disabled={!c.ready||!active} pressed={held.has(code)}
|
||||
onPointerDown={e=>{if(!c.ready||!e.isTrusted||e.button!==0)return;e.preventDefault();e.currentTarget.setPointerCapture(e.pointerId);stage.current?.focus();input.current?.pointerDown(e.pointerId,code);}}
|
||||
onPointerUp={e=>input.current?.pointerUp(e.pointerId)}
|
||||
onPointerCancel={e=>input.current?.pointerCancel(e.pointerId)}
|
||||
onLostPointerCapture={e=>input.current?.pointerCancel(e.pointerId)}>{code.slice(3)}</KeyButton>)}
|
||||
</div>
|
||||
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
|
||||
</div>}
|
||||
<div className="rover-view__authority">
|
||||
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
|
||||
</div>
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(e.target.value)}))}/>
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={settings.maxErpm} onChange={e=>setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/>
|
||||
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/>
|
||||
{availability&&<StatusBadge tone="warning">{availability}</StatusBadge>}
|
||||
<p>Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!confirmed||!c.canArm||!(settings.currentA>=.5&&settings.currentA<=30&&settings.maxErpm>=300&&settings.maxErpm<=3000)} loading={c.pending}
|
||||
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button>
|
||||
</div></Window>
|
||||
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"source": "NodeDC ThreeDAssetNode / PlayCanvasViewer",
|
||||
"files": {
|
||||
"PlayCanvasViewer.tsx": "34cd6df2e47a7714288aeb5afb2859b1058eb91dc1819abbf296c6a8937a1533",
|
||||
"playcanvasPostFx.ts": "91cfb7f8ba821fef14681c6c25a61f430ce25aae65b0f181d359f38e37ccd014",
|
||||
"sceneTree.ts": "eead378c2402f69e2c68cd1fc2a5ec9028555dced53858c600c599f613dda516",
|
||||
"environment-map.png": "793f72dce207c1a4d2bdb262610f688bd655a79066298b672b642f228cf7d230"
|
||||
},
|
||||
"adaptations": [
|
||||
"Domain asset URL and error/loading callbacks",
|
||||
"No fallback to a different vehicle",
|
||||
"Removed unused node-editor type helper; rendering settings unchanged",
|
||||
"Observe the host pane on resize; preserve responsive canvas CSS sizing",
|
||||
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,393 @@
|
||||
|
||||
export type PostFxSettings = {
|
||||
lighting: {
|
||||
exposure: number
|
||||
skyBoxIntensity: number
|
||||
}
|
||||
envAtlas: {
|
||||
enabled: boolean
|
||||
background: boolean
|
||||
reflection: boolean
|
||||
intensity: number
|
||||
reflectionIntensity: number
|
||||
brightness: number
|
||||
contrast: number
|
||||
saturation: number
|
||||
toneMapping: number
|
||||
mip: number
|
||||
rotation: number
|
||||
}
|
||||
skybox: {
|
||||
enabled: boolean
|
||||
background: boolean
|
||||
reflection: boolean
|
||||
intensity: number
|
||||
reflectionIntensity: number
|
||||
mip: number
|
||||
rotation: number
|
||||
colorA: string
|
||||
colorB: string
|
||||
}
|
||||
rendering: {
|
||||
backgroundColor: string
|
||||
wireframe: boolean
|
||||
renderFormat: number
|
||||
renderFormatFallback0: number
|
||||
renderFormatFallback1: number
|
||||
stencil: boolean
|
||||
renderTargetScale: number
|
||||
samples: number
|
||||
sharpness: number
|
||||
toneMapping: number
|
||||
sceneColorMap: boolean
|
||||
sceneDepthMap: boolean
|
||||
fog: 'none' | 'linear' | 'exp' | 'exp2'
|
||||
fogColor: string
|
||||
fogRange: [number, number]
|
||||
fogDensity: number
|
||||
fogStart: number
|
||||
fogEnd: number
|
||||
}
|
||||
grid: {
|
||||
enabled: boolean
|
||||
colorX: string
|
||||
colorZ: string
|
||||
colorMain: string
|
||||
alphaX: number
|
||||
alphaZ: number
|
||||
alphaMain: number
|
||||
dotsEnabled: boolean
|
||||
dotsColor: string
|
||||
dotsAlpha: number
|
||||
dotsDiameter: number
|
||||
crossEnabled: boolean
|
||||
crossColor: string
|
||||
crossAlpha: number
|
||||
crossLength: number
|
||||
crossWidth: number
|
||||
fadeStart: number
|
||||
fadeEnd: number
|
||||
}
|
||||
ssao: {
|
||||
type: 'none' | 'lighting' | 'combine'
|
||||
blurEnabled: boolean
|
||||
intensity: number
|
||||
radius: number
|
||||
samples: number
|
||||
power: number
|
||||
minAngle: number
|
||||
scale: number
|
||||
}
|
||||
bloom: {
|
||||
enabled: boolean
|
||||
intensity: number
|
||||
lastMipLevel: number
|
||||
}
|
||||
chromaticAberration: {
|
||||
enabled: boolean
|
||||
intensity: number
|
||||
}
|
||||
taa: {
|
||||
enabled: boolean
|
||||
jitter: number
|
||||
}
|
||||
grading: {
|
||||
enabled: boolean
|
||||
brightness: number
|
||||
contrast: number
|
||||
saturation: number
|
||||
tint: string
|
||||
}
|
||||
lut: {
|
||||
intensity: number
|
||||
textureUrl?: string | null
|
||||
}
|
||||
vignette: {
|
||||
enabled: boolean
|
||||
intensity: number
|
||||
inner: number
|
||||
outer: number
|
||||
curvature: number
|
||||
color: string
|
||||
}
|
||||
directionalLight: {
|
||||
enabled: boolean
|
||||
color: string
|
||||
intensity: number
|
||||
azimuth: number
|
||||
elevation: number
|
||||
castShadows: boolean
|
||||
shadowIntensity: number
|
||||
shadowDistance: number
|
||||
shadowResolution: number
|
||||
shadowBias: number
|
||||
normalOffsetBias: number
|
||||
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
||||
vsmBlurSize: number
|
||||
}
|
||||
shadowCatcher: {
|
||||
enabled: boolean
|
||||
size: number
|
||||
yOffset: number
|
||||
lightIntensity: number
|
||||
lightColor: string
|
||||
lightAzimuth: number
|
||||
lightElevation: number
|
||||
shadowIntensity: number
|
||||
shadowDistance: number
|
||||
shadowResolution: number
|
||||
shadowBias: number
|
||||
normalOffsetBias: number
|
||||
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
||||
vsmBlurSize: number
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_POSTFX: PostFxSettings = {
|
||||
lighting: {
|
||||
exposure: 1.21,
|
||||
skyBoxIntensity: 0.86,
|
||||
},
|
||||
envAtlas: {
|
||||
enabled: true,
|
||||
background: false,
|
||||
reflection: true,
|
||||
intensity: 0.76,
|
||||
reflectionIntensity: 0.6,
|
||||
brightness: 1.65,
|
||||
contrast: 1,
|
||||
saturation: 1,
|
||||
toneMapping: 0,
|
||||
mip: 1,
|
||||
rotation: 247,
|
||||
},
|
||||
skybox: {
|
||||
enabled: false,
|
||||
background: false,
|
||||
reflection: true,
|
||||
intensity: 0.62,
|
||||
reflectionIntensity: 1,
|
||||
mip: 0,
|
||||
rotation: 0,
|
||||
colorA: '#c5bfbf',
|
||||
colorB: '#c7bcbc',
|
||||
},
|
||||
rendering: {
|
||||
backgroundColor: '#111113',
|
||||
wireframe: false,
|
||||
renderFormat: 18,
|
||||
renderFormatFallback0: 12,
|
||||
renderFormatFallback1: 14,
|
||||
stencil: false,
|
||||
renderTargetScale: 1,
|
||||
samples: 4,
|
||||
sharpness: 0,
|
||||
toneMapping: 4,
|
||||
sceneColorMap: false,
|
||||
sceneDepthMap: false,
|
||||
fog: 'exp',
|
||||
fogColor: '#dcc2ff',
|
||||
fogRange: [0, 100],
|
||||
fogDensity: 0.008,
|
||||
fogStart: 0,
|
||||
fogEnd: 100,
|
||||
},
|
||||
grid: {
|
||||
enabled: true,
|
||||
colorX: '#ffffff',
|
||||
colorZ: '#ffffff',
|
||||
colorMain: '#7a3cff',
|
||||
alphaX: 0.18,
|
||||
alphaZ: 0.18,
|
||||
alphaMain: 0.6,
|
||||
dotsEnabled: false,
|
||||
dotsColor: '#ffffff',
|
||||
dotsAlpha: 0.5,
|
||||
dotsDiameter: 0.06,
|
||||
crossEnabled: false,
|
||||
crossColor: '#ffffff',
|
||||
crossAlpha: 0.5,
|
||||
crossLength: 0.5,
|
||||
crossWidth: 0.06,
|
||||
fadeStart: 0,
|
||||
fadeEnd: 0,
|
||||
},
|
||||
ssao: {
|
||||
type: 'none',
|
||||
blurEnabled: true,
|
||||
intensity: 0.5,
|
||||
radius: 30,
|
||||
samples: 12,
|
||||
power: 6,
|
||||
minAngle: 10,
|
||||
scale: 1,
|
||||
},
|
||||
bloom: {
|
||||
enabled: true,
|
||||
intensity: 0.03,
|
||||
lastMipLevel: 4,
|
||||
},
|
||||
chromaticAberration: {
|
||||
enabled: true,
|
||||
intensity: 30,
|
||||
},
|
||||
taa: {
|
||||
enabled: false,
|
||||
jitter: 1,
|
||||
},
|
||||
grading: {
|
||||
enabled: true,
|
||||
brightness: 0.837,
|
||||
contrast: 1.1,
|
||||
saturation: 1.126,
|
||||
tint: '#ffffff',
|
||||
},
|
||||
lut: {
|
||||
intensity: 1,
|
||||
textureUrl: null,
|
||||
},
|
||||
vignette: {
|
||||
enabled: true,
|
||||
intensity: 1,
|
||||
inner: 0.25,
|
||||
outer: 1.52,
|
||||
curvature: 0.78,
|
||||
color: '#000000',
|
||||
},
|
||||
directionalLight: {
|
||||
enabled: true,
|
||||
color: '#ffffff',
|
||||
intensity: 0.4,
|
||||
azimuth: 0,
|
||||
elevation: 0,
|
||||
castShadows: false,
|
||||
shadowIntensity: 0.5,
|
||||
shadowDistance: 16,
|
||||
shadowResolution: 1024,
|
||||
shadowBias: 0,
|
||||
normalOffsetBias: 0,
|
||||
shadowType: 'vsm16',
|
||||
vsmBlurSize: 8,
|
||||
},
|
||||
shadowCatcher: {
|
||||
enabled: true,
|
||||
size: 9,
|
||||
yOffset: 0.001,
|
||||
lightIntensity: 0.3,
|
||||
lightColor: '#ffffff',
|
||||
lightAzimuth: 20,
|
||||
lightElevation: 60,
|
||||
shadowIntensity: 0.29,
|
||||
shadowDistance: 16,
|
||||
shadowResolution: 2048,
|
||||
shadowBias: 0,
|
||||
normalOffsetBias: 0,
|
||||
shadowType: 'vsm16',
|
||||
vsmBlurSize: 8,
|
||||
},
|
||||
}
|
||||
|
||||
function isObject(value: any): value is Record<string, any> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
|
||||
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
|
||||
|
||||
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
|
||||
const merge = (target: any, source: any) => {
|
||||
if (!isObject(source)) return
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (isObject(value)) {
|
||||
if (!isObject(target[key])) target[key] = {}
|
||||
merge(target[key], value)
|
||||
} else {
|
||||
target[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
merge(out, raw)
|
||||
|
||||
const legacy: any = raw as any
|
||||
if (legacy?.hdrLight) {
|
||||
const src = legacy.hdrLight
|
||||
const env = legacy?.envAtlas ?? {}
|
||||
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
|
||||
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
|
||||
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
|
||||
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
|
||||
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
|
||||
}
|
||||
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
|
||||
if (typeof legacy.hdrReflection.enabled === 'boolean') {
|
||||
out.envAtlas.reflection = legacy.hdrReflection.enabled
|
||||
}
|
||||
}
|
||||
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
|
||||
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
|
||||
}
|
||||
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
|
||||
out.envAtlas.brightness = 1
|
||||
}
|
||||
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
|
||||
out.envAtlas.contrast = 1
|
||||
}
|
||||
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
|
||||
out.envAtlas.saturation = 1
|
||||
}
|
||||
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
|
||||
out.envAtlas.toneMapping = 0
|
||||
}
|
||||
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
|
||||
out.skybox.reflectionIntensity = out.skybox.intensity
|
||||
}
|
||||
if (out.grid && typeof out.grid.enabled !== 'boolean') {
|
||||
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
|
||||
}
|
||||
if (out.grid && typeof out.grid.colorX !== 'string') {
|
||||
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
|
||||
}
|
||||
if (out.grid && typeof out.grid.colorZ !== 'string') {
|
||||
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
|
||||
}
|
||||
if (out.grid && typeof out.grid.colorMain !== 'string') {
|
||||
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
|
||||
}
|
||||
if (out.grid && typeof out.grid.alphaX !== 'number') {
|
||||
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
|
||||
}
|
||||
if (out.grid && typeof out.grid.alphaZ !== 'number') {
|
||||
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
|
||||
}
|
||||
if (out.grid && typeof out.grid.alphaMain !== 'number') {
|
||||
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
|
||||
}
|
||||
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
|
||||
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
|
||||
}
|
||||
if (out.grid && typeof out.grid.dotsColor !== 'string') {
|
||||
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
|
||||
}
|
||||
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
|
||||
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
|
||||
}
|
||||
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
|
||||
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
|
||||
}
|
||||
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
|
||||
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
|
||||
}
|
||||
if (out.grid && typeof out.grid.crossColor !== 'string') {
|
||||
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
|
||||
}
|
||||
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
|
||||
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
|
||||
}
|
||||
if (out.grid && typeof out.grid.crossLength !== 'number') {
|
||||
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
|
||||
}
|
||||
if (out.grid && typeof out.grid.crossWidth !== 'number') {
|
||||
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
|
||||
}
|
||||
return out as PostFxSettings
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type * as pc from 'playcanvas'
|
||||
|
||||
export type SceneTreeNode = {
|
||||
id: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
children: SceneTreeNode[]
|
||||
}
|
||||
|
||||
export function buildSceneTree(root: pc.GraphNode, map: Map<string, pc.Entity>): SceneTreeNode {
|
||||
const id = String((root as any).getGuid?.() ?? (root as any)._guid ?? root.name)
|
||||
const children = (root.children || []).map((c) => buildSceneTree(c, map))
|
||||
map.set(id, root as pc.Entity)
|
||||
return {
|
||||
id,
|
||||
name: root.name || 'Entity',
|
||||
enabled: root.enabled !== false,
|
||||
children,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
.rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; }
|
||||
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
|
||||
.rover-view .rover-view__scene { position:absolute; inset:0; }
|
||||
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
|
||||
.rover-view__status { position:absolute; top:var(--nodedc-space-3); left:var(--nodedc-space-3); }
|
||||
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
|
||||
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
|
||||
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
|
||||
.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; }
|
||||
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
|
||||
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
|
||||
@container (max-width: 380px) {
|
||||
.rover-view__authority { top:48px; bottom:auto; }
|
||||
}
|
||||
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
|
||||
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||
.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); }
|
||||
.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); }
|
||||
.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); }
|
||||
.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; }
|
||||
@@ -0,0 +1,26 @@
|
||||
import { FieldFrame, Select } from "@nodedc/ui-react";
|
||||
import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon";
|
||||
|
||||
const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф",
|
||||
range: "Расстояния", motion: "Навигация", policy: "Поведение" };
|
||||
|
||||
export function AiCompositionFields({ modules, selection, disabled, onChange }: {
|
||||
modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void;
|
||||
}) {
|
||||
return <section className="ai-polygon__section" aria-label="Композиция AI">
|
||||
<h3>Модули AI</h3>
|
||||
{modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) =>
|
||||
<FieldFrame key={group} label={labels[group]}>
|
||||
<Select label={`Модуль: ${labels[group]}`} disabled={disabled}
|
||||
value={selection.selections.find((row) => row.group === group)?.module_id ?? ""}
|
||||
options={options.map((module) => ({ value: module.moduleId, label: module.label }))}
|
||||
onChange={(value) => {
|
||||
const module = options.find((item) => item.moduleId === value);
|
||||
if (!module) return;
|
||||
onChange({ ...selection, selections: [...selection.selections.filter((row) => row.group !== group), {
|
||||
group, module_id: module.moduleId, module_sha256: module.moduleSha256, parameters: module.defaults,
|
||||
}] });
|
||||
}} />
|
||||
</FieldFrame>)}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useState } from "react";
|
||||
import { Button, Icon, ToastStack } from "@nodedc/ui-react";
|
||||
import { controlAiRun, type AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiRunActions({ run, onChange }: { run: AiRun; onChange: (run: AiRun) => void }) {
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const terminal = ["completed", "stopped", "failed"].includes(run.state);
|
||||
const pending = !terminal && (run.control_sequence ?? 0) > (run.telemetry?.control_sequence ?? 0);
|
||||
const command = (value: "pause" | "play" | "stop") => {
|
||||
setBusy(value); setError(null);
|
||||
void controlAiRun(run, value).then(onChange).catch((caught: Error) => setError(caught.message))
|
||||
.finally(() => setBusy(null));
|
||||
};
|
||||
return <>
|
||||
{!terminal ? <>
|
||||
<Button disabled={!!busy || pending || ["starting", "stopping", "disconnected"].includes(run.state)}
|
||||
variant={run.state === "ready" ? "primary" : "secondary"}
|
||||
loading={busy === "pause" || busy === "play"}
|
||||
onClick={() => command(run.state === "running" ? "pause" : "play")}>
|
||||
{run.state === "starting" ? "Подготовка…" : run.state === "ready" ? "Запустить AI" : run.state === "running" ? "Пауза" : "Продолжить"}
|
||||
</Button>
|
||||
<Button disabled={!!busy || run.state === "stopping"} loading={busy === "stop" || run.state === "stopping"}
|
||||
icon={<Icon name="stop" />} onClick={() => command("stop")}>Завершить симуляцию</Button>
|
||||
</> : null}
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Команда не выполнена", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { StatusBadge } from "@nodedc/ui-react";
|
||||
import { type AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
const STATES: Record<AiRun["state"], string> = {
|
||||
starting: "Подготовка симуляции", ready: "Сцена открыта · AI выключен",
|
||||
running: "AI управляет ровером", paused: "Пауза · движение остановлено",
|
||||
stopping: "Завершаем симуляцию и inference…", completed: "Симуляция завершена",
|
||||
stopped: "Симуляция и inference остановлены", failed: "Симуляция прервана",
|
||||
disconnected: "Нет связи с Worker · состояние уточняется",
|
||||
};
|
||||
const REASONS: Record<string, string> = {
|
||||
road: "Движение по тропе", obstacle: "Остановка перед препятствием", "no-road": "Путь не найден",
|
||||
uncertain: "Недостаточно уверенности", "inference-error": "Inference недоступен",
|
||||
replanning: "Ищем другой проезд", stuck: "Ровер застрял · прогон остановлен",
|
||||
"goal-reached": "Цель достигнута", unstable: "Остановка: опасный наклон",
|
||||
waiting: "Ожидаем возможность движения",
|
||||
};
|
||||
export function AiRunView({ run, connection }: { run: AiRun; connection: ReactNode }) {
|
||||
const terminal = ["completed", "stopped", "failed"].includes(run.state);
|
||||
const telemetry = run.telemetry;
|
||||
const pending = !terminal && (run.control_sequence ?? 0) > (telemetry?.control_sequence ?? 0);
|
||||
const preparingModels = run.state === "running" && run.phase === "models";
|
||||
const reason = telemetry?.stop_reason === "unstable" ? "Остановка: опасный наклон"
|
||||
: telemetry?.stop_reason === "stale-camera" || telemetry?.stop_reason === "stale-command"
|
||||
? "Остановка: решение AI устарело" : telemetry?.stop_reason === "inference-error"
|
||||
? "Остановка: inference недоступен" : telemetry?.decision?.reason === "road" && Math.abs(telemetry.speed_mps) < 0.01
|
||||
? "Ровер не движется" : REASONS[telemetry?.decision?.reason ?? ""];
|
||||
return <section className="ai-polygon__run" aria-label="Управление симуляцией">
|
||||
<div className="ai-polygon__telemetry-row">
|
||||
<div className="ai-polygon__facts">
|
||||
{run.state !== "ready" && run.state !== "running" || preparingModels || pending ? <StatusBadge tone={run.state === "failed" || run.state === "disconnected" ? "warning" : "neutral"}>
|
||||
{preparingModels ? "Загружаем AI-модели" : pending && run.state !== "stopping" ? "Worker выполняет команду…" : STATES[run.state]}
|
||||
</StatusBadge> : null}
|
||||
{telemetry && !terminal && run.state !== "stopping" && run.state !== "disconnected" ? <div className="ai-polygon__facts">
|
||||
{run.state === "running" && !preparingModels && reason ? <strong>{reason}</strong> : null}
|
||||
<span>Скорость: {Math.abs(telemetry.speed_mps).toFixed(2)} м/с</span>
|
||||
<span>Время мира: {(telemetry.simulation_time_ns / 1e9).toFixed(1)} с</span>
|
||||
{run.state === "running" ? <>
|
||||
<span>Симуляция: {telemetry.rtf.toFixed(2)}×</span>
|
||||
<span>Камера: {telemetry.sensor_fps.toFixed(1)} FPS</span>
|
||||
<span>AI: {telemetry.ai_hz.toFixed(1)} решений/с</span>
|
||||
{telemetry.inference_ms !== null ? <span>Inference: {telemetry.inference_ms.toFixed(0)} мс</span> : null}
|
||||
{telemetry.frame_age_ms !== null ? <span>Возраст кадра: {telemetry.frame_age_ms.toFixed(0)} мс</span> : null}
|
||||
</> : null}
|
||||
</div> : null}
|
||||
</div>
|
||||
{connection}
|
||||
</div>
|
||||
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Icon, ProgressBar, TextField, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { importAiWorld, type AiSource, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiSource>(source ?? {
|
||||
name: "", author: "", license: "", source_url: "",
|
||||
});
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [pending, setPending] = useState<AiWorld | undefined>(resume);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const picker = useRef<HTMLInputElement>(null);
|
||||
const controller = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const submit = async () => {
|
||||
if (!file || busy) return;
|
||||
setBusy(true); setError(null);
|
||||
const abort = new AbortController(); controller.current = abort;
|
||||
try { onImported(await importAiWorld(file, draft, setProgress, abort.signal, pending, setPending)); }
|
||||
catch (caught) { if (!abort.signal.aborted) setError(caught instanceof Error ? caught.message : "Импорт не завершён."); }
|
||||
finally { if (!abort.signal.aborted) setBusy(false); }
|
||||
};
|
||||
return <Window open onClose={onClose} title={resume ? "Продолжить импорт" : "Импорт локации"}
|
||||
footer={<Button variant="primary" loading={busy} disabled={!file || !draft.name.trim() || !draft.author.trim() || !draft.license.trim()}
|
||||
onClick={() => void submit()}>Импортировать</Button>}>
|
||||
<div className="ai-polygon__form">
|
||||
<TextField label="Название" value={draft.name} disabled={busy || !!resume}
|
||||
onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
|
||||
<TextField label="Автор" value={draft.author} disabled={busy || !!resume}
|
||||
onChange={(e) => setDraft({ ...draft, author: e.target.value })} />
|
||||
<TextField label="Лицензия" value={draft.license} disabled={busy || !!resume}
|
||||
onChange={(e) => setDraft({ ...draft, license: e.target.value })} />
|
||||
<TextField label="Страница источника" value={draft.source_url ?? ""} disabled={busy || !!resume}
|
||||
onChange={(e) => setDraft({ ...draft, source_url: e.target.value })} />
|
||||
<input ref={picker} type="file" accept=".ply" hidden onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
|
||||
<Button disabled={busy} icon={<Icon name="upload" />} onClick={() => picker.current?.click()}>
|
||||
{file?.name ?? "Выбрать Gaussian PLY"}
|
||||
</Button>
|
||||
{busy ? <ProgressBar value={progress} label={`Передано ${Math.round(progress * 100)}%`} /> : null}
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Импорт не завершён", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState } from "react";
|
||||
import { Button, TextField, TextAreaField, ToastStack } from "@nodedc/ui-react";
|
||||
import { configureAiWorld, type AiWorld, type AiWorldSettings } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldSetup({ world, disabled, onSaved }: {
|
||||
world: AiWorld; disabled: boolean; onSaved: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiWorldSettings>(world.settings);
|
||||
const [route, setRoute] = useState((world.settings.route_xy ?? []).map((p) => p.join(" ")).join("\n"));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const field = (label: string, value: number, change: (value: number) => void) =>
|
||||
<TextField label={label} type="number" step="any" value={Number.isFinite(value) ? value : ""}
|
||||
disabled={disabled || busy} onChange={(e) => change(e.target.value === "" ? NaN : Number(e.target.value))} />;
|
||||
return <div className="ai-polygon__setup">
|
||||
{field("Метров на единицу сцены", draft.meters_per_unit, (v) => setDraft({ ...draft, meters_per_unit: v }))}
|
||||
{([0, 1, 2] as const).map((axis) => <div key={axis}>
|
||||
{field(`Поворот ${["X", "Y", "Z"][axis]}, °`, draft.rotation_degrees[axis], (v) => {
|
||||
const rotation = [...draft.rotation_degrees] as [number, number, number]; rotation[axis] = v;
|
||||
setDraft({ ...draft, rotation_degrees: rotation });
|
||||
})}
|
||||
</div>)}
|
||||
{field("Уровень грунта Z, м", draft.ground_z, (v) => setDraft({ ...draft, ground_z: v }))}
|
||||
{field("Старт X, м", draft.spawn_xy[0], (v) => setDraft({ ...draft, spawn_xy: [v, draft.spawn_xy[1]] }))}
|
||||
{field("Старт Y, м", draft.spawn_xy[1], (v) => setDraft({ ...draft, spawn_xy: [draft.spawn_xy[0], v] }))}
|
||||
{field("Направление, °", draft.heading_degrees, (v) => setDraft({ ...draft, heading_degrees: v }))}
|
||||
{field("Высота камеры, м", draft.camera_height_m, (v) => setDraft({ ...draft, camera_height_m: v }))}
|
||||
{field("Скорость до, м/с", draft.max_speed_mps, (v) => setDraft({ ...draft, max_speed_mps: v }))}
|
||||
<TextAreaField label="Точки маршрута, X Y в метрах" rows={3} value={route}
|
||||
hint="Каждая точка — с новой строки. Пустое поле: движение по видимой тропе."
|
||||
disabled={disabled || busy} onChange={(e) => setRoute(e.target.value)} />
|
||||
<Button disabled={disabled} loading={busy} onClick={() => {
|
||||
const points = route.trim() ? route.trim().split(/\n+/).map((line) => line.trim().split(/\s+/).map(Number)) : [];
|
||||
if (points.length > 32 || points.some((p) => p.length !== 2 || p.some((v) => !Number.isFinite(v)))) {
|
||||
setError("Укажите не более 32 точек: два числа X Y в каждой строке."); return;
|
||||
}
|
||||
setBusy(true); setError(null);
|
||||
void configureAiWorld(world, { ...draft, route_xy: points as [number, number][], prepared: true }).then(onSaved)
|
||||
.catch((caught: Error) => setError(caught.message)).finally(() => setBusy(false));
|
||||
}}>Сохранить старт и масштаб</Button>
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Настройки не сохранены", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, Icon, IconButton, LoadingRegion, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
|
||||
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
// NVIDIA has process-global browser listeners. Serialize replacement/cleanup,
|
||||
// including React StrictMode, without letting an old viewer terminate a new one.
|
||||
let streamLifecycle: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/** Decode the actual Worker stream. This component never loads a world or creates a 3D engine. */
|
||||
export function AiWorldStream({ world, run, onBack, onChange, controls, headerActions, actionsHost }: {
|
||||
world: AiWorld; run?: AiRun | null; onBack: () => void; onChange: (run: AiRun) => void; controls?: ReactNode;
|
||||
headerActions?: ReactNode; actionsHost?: HTMLElement | null;
|
||||
}) {
|
||||
const frame = useRef<HTMLDivElement>(null);
|
||||
const video = useRef<HTMLVideoElement>(null);
|
||||
const id = useId().replaceAll(":", "");
|
||||
const { expanded, toggle } = useSimulationFullscreen(frame);
|
||||
const [state, setState] = useState<"connecting" | "live" | "failed" | "stalled">("connecting");
|
||||
const [fps, setFps] = useState<number | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [cameraError, setCameraError] = useState(false);
|
||||
const endpoint = run?.worker?.stream;
|
||||
const terminal = !run || ["completed", "stopped", "failed"].includes(run.state);
|
||||
const connectable = !terminal && !!run?.telemetry?.stream_ready && !!endpoint;
|
||||
const endpointKey = JSON.stringify(endpoint);
|
||||
useEffect(() => {
|
||||
if (!connectable || !endpoint || !video.current) return;
|
||||
let disposed = false;
|
||||
let stream: import("@nvidia/ov-web-rtc").AppStreamer | undefined;
|
||||
let settle!: () => void;
|
||||
const settled = new Promise<void>((resolve) => { settle = resolve; });
|
||||
let callback = 0;
|
||||
let lastFrame = performance.now();
|
||||
let frames = 0;
|
||||
let measuredAt = performance.now();
|
||||
let connected = false;
|
||||
setState("connecting"); setFps(null);
|
||||
const element = video.current;
|
||||
const received = () => {
|
||||
if (disposed) return;
|
||||
lastFrame = performance.now(); frames += 1; connected = true; setState("live");
|
||||
callback = element.requestVideoFrameCallback(received);
|
||||
};
|
||||
callback = element.requestVideoFrameCallback(received);
|
||||
const timer = setInterval(() => {
|
||||
const now = performance.now();
|
||||
setFps(frames * 1000 / (now - measuredAt));
|
||||
frames = 0; measuredAt = now;
|
||||
if (connected && now - lastFrame > 3000) setState("stalled");
|
||||
}, 1000);
|
||||
const setup = streamLifecycle.catch(() => undefined).then(async () => {
|
||||
const sdk = await import("@nvidia/ov-web-rtc");
|
||||
if (disposed) { settle(); return; }
|
||||
stream = new sdk.AppStreamer();
|
||||
await stream.connect({ streamSource: sdk.StreamType.DIRECT, logLevel: sdk.LogLevel.WARN,
|
||||
streamConfig: { signalingServer: endpoint.server, signalingPort: endpoint.signaling_port,
|
||||
signalingPath: "/", mediaServer: endpoint.server, mediaPort: endpoint.media_port,
|
||||
width: endpoint.width, height: endpoint.height, fps: endpoint.fps,
|
||||
videoElementId: `polygon-video-${id}`, audioElementId: `polygon-audio-${id}`,
|
||||
autoLaunch: true, mic: false, enableAV1Support: false, fitStreamResolution: false,
|
||||
maxReconnects: 1, reconnectDelay: 2000, connectivityTimeout: 5000,
|
||||
onStart: (event) => {
|
||||
if (event.status === sdk.EventStatus.SUCCESS || event.status === sdk.EventStatus.ERROR
|
||||
|| event.status === sdk.EventStatus.CANCELED) settle();
|
||||
if (!disposed && event.status === sdk.EventStatus.ERROR) setState("failed");
|
||||
},
|
||||
onStop: () => { settle(); if (!disposed) setState("stalled"); },
|
||||
} });
|
||||
if (stream.streamStatus !== sdk.StreamStatus.STARTING) settle();
|
||||
}).catch(() => { settle(); if (!disposed) setState("failed"); });
|
||||
streamLifecycle = setup;
|
||||
return () => {
|
||||
disposed = true; clearInterval(timer); element.cancelVideoFrameCallback(callback);
|
||||
// connect() resolves with IN_PROGRESS; terminate() during STARTING does
|
||||
// not dispose the SDK. Await its final callback before admitting a new owner.
|
||||
streamLifecycle = setup.then(async () => {
|
||||
await settled;
|
||||
await stream?.terminate(false);
|
||||
}).catch(() => undefined);
|
||||
};
|
||||
// A telemetry refresh must never reconnect or reload the stream.
|
||||
}, [connectable, endpointKey, run?.run_id, id, revision]);
|
||||
const mode = run?.camera ?? "follow";
|
||||
const changeCamera = (camera: AiCamera) => {
|
||||
if (!run) return;
|
||||
setCameraError(false);
|
||||
void setAiCamera(run, camera).then(onChange).catch(() => setCameraError(true));
|
||||
};
|
||||
return <div ref={frame} className="ai-polygon__stage">
|
||||
{!expanded && actionsHost ? createPortal(headerActions, actionsHost) : null}
|
||||
{expanded ? <div className="ai-polygon__head">
|
||||
<div className="ai-polygon__title">
|
||||
<IconButton label="Назад к локациям" onClick={onBack}><Icon name="chevron-left" /></IconButton>
|
||||
<h2>{world.name}</h2>
|
||||
</div>
|
||||
<div className="ai-polygon__actions">{headerActions}</div>
|
||||
</div> : null}
|
||||
{controls ? <div className="ai-polygon__viewer-controls">{controls}</div> : null}
|
||||
<div className="ai-polygon__viewer">
|
||||
<div className="ai-polygon__viewer-toolbar">
|
||||
<SegmentedControl<AiCamera> label="Вид симуляции" size="dense" value={mode} onChange={changeCamera}
|
||||
items={[{ value: "follow", label: "За ровером", disabled: terminal },
|
||||
{ value: "overview", label: "Обзор", disabled: terminal }, { value: "camera", label: "Камера AI", disabled: terminal }]} />
|
||||
<div className="ai-polygon__actions">
|
||||
{connectable ? <StatusBadge tone={state === "live" ? "success" : "warning"}>
|
||||
{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : "Ожидаем видео"}
|
||||
</StatusBadge> : null}
|
||||
<IconButton label={expanded ? "Свернуть симуляцию" : "Развернуть симуляцию"} onClick={toggle}>
|
||||
<Icon name={expanded ? "minimize" : "expand"} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
|
||||
<div className="ai-polygon__viewport">
|
||||
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
|
||||
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
|
||||
<div className="ai-polygon__video" inert>
|
||||
<video ref={video} id={`polygon-video-${id}`} autoPlay muted playsInline tabIndex={-1}
|
||||
aria-label={`Видео симуляции ${world.name} с Worker`} />
|
||||
<audio id={`polygon-audio-${id}`} muted />
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
|
||||
: connectable && (state === "failed" || state === "stalled") ? <div className="ai-polygon__preview-error" role="status">
|
||||
<p>Видеопоток прерван. Состояние симуляции показано выше.</p>
|
||||
<Button onClick={() => setRevision((value) => value + 1)}>Подключить видео</Button>
|
||||
</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState, type RefObject } from "react";
|
||||
|
||||
export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
useEffect(() => {
|
||||
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
|
||||
const escape = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void document.exitFullscreen().catch(() => undefined);
|
||||
};
|
||||
document.addEventListener("fullscreenchange", sync);
|
||||
document.addEventListener("keydown", escape, true);
|
||||
return () => {
|
||||
document.removeEventListener("fullscreenchange", sync);
|
||||
document.removeEventListener("keydown", escape, true);
|
||||
};
|
||||
}, [view]);
|
||||
const toggle = () => {
|
||||
if (!view.current) return;
|
||||
void (document.fullscreenElement === view.current
|
||||
? document.exitFullscreen() : view.current?.requestFullscreen())?.catch(() => undefined);
|
||||
};
|
||||
return { expanded, toggle };
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
|
||||
import type { DeviceUiPlugin } from "../core/device-plugins/contracts";
|
||||
import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin";
|
||||
import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin';
|
||||
@@ -10,4 +11,4 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
|
||||
|
||||
// Node-executed camera controls use the existing sensor contribution contract;
|
||||
// they do not register a desktop capture/AI runtime or a new product workspace.
|
||||
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi]);
|
||||
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi]);
|
||||
|
||||
@@ -43,7 +43,7 @@ const defaultQuickActions: Record<
|
||||
missions: ["routes", null],
|
||||
data: ["recordings", "datasets"],
|
||||
system: ["modules", "integrations"],
|
||||
polygon: ["lab-archive", "local-device"],
|
||||
polygon: ["observatory", "local-device"],
|
||||
};
|
||||
|
||||
export function defaultEnvironmentSettings(): EnvironmentSettings {
|
||||
@@ -140,6 +140,10 @@ function decodeBackground(value: unknown, path: string): EnvironmentBackground {
|
||||
};
|
||||
}
|
||||
|
||||
function currentQuickAction(value: string | null): string | null {
|
||||
return value === "lab-archive" ? "observatory" : value;
|
||||
}
|
||||
|
||||
function decodePage(value: unknown, path: string): EnvironmentPage {
|
||||
const record = requireRecord(value, path);
|
||||
return {
|
||||
@@ -147,16 +151,16 @@ function decodePage(value: unknown, path: string): EnvironmentPage {
|
||||
eyebrow: requireString(record.eyebrow, `${path}.eyebrow`)!,
|
||||
title: requireString(record.title, `${path}.title`)!,
|
||||
description: requireString(record.description, `${path}.description`)!,
|
||||
primaryWorkspaceId: requireString(
|
||||
primaryWorkspaceId: currentQuickAction(requireString(
|
||||
record.primary_workspace_id,
|
||||
`${path}.primary_workspace_id`,
|
||||
true,
|
||||
),
|
||||
secondaryWorkspaceId: requireString(
|
||||
)),
|
||||
secondaryWorkspaceId: currentQuickAction(requireString(
|
||||
record.secondary_workspace_id,
|
||||
`${path}.secondary_workspace_id`,
|
||||
true,
|
||||
),
|
||||
)),
|
||||
background: decodeBackground(record.background, `${path}.background`),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import {createBoardLayoutStore,type BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout';
|
||||
import {fleetRequest} from './useFleet';
|
||||
|
||||
const layouts=new Map<string,BoardLayoutStore>();
|
||||
export function boardLayout(vehicleID:string):BoardLayoutStore {
|
||||
let layout=layouts.get(vehicleID);
|
||||
if(!layout){
|
||||
const path=`/${encodeURIComponent(vehicleID)}/board-layout`;
|
||||
layout=createBoardLayoutStore({read:()=>fleetRequest(path),patch:(section,open)=>fleetRequest(path,'PATCH',{section,open})});
|
||||
layouts.set(vehicleID,layout);
|
||||
}
|
||||
return layout;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput';
|
||||
|
||||
// The network heartbeat is not evidence that a physical key is still held.
|
||||
// Allow the initial OS repeat delay, then require continuing keyboard evidence.
|
||||
export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300;
|
||||
export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
held:(keys:Set<string>)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void;
|
||||
},now:()=>number=()=>performance.now()){
|
||||
const doc=scope.ownerDocument,win=doc.defaultView!;
|
||||
const keyboard=new Set<string>(),pointers=new Map<number,string>();
|
||||
let deadline=0,closed=false,suspended=false;
|
||||
const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());};
|
||||
const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();};
|
||||
const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();};
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement);
|
||||
const valid=()=>{
|
||||
if(closed)return false;
|
||||
if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;}
|
||||
return true;
|
||||
};
|
||||
const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));};
|
||||
const down=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed)return;
|
||||
if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;}
|
||||
if(e.altKey||e.ctrlKey||e.metaKey){pause();return;}
|
||||
if(!keysFor(mode).includes(e.code)||!valid())return;
|
||||
if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;}
|
||||
// A repeat delivered after focus returns cannot become a fresh press.
|
||||
if(e.repeat&&!keyboard.has(e.code))return;
|
||||
e.preventDefault();suspended=false;keyboard.add(e.code);
|
||||
deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish();
|
||||
};
|
||||
const up=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed||!keyboard.delete(e.code))return;
|
||||
e.preventDefault();if(!keyboard.size)deadline=0;publish();
|
||||
};
|
||||
const blur=(e:Event)=>{if(e.target===win)pause();};
|
||||
const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();};
|
||||
const focusIn=()=>{if(!focused())pause();};
|
||||
const hidden=()=>{if(doc.hidden)pause();};
|
||||
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();};
|
||||
const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();};
|
||||
const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();};
|
||||
win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true);
|
||||
win.addEventListener('blur',blur,true);win.addEventListener('pagehide',stop);
|
||||
doc.addEventListener('focusout',focusOut,true);doc.addEventListener('focusin',focusIn,true);
|
||||
doc.addEventListener('visibilitychange',hidden);doc.addEventListener('pointerdown',outside,true);
|
||||
doc.addEventListener('pointerup',pointerUp,true);doc.addEventListener('pointercancel',pointerCancel,true);
|
||||
doc.addEventListener('contextmenu',pause,true);
|
||||
const timer=win.setInterval(valid,50);
|
||||
return {
|
||||
valid,
|
||||
pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}},
|
||||
pointerUp(id:number){if(!closed&&pointers.delete(id))publish();},
|
||||
pointerCancel(id:number){if(pointers.has(id))pause();},
|
||||
dispose(){
|
||||
closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
|
||||
win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true);
|
||||
win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop);
|
||||
doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true);
|
||||
doc.removeEventListener('visibilitychange',hidden);doc.removeEventListener('pointerdown',outside,true);
|
||||
doc.removeEventListener('pointerup',pointerUp,true);doc.removeEventListener('pointercancel',pointerCancel,true);
|
||||
doc.removeEventListener('contextmenu',pause,true);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type RoverMode='arcade'|'tank';
|
||||
export type Demand={left:number;right:number};
|
||||
export const keysFor=(mode:RoverMode)=>mode==='arcade'?['KeyW','KeyA','KeyS','KeyD']:['KeyQ','KeyE','KeyA','KeyD'];
|
||||
export function keyDemand(mode:RoverMode,held:ReadonlySet<string>):Demand {
|
||||
const axis=(positive:string,negative:string)=>Number(held.has(positive))-Number(held.has(negative));
|
||||
if(mode==='tank')return {left:axis('KeyQ','KeyA'),right:axis('KeyE','KeyD')};
|
||||
const forward=axis('KeyW','KeyS'),turn=axis('KeyD','KeyA');
|
||||
const scale=Math.max(1,Math.abs(forward)+Math.abs(turn));
|
||||
return {left:(forward+turn)/scale,right:(forward-turn)/scale};
|
||||
}
|
||||
export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''};
|
||||
export function roverSettings(value:unknown):typeof defaultRoverSettings {
|
||||
const v=value as Partial<typeof defaultRoverSettings>|null;
|
||||
return {...defaultRoverSettings,...(v?.version===1?{
|
||||
mode:v.mode==='tank'?'tank':'arcade',
|
||||
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30,
|
||||
maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000,
|
||||
model:v.model==='dcd006-v020'?v.model:'',
|
||||
}:{} )};
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export function createFleetSensorTransport(vehicleID:string):SensorTransport {
|
||||
return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'};
|
||||
};
|
||||
return {
|
||||
configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)},
|
||||
enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)},
|
||||
inventory:async()=>inventory(await fleetRequest()),
|
||||
subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import type {Demand} from './roverInput';
|
||||
|
||||
export interface RoverReading {
|
||||
id:string;uuid:string;slot:string|null;label:string;age_ms:number;
|
||||
values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number};
|
||||
}
|
||||
export interface RoverState {
|
||||
fresh:boolean;controlling:boolean;
|
||||
snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[];
|
||||
profile?:{layout:null|'1x1'|'2x2';bindings:Record<string,{device_id:string;uuid:string}>}};
|
||||
}
|
||||
const empty:RoverState={fresh:false,controlling:false,snapshot:{}};
|
||||
async function request<T>(url:string,body?:unknown,keepalive=false):Promise<T>{
|
||||
const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined,
|
||||
body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive});
|
||||
const result=await response.json();
|
||||
if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.');
|
||||
return result;
|
||||
}
|
||||
export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<RoverState>(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const [connecting,setConnecting]=useState(true),armPending=useRef(false);
|
||||
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(false),generation=useRef(0);
|
||||
const inputGuard=useRef<(()=>boolean)|null>(null);
|
||||
const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]);
|
||||
const stop=useCallback(()=>{
|
||||
generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
|
||||
if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{});
|
||||
},[url]);
|
||||
const send=useCallback(async()=>{
|
||||
const id=session.current;if(!id)return;
|
||||
// Check on every heartbeat, even when a previous request is still pending.
|
||||
const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.();
|
||||
if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0};
|
||||
if(sending.current)return;
|
||||
sending.current=true;
|
||||
try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});}
|
||||
catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}}
|
||||
finally{sending.current=false;}
|
||||
},[url,stop]);
|
||||
const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]);
|
||||
const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]);
|
||||
const arm=useCallback(async(currentA:number,maxErpm:number)=>{
|
||||
if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
try{
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm});
|
||||
if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;}
|
||||
// Retire every read started before this acknowledgement, including reads
|
||||
// begun while POST /arm was pending. They describe the previous authority.
|
||||
generation.current++;armPending.current=false;setPending(false);
|
||||
seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send();
|
||||
return true;
|
||||
}catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;}
|
||||
finally{if(g===generation.current){armPending.current=false;setPending(false);}}
|
||||
},[url,send]);
|
||||
useEffect(()=>{
|
||||
if(!visible){stop();setState(empty);setConnecting(false);return;}
|
||||
let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true);
|
||||
const poll=async()=>{
|
||||
if(busy)return;busy=true;const before=generation.current;
|
||||
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){setState(value);
|
||||
setConnecting(!value.fresh&&performance.now()-started<2000);
|
||||
if(session.current&&(!value.fresh||!value.controlling)){stop();}
|
||||
const fault=value.snapshot.state==='fault'?value.snapshot.message??'':'';
|
||||
if(fault&&lastFault!==fault){lastFault=fault;setError(fault);}
|
||||
}}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;}
|
||||
};
|
||||
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100);
|
||||
const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();};
|
||||
window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();};
|
||||
},[url,visible,stop,send,pauseInput]);
|
||||
const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
|
||||
const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
}
|
||||
export type RoverController=ReturnType<typeof useRoverControl>;
|
||||
@@ -87,6 +87,10 @@ export async function fetchAIModuleCatalog(signal?: AbortSignal): Promise<AIModu
|
||||
});
|
||||
const body = await bodyOf(response);
|
||||
if (!response.ok) throw apiError(body, response.status);
|
||||
return decodeAIModuleCatalog(body);
|
||||
}
|
||||
|
||||
export function decodeAIModuleCatalog(body: unknown): AIModuleCatalog {
|
||||
const root = record(body, "каталог AI-модулей");
|
||||
exactKeys(root, ["authority", "groups", "schema_version"]);
|
||||
if (root.schema_version !== CATALOG_SCHEMA) throw new Error("Версия каталога AI-модулей изменилась.");
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
|
||||
|
||||
const API = "/api/v1/ai-polygon";
|
||||
|
||||
export interface AiSelection {
|
||||
schema_version: "missioncore.observatory-ai-composition/v1";
|
||||
selections: { group: AIGroupId; module_id: string; module_sha256: string; parameters: Readonly<Record<string, unknown>> }[];
|
||||
}
|
||||
export interface AiModules { catalog: AIModuleCatalog; selection: AiSelection }
|
||||
export async function fetchAiModules(): Promise<AiModules> {
|
||||
const value = await polygonRequest<{ catalog: unknown; selection: AiSelection }>("/ai-modules");
|
||||
return { catalog: decodeAIModuleCatalog(value.catalog), selection: value.selection };
|
||||
}
|
||||
|
||||
export interface AiWorldSettings {
|
||||
meters_per_unit: number;
|
||||
rotation_degrees: [number, number, number];
|
||||
ground_z: number;
|
||||
spawn_xy: [number, number];
|
||||
heading_degrees: number;
|
||||
camera_height_m: number;
|
||||
max_speed_mps: number;
|
||||
prepared: boolean;
|
||||
route_xy?: [number, number][];
|
||||
}
|
||||
export interface AiSource {
|
||||
name: string; author: string; license: string; source_url: string | null;
|
||||
description?: string;
|
||||
}
|
||||
export interface AiWorld extends AiSource {
|
||||
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
|
||||
status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
|
||||
settings: AiWorldSettings;
|
||||
}
|
||||
export interface AiRun {
|
||||
run_id: string;
|
||||
world: AiWorld;
|
||||
request?: { composition?: AiSelection };
|
||||
state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
|
||||
clock?: "lockstep" | "realtime";
|
||||
control?: "play" | "pause" | "stop";
|
||||
control_sequence?: number;
|
||||
camera?: AiCamera;
|
||||
worker?: { stream?: AiStreamEndpoint | null };
|
||||
telemetry?: AiTelemetry | null;
|
||||
samples: number;
|
||||
phase?: string;
|
||||
applied_steps?: number;
|
||||
last_applied?: null | {
|
||||
sequence: number; simulation_time_ns: number; pose_xy: [number, number];
|
||||
pose_yaw?: number | null; cycle_ms?: number | null;
|
||||
};
|
||||
message: string | null;
|
||||
last_sample: null | {
|
||||
sequence: number; simulation_time_ns: number; inference_ms: number; pose_xy: [number, number];
|
||||
decision: { speed_mps: number; yaw_rate_rps: number; reason: string;
|
||||
road_fraction: number; obstacle_count: number };
|
||||
};
|
||||
}
|
||||
export type AiCamera = "follow" | "overview" | "camera";
|
||||
export interface AiStreamEndpoint {
|
||||
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
|
||||
}
|
||||
export interface AiTelemetry {
|
||||
sequence: number; control_sequence: number; simulation_time_ns: number;
|
||||
rtf: number; render_fps: number; sensor_fps: number; ai_hz: number;
|
||||
inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
|
||||
speed_mps: number; applied_speed_mps: number; stop_reason: string;
|
||||
ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
|
||||
decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
|
||||
}
|
||||
export interface AiCatalog {
|
||||
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
|
||||
runtime: { available: boolean; active_run: AiRun | null };
|
||||
}
|
||||
|
||||
export async function polygonRequest<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(`${API}${path}`, { ...init, headers: {
|
||||
...(typeof init.body === "string" ? { "Content-Type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
} });
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(typeof body?.detail === "string" ? body.detail : "Не удалось выполнить запрос полигона.");
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
|
||||
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
|
||||
export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
|
||||
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
|
||||
method: "PUT", body: JSON.stringify(settings),
|
||||
});
|
||||
export const startAiRun = (world: AiWorld, composition?: AiSelection) => polygonRequest<AiRun>("/runs", {
|
||||
method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() },
|
||||
body: JSON.stringify({ world_id: world.world_id, clock: "realtime", start_paused: true, duration_seconds: 1800, composition }),
|
||||
});
|
||||
export const setAiCamera = (run: AiRun, camera: AiCamera) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
|
||||
export const controlAiRun = (run: AiRun, command: "play" | "pause" | "step" | "stop") =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/${command}`, { method: "POST" });
|
||||
|
||||
export async function importAiWorld(file: File, source: AiSource, progress: (value: number) => void,
|
||||
signal: AbortSignal, resume?: AiWorld, onCreated?: (world: AiWorld) => void): Promise<AiWorld> {
|
||||
if (!file.name.toLowerCase().endsWith(".ply")) throw new Error("Выберите Gaussian PLY из экспорта сцены.");
|
||||
if (resume && (file.name !== resume.filename || file.size !== resume.byte_length)) {
|
||||
throw new Error("Для продолжения выберите тот же файл.");
|
||||
}
|
||||
let world = resume ? await polygonRequest<AiWorld>(`/worlds/${resume.world_id}`, { signal })
|
||||
: await polygonRequest<AiWorld>("/worlds", { method: "POST", signal,
|
||||
body: JSON.stringify({ ...source, description: undefined, filename: file.name,
|
||||
byte_length: file.size, source_url: source.source_url || null }) });
|
||||
onCreated?.(world);
|
||||
if (world.uploaded_bytes > 0) {
|
||||
const prefix = await polygonRequest<{ uploaded_bytes: number; chunks: { byte_length: number; sha256: string }[] }>(
|
||||
`/worlds/${world.world_id}/upload-prefix`, { signal });
|
||||
let offset = 0;
|
||||
for (const chunk of prefix.chunks) {
|
||||
signal.throwIfAborted();
|
||||
const bytes = await file.slice(offset, offset + chunk.byte_length).arrayBuffer();
|
||||
const digest = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))
|
||||
.map((value) => value.toString(16).padStart(2, "0")).join("");
|
||||
if (digest !== chunk.sha256) throw new Error("Этот файл отличается от начатой загрузки. Выберите исходный файл.");
|
||||
offset += chunk.byte_length;
|
||||
}
|
||||
if (offset !== prefix.uploaded_bytes || offset !== world.uploaded_bytes) {
|
||||
throw new Error("Загрузка изменилась в другом окне. Повторите продолжение импорта.");
|
||||
}
|
||||
}
|
||||
const chunkSize = 4 * 1024 ** 2;
|
||||
progress(world.uploaded_bytes / file.size);
|
||||
while (world.uploaded_bytes < file.size) {
|
||||
const offset = world.uploaded_bytes;
|
||||
world = await polygonRequest<AiWorld>(`/worlds/${world.world_id}/source`, {
|
||||
method: "PATCH", signal, headers: { "Upload-Offset": String(offset) },
|
||||
body: file.slice(offset, Math.min(file.size, offset + chunkSize)),
|
||||
});
|
||||
progress(world.uploaded_bytes / file.size);
|
||||
}
|
||||
return polygonRequest<AiWorld>(`/worlds/${world.world_id}/complete`, { method: "POST", signal });
|
||||
}
|
||||
@@ -155,6 +155,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
description: "Профили конфигураций, лабораторные работы и их воспроизводимые результаты.",
|
||||
icon: "clipboard",
|
||||
kind: "lab-archive",
|
||||
internalOnly: true,
|
||||
groups: [],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
@import "./styles/l34-annotation.css";
|
||||
@import "./styles/laboratory-reporting.css";
|
||||
@import "./styles/simulation.css";
|
||||
@import "./styles/ai-polygon.css";
|
||||
@import "./styles/laboratory-evidence-report.css";
|
||||
@import "./styles/e34-temporal-layer.css";
|
||||
@import "./styles/m4-replay-threat.css";
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
.simulation-profiles { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-height: 0; }
|
||||
.simulation-profiles > .nodedc-select-anchor { justify-self: start; }
|
||||
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
|
||||
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
||||
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
|
||||
.ai-polygon__telemetry-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
|
||||
.ai-polygon__telemetry-row > .ai-polygon__facts { flex: 1; min-width: 0; }
|
||||
.ai-polygon__telemetry-row > :last-child { flex-shrink: 0; }
|
||||
.ai-polygon__section, .ai-polygon__run, .ai-polygon__form { display: grid; gap: .75rem; }
|
||||
.ai-polygon h2, .ai-polygon h3, .ai-polygon p { margin: 0; }
|
||||
.ai-polygon h2 { font-size: var(--nodedc-font-size-title); }
|
||||
.ai-polygon h3, .ai-polygon strong { font-size: var(--nodedc-font-size-md); }
|
||||
.ai-polygon p, .ai-polygon span, .ai-polygon a { font-size: var(--nodedc-font-size-sm); }
|
||||
.ai-polygon p { color: var(--nodedc-text-muted); line-height: 1.5; }
|
||||
.ai-polygon__setup { display: grid; grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); gap: .75rem; }
|
||||
|
||||
.ai-polygon__title { display: flex; align-items: center; gap: 1rem; }
|
||||
.ai-polygon__stage { display: flex; flex-direction: column; gap: .75rem; min-width: 0; }
|
||||
.ai-polygon__viewer { display: flex; flex-direction: column; min-height: 24rem; height: min(65vh, 48rem); overflow: hidden; border-radius: var(--nodedc-radius-panel); background: var(--nodedc-canvas); }
|
||||
.ai-polygon__viewer-toolbar { display: flex; justify-content: space-between; align-items: flex-start; padding: .5rem; gap: .5rem; }
|
||||
.ai-polygon__viewport { flex: 1; position: relative; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon__viewport[hidden] { display: none; }
|
||||
.ai-polygon__viewport .nodedc-loading-region { height: 100%; }
|
||||
.ai-polygon__video { width: 100%; height: 100%; pointer-events: none; }
|
||||
.ai-polygon__video video { display: block; width: 100%; height: 100%; object-fit: contain; }
|
||||
.ai-polygon__preview-error { position: absolute; inset: 0; display: grid; place-content: center; gap: .75rem; background: var(--nodedc-canvas); }
|
||||
.ai-polygon__stage:fullscreen { height: 100%; box-sizing: border-box; padding: .75rem; overflow: auto; background: var(--nodedc-canvas); }
|
||||
.ai-polygon__stage:fullscreen .ai-polygon__viewer { flex: 1; height: auto; min-height: 12rem; }
|
||||
@@ -431,7 +431,7 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
|
||||
case "missions":
|
||||
return <MissionPlannerWorkspace openView={props.navigation.openView} headerToolsHost={props.headerToolsHost} />;
|
||||
case "vehicles":
|
||||
return <VehiclesWorkspace createRequest={props.fleetCreateRequest} />;
|
||||
return <VehiclesWorkspace createRequest={props.fleetCreateRequest} headerToolsHost={props.headerToolsHost} />;
|
||||
case "catalog":
|
||||
return <CatalogWorkspace {...props} />;
|
||||
case "contour-health":
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import {useMemo} from 'react';
|
||||
import {useMemo,type ReactNode} from 'react';
|
||||
import {boardLayout} from '../../core/fleet/boardLayout';
|
||||
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
|
||||
import {createIsolatedRerunHost} from '../../components/rerun/isolatedRerunHost';
|
||||
import {SensorWorkspace} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||
import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
|
||||
export function VehicleSensors({vehicleID,enabled,onDetailChange}:{vehicleID:string;enabled:boolean;onDetailChange:(open:boolean)=>void}){
|
||||
export function VehicleSensors({vehicleID,enabled,computer,description}:{vehicleID:string;enabled:boolean;computer:ReactNode;description:string}){
|
||||
const {registry}=useDevicePluginHost();
|
||||
const sensorContributions=registry.sensorContributions;
|
||||
const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]);
|
||||
const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
||||
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} onDetailChange={onDetailChange}/>;
|
||||
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} board={{layout,computer,description}}/>;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ const platforms = [{ value: "ugv", label: "Наземный (UGV)" }, { value: "
|
||||
const platformLabel = (value: string) => platforms.find(item => item.value === value)?.label ?? value;
|
||||
function statusLabel(item: Vehicle) { return item.enrollment === "pending" ? "Подтверждаем привязку" : item.enrollment === "revoked" ? "Доверие отозвано" : item.enrollment === "failed" ? "Привязка не завершена" : item.connectivity === "online" ? "В сети" : "Нет связи"; }
|
||||
|
||||
export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: number }) {
|
||||
export function VehiclesWorkspace({ createRequest = 0, headerToolsHost }: { createRequest?: number; headerToolsHost?: HTMLElement|null }) {
|
||||
const fleet = useFleet();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [code, setCode] = useState("");
|
||||
@@ -20,7 +20,6 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [sensorOpen, setSensorOpen] = useState(false);
|
||||
const [monitorOpen,setMonitorOpen]=useState(false);
|
||||
const [observationOpen,setObservationOpen]=useState(false);
|
||||
const [revoking, setRevoking] = useState<Vehicle | null>(null);
|
||||
@@ -44,25 +43,24 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe
|
||||
finally { setPending(false); }
|
||||
}
|
||||
const detail = fleet.items?.find(item => item.id === selected);
|
||||
if(detail&&observationOpen)return <BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={!fleet.error&&detail.enrollment==="paired"&&detail.connectivity==="online"} back={()=>{setObservationOpen(false);setSensorOpen(false);}}/>;
|
||||
if(detail&&observationOpen)return <BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={!fleet.error&&detail.enrollment==="paired"&&detail.connectivity==="online"} back={()=>{setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>;
|
||||
if(detail&&monitorOpen)return <BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)}/>;
|
||||
return <div className="fleet-workspace">
|
||||
{fleet.error && <p role="alert">{fleet.error}</p>}
|
||||
{!adding && error && <p role="alert">{error}</p>}
|
||||
{detail ? <>
|
||||
<div><Button onClick={() => {setSelected(null);setSensorOpen(false);}}>К списку аппаратов</Button></div>
|
||||
{!sensorOpen && <SettingsCard title={detail.name} description={`${platformLabel(detail.platform)} · с бортовым компьютером`} actions={<StatusBadge tone={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(detail)}</StatusBadge>}>
|
||||
<div><Button onClick={() => {setSelected(null);}}>К списку аппаратов</Button></div>
|
||||
<VehicleSensors vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} description={detail.name} computer={<SettingsCard title={detail.name} description={`${platformLabel(detail.platform)} · с бортовым компьютером`} actions={<StatusBadge tone={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(detail)}</StatusBadge>}>
|
||||
{detail.notice && <p role="status">{detail.notice}</p>}
|
||||
<dl className="fleet-facts"><div><dt>Бортовой компьютер</dt><dd>{detail.node_id}</dd></div>
|
||||
<div><dt>Последняя связь</dt><dd>{detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}</dd></div>
|
||||
{detail.host && <><div><dt>Имя БК в системе</dt><dd>{detail.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{detail.host.os}</dd></div><div><dt>Архитектура</dt><dd>{detail.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{detail.host.cpus}</dd></div><div><dt>Память</dt><dd>{detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}</dd></div></>}
|
||||
</dl>
|
||||
<div className="fleet-board-actions"><Button onClick={()=>setMonitorOpen(true)}><Icon name="activity"/>Мониторинг системы БК</Button>
|
||||
<Button onClick={()=>setObservationOpen(true)}><Icon name="eye"/>Центр наблюдения</Button>
|
||||
<Button onClick={()=>setObservationOpen(true)}><Icon name="eye"/>Центр наблюдения и управления</Button>
|
||||
{detail.enrollment !== "revoked" && <Button onClick={() => setRevoking(detail)}>Отозвать привязку БК</Button>}</div>
|
||||
</SettingsCard>}
|
||||
<SettingsCard title="Устройства аппарата"><VehicleSensors onDetailChange={setSensorOpen} vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} /></SettingsCard>
|
||||
</> : !fleet.items ? <LoadingRegion loading label="Получение аппаратов" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="sliders" /></IconButton><IconButton label={`Центр наблюдения: ${item.name}`} onClick={() => {setSelected(item.id);setObservationOpen(true);}}><Icon name="eye" /></IconButton></>} /></li>)}</ResourceList>}
|
||||
</SettingsCard>}/>
|
||||
</> : !fleet.items ? <LoadingRegion loading label="Получение аппаратов" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="sliders" /></IconButton><IconButton label={`Центр наблюдения и управления: ${item.name}`} onClick={() => {setSelected(item.id);setObservationOpen(true);}}><Icon name="eye" /></IconButton></>} /></li>)}</ResourceList>}
|
||||
<Window open={adding} title="Добавить аппарат" subtitle="Подключить бортовой компьютер по приглашению Node" size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={close} footer={<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button>{preview ? <Button disabled={pending || !name.trim()} onClick={() => void add()}>{pending ? "Добавление…" : "Добавить аппарат"}</Button> : <Button type="submit" form="fleet-invitation" disabled={pending || !code.trim()}>{pending ? "Проверка БК…" : "Проверить БК"}</Button>}</WindowFooterActions>}>
|
||||
<form id="fleet-invitation" className="fleet-form" onSubmit={inspect} aria-busy={pending}>
|
||||
<Select label="Способ подключения" value="node" options={[{ value: "node", label: "С бортовым компьютером" }]} onChange={() => undefined} disabled={pending} />
|
||||
|
||||
@@ -11,8 +11,11 @@ import {ObservationDeck,ObservationMount} from './ObservationDeck';
|
||||
import {ObservationMap} from './ObservationMap';
|
||||
import {useObservationInventory} from './useObservationInventory';
|
||||
import './observation.css';
|
||||
import {RoverView} from '../../../components/rover/RoverView';
|
||||
import {RoverTelemetry} from '../../../components/rover/RoverTelemetry';
|
||||
import {useRoverControl} from '../../../core/fleet/useRoverControl';
|
||||
|
||||
export function BoardObservationCenter({vehicleID,name,enabled,back}:{vehicleID:string;name:string;enabled:boolean;back:()=>void}){
|
||||
export function BoardObservationCenter({vehicleID,name,enabled,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
|
||||
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
||||
const inventory=useObservationInventory(transport),storageKey=`missioncore.observation.v1:${vehicleID}`;
|
||||
const [layout,setLayout]=useState(()=>{try{return decodeObservationLayout(JSON.parse(localStorage.getItem(storageKey)??'null'));}catch{return emptyObservationLayout();}});
|
||||
@@ -27,17 +30,20 @@ export function BoardObservationCenter({vehicleID,name,enabled,back}:{vehicleID:
|
||||
return views.length?[{device,views,Session:contribution?.Session??CameraObservation}]:[];
|
||||
});
|
||||
const sources:{key:string;deviceID?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
|
||||
sources.push({key:'map',view:{id:'map',label:'Карта'}});
|
||||
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
|
||||
for(const source of sources){if(!mounts.current.has(source.key)){mounts.current.set(source.key,document.createElement('div'));media.current.set(source.key,document.createElement('div'));headers.current.set(source.key,{statusTarget:document.createElement('div'),actionsTarget:document.createElement('div')});mounts.current.get(source.key)!.className='observation-panel-mount';media.current.get(source.key)!.className='observation-media-mount';}}
|
||||
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id));
|
||||
const effectiveFull=full&&visible.includes(full)?full:null;
|
||||
const rover=useRoverControl(vehicleID,enabled&&(visible.includes('rover')||visible.includes('telemetry')));
|
||||
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen;
|
||||
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
||||
const active=sources.find(source=>source.key===focused);
|
||||
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
||||
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
|
||||
return <><div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения · ${name}`}>
|
||||
<header className="observation-toolbar"><div><h2>Центр наблюдения</h2><span>{name}</span></div><div className="observation-actions"><Button onClick={back}><Icon name="sliders"/>Конфигуратор</Button><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
|
||||
return <>{headerToolsHost&&createPortal(<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
|
||||
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>}<Button onClick={configure}><Icon name="sliders"/>Конфигуратор</Button><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
|
||||
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
|
||||
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
|
||||
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
|
||||
@@ -51,7 +57,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,back}:{vehicleID:
|
||||
<div className="observation-actions">
|
||||
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
|
||||
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
|
||||
{source.key!=='map'&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setFocused(source.key);setLayersOpen(true);}}><Icon name="settings"/></IconButton>}
|
||||
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setFocused(source.key);setLayersOpen(true);}}><Icon name="settings"/></IconButton>}
|
||||
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
|
||||
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
|
||||
</div>
|
||||
@@ -63,6 +69,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back}:{vehicleID:
|
||||
</DragDropRoot>
|
||||
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
||||
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
|
||||
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
|
||||
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
|
||||
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title={active?active.view.label:'Доступные слои'} size="md"><div className="observation-settings">
|
||||
{!active&&<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>}
|
||||
{ids.filter(id=>!active||id===active.key).map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
|
||||
|
||||
@@ -11,6 +11,8 @@ export function ObservationMount({element,className='observation-mount'}:{elemen
|
||||
export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onSplit:(key:string,value:number)=>void;depth?:number}){
|
||||
if(!ids.length)return null;
|
||||
if(ids.length===1)return <ObservationMount element={mounts.get(ids[0])!}/>;
|
||||
const mid=Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
|
||||
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
|
||||
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
||||
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
|
||||
return <SplitPane className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
|
||||
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
|
||||
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
|
||||
import { AiRunView } from "../../components/simulation/AiRunView";
|
||||
import { AiRunActions } from "../../components/simulation/AiRunActions";
|
||||
import { AiCompositionFields } from "../../components/simulation/AiCompositionFields";
|
||||
import { fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules, type AiSelection } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiPolygonWorkspace() {
|
||||
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [runId, setRunId] = useState<string | null>(null);
|
||||
const [importing, setImporting] = useState<{ source: AiSource | null; resume?: AiWorld } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [actionsHost, setActionsHost] = useState<HTMLDivElement | null>(null);
|
||||
const [modules, setModules] = useState<AiModules | null>(null);
|
||||
const [selection, setSelection] = useState<AiSelection | undefined>();
|
||||
const fast = useRef(false);
|
||||
const load = useCallback(async () => { const result = await fetchAiCatalog(); setCatalog(result); }, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void fetchAiModules().then((value) => { if (active) { setModules(value); setSelection(value.selection); } })
|
||||
.catch((caught: Error) => { if (active) setError(caught.message); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let active = true; let timer: ReturnType<typeof setTimeout>;
|
||||
const poll = async () => {
|
||||
try { const result = await fetchAiCatalog(); if (active) {
|
||||
setCatalog(result); fast.current = !!result.runtime.active_run;
|
||||
} }
|
||||
catch (caught) { if (active) setError(caught instanceof Error ? caught.message : "Локации недоступны."); }
|
||||
if (active) timer = setTimeout(() => void poll(), fast.current ? 500 : 1500);
|
||||
};
|
||||
void poll(); return () => { active = false; clearTimeout(timer); };
|
||||
}, []);
|
||||
const selected = catalog?.worlds.find((world) => world.world_id === selectedId);
|
||||
const activeRun = catalog?.runtime.active_run;
|
||||
useEffect(() => {
|
||||
if (activeRun?.world.world_id === selectedId) setRunId(activeRun.run_id);
|
||||
}, [activeRun?.run_id, activeRun?.world.world_id, selectedId]);
|
||||
const run = selected ? catalog?.runtime.active_run?.world.world_id === selected.world_id
|
||||
? catalog.runtime.active_run : catalog?.runs.find((item) => item.run_id === runId && item.world.world_id === selected.world_id)
|
||||
: undefined;
|
||||
const acceptRun = (value: AiRun) => {
|
||||
setSettingsOpen(false);
|
||||
setRunId(value.run_id); fast.current = !["completed", "stopped", "failed"].includes(value.state);
|
||||
setCatalog((prior) => prior ? { ...prior, runs: [value, ...prior.runs.filter((r) => r.run_id !== value.run_id)],
|
||||
runtime: { ...prior.runtime, active_run: fast.current ? value : null } } : prior);
|
||||
void load().catch(() => undefined);
|
||||
};
|
||||
const acceptWorld = (value: AiWorld) => {
|
||||
setSelectedId(value.world_id); setImporting(null); setSettingsOpen(false); void load().catch(() => undefined);
|
||||
};
|
||||
const openWorld = (world: AiWorld) => {
|
||||
if (world.status === "uploading") setImporting({ source: world, resume: world });
|
||||
else {
|
||||
setSelectedId(world.world_id); setRunId(null); setSettingsOpen(!world.settings.prepared);
|
||||
}
|
||||
};
|
||||
const returnToLocations = () => { setSelectedId(null); setRunId(null); };
|
||||
const connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
|
||||
{catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"}
|
||||
</StatusBadge>;
|
||||
const sceneActions = selected && catalog ? <>
|
||||
<Button onClick={() => setSettingsOpen(!settingsOpen)}>Старт и масштаб</Button>
|
||||
{!run || ["completed", "stopped", "failed"].includes(run.state) ? <Button variant="primary"
|
||||
icon={<Icon name="play" />} loading={starting}
|
||||
disabled={!catalog.runtime.available || !selected.settings.prepared || !!catalog.runtime.active_run}
|
||||
onClick={() => { setStarting(true); void startAiRun(selected, selection).then(acceptRun)
|
||||
.catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false)); }}>Открыть симуляцию</Button> : null}
|
||||
{run ? <AiRunActions run={run} onChange={acceptRun} /> : null}
|
||||
</> : null;
|
||||
return <div className="ai-polygon">
|
||||
<header className="ai-polygon__head">
|
||||
<div className="ai-polygon__title">
|
||||
{selected ? <IconButton label="Назад к локациям" onClick={returnToLocations}>
|
||||
<Icon name="chevron-left" />
|
||||
</IconButton> : null}
|
||||
<h2>{selected?.name ?? "Доступные локации"}</h2>
|
||||
</div>
|
||||
<div className="ai-polygon__actions" ref={setActionsHost}>
|
||||
{selected ? !run ? sceneActions : null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImporting({ source: null })}>Импорт локации</Button></>}
|
||||
</div>
|
||||
</header>
|
||||
<LoadingRegion className="ai-polygon__content" loading={!catalog && !error} label="Загрузка локаций">
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Не удалось выполнить действие", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
{catalog ? !selected ? <section aria-label="Доступные локации" className="ai-polygon__section">
|
||||
{catalog.worlds.map((world) => <GlassSurface key={world.world_id} padding="md" className="ai-polygon__row">
|
||||
<div><strong>{world.name}</strong><p>{world.author} · {world.license}</p></div>
|
||||
{catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
|
||||
{catalog.runtime.active_run.state === "running" && catalog.runtime.active_run.telemetry?.ai_ready
|
||||
? "AI запущен" : catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
|
||||
</StatusBadge> : null}
|
||||
<Button onClick={() => openWorld(world)}>{world.status === "uploading" ? "Продолжить импорт" : "Открыть"}</Button>
|
||||
</GlassSurface>)}
|
||||
</section> : <section className="ai-polygon__section" aria-label={`Симуляция ${selected.name}`}>
|
||||
<LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
{run ? <AiWorldStream world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
|
||||
actionsHost={actionsHost} headerActions={sceneActions}
|
||||
controls={<AiRunView run={run} connection={connection} />} /> : <div className="ai-polygon__telemetry-row">{connection}</div>}
|
||||
</LoadingRegion>
|
||||
{settingsOpen ? <AiWorldSetup key={selected.world_id} world={selected}
|
||||
disabled={!!catalog.runtime.active_run} onSaved={acceptWorld} /> : null}
|
||||
{settingsOpen && modules && selection ? <AiCompositionFields modules={modules}
|
||||
selection={activeRun?.world.world_id === selectedId ? activeRun.request?.composition ?? selection : selection}
|
||||
disabled={!!catalog.runtime.active_run} onChange={setSelection} /> : null}
|
||||
</section> : null}
|
||||
</LoadingRegion>
|
||||
{importing ? <AiWorldImport source={importing.source} resume={importing.resume}
|
||||
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -13,9 +13,11 @@ import {
|
||||
GlassSurface,
|
||||
Icon,
|
||||
StatusBadge,
|
||||
Select,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import { SimulationCatalog } from "../../components/simulation/SimulationCatalog";
|
||||
import { AiPolygonWorkspace } from "./AiPolygonWorkspace";
|
||||
import { SimulationProjectWindow } from "../../components/simulation/SimulationProjectWindow";
|
||||
import { SimulationViewport } from "../../components/simulation/SimulationViewport";
|
||||
import {
|
||||
@@ -42,6 +44,21 @@ interface BrowserUpload {
|
||||
}
|
||||
|
||||
export function SimulationWorkspace() {
|
||||
const [profile, setProfile] = useState<"lcc" | "ai">(() => {
|
||||
try { return localStorage.getItem("missioncore.simulation-profile") === "ai" ? "ai" : "lcc"; }
|
||||
catch { return "lcc"; }
|
||||
});
|
||||
return <div className="simulation-profiles" data-simulation-profile={profile}>
|
||||
<Select label="Профиль симуляции" value={profile} options={[
|
||||
{ value: "lcc", label: "LCC Gaussian Mirror" }, { value: "ai", label: "AI-полигон" },
|
||||
]} onChange={(value) => { setProfile(value);
|
||||
try { localStorage.setItem("missioncore.simulation-profile", value); } catch { /* Private browsing. */ }
|
||||
}} />
|
||||
{profile === "lcc" ? <LccGaussianWorkspace /> : <AiPolygonWorkspace />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function LccGaussianWorkspace() {
|
||||
const [projects, setProjects] = useState<SimulationProject[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../../../packages/sensor-ui/src/boardLayout.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const {createBoardLayoutStore,defaultBoardLayout}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
function server(){
|
||||
let value=structuredClone(defaultBoardLayout);const calls=[];
|
||||
return {calls,read:async()=>structuredClone(value),patch:async(section,open)=>{
|
||||
calls.push({section,open});await tick();
|
||||
value={...value,revision:value.revision+1,open_sections:defaultBoardLayout.open_sections.filter(id=>id===section?open:value.open_sections.includes(id))};
|
||||
return structuredClone(value);
|
||||
}};
|
||||
}
|
||||
test('rapid toggles persist after navigation and preserve all-closed state',async()=>{
|
||||
const api=server();const store=createBoardLayoutStore(api);await store.load();
|
||||
const unsubscribe=store.subscribe(()=>{});
|
||||
store.change(['settings','devices']);store.change(['devices']);store.change([]);
|
||||
unsubscribe();
|
||||
while(store.getSnapshot().saving)await tick();
|
||||
const reopened=createBoardLayoutStore(api);await reopened.load();
|
||||
assert.deepEqual(reopened.getSnapshot().value.open_sections,[]);
|
||||
assert.equal(api.calls.length,3);
|
||||
});
|
||||
test('a later toggle wins while an older patch is still in flight',async()=>{
|
||||
const api=server();const store=createBoardLayoutStore(api);await store.load();
|
||||
store.change(['settings','devices']);store.change(['computer','settings','devices']);
|
||||
while(store.getSnapshot().saving)await tick();
|
||||
assert.deepEqual((await api.read()).open_sections,defaultBoardLayout.open_sections);
|
||||
});
|
||||
test('different vehicles and simultaneous section changes do not clobber one another',async()=>{
|
||||
const api=server(),other=server();const a=createBoardLayoutStore(api),b=createBoardLayoutStore(api),c=createBoardLayoutStore(other);
|
||||
await Promise.all([a.load(),b.load(),c.load()]);
|
||||
a.change(['settings','devices']);b.change(['computer','devices']);
|
||||
while(a.getSnapshot().saving||b.getSnapshot().saving)await tick();
|
||||
assert.deepEqual((await api.read()).open_sections,['devices']);
|
||||
assert.deepEqual(c.getSnapshot().value.open_sections,defaultBoardLayout.open_sections);
|
||||
});
|
||||
test('failed save reports failure, rolls back, and explicit reload recovers',async()=>{
|
||||
const api=server();let fail=true;
|
||||
const store=createBoardLayoutStore({...api,patch:(...args)=>fail?Promise.reject(new Error('offline')):api.patch(...args)});
|
||||
await store.load();store.change([]);
|
||||
while(store.getSnapshot().saving)await tick();
|
||||
assert.ok(store.getSnapshot().error);
|
||||
assert.deepEqual(store.getSnapshot().value.open_sections,defaultBoardLayout.open_sections);
|
||||
fail=false;await store.load();store.change(['devices']);
|
||||
while(store.getSnapshot().saving)await tick();
|
||||
assert.equal(store.getSnapshot().error,null);
|
||||
assert.deepEqual((await api.read()).open_sections,['devices']);
|
||||
});
|
||||
test('invalid layout cannot overwrite stored preferences',async()=>{
|
||||
let writes=0;
|
||||
const store=createBoardLayoutStore({read:async()=>({...defaultBoardLayout,open_sections:['motor-start']}),patch:async()=>{writes++;return defaultBoardLayout;}});
|
||||
await store.load();store.change([]);
|
||||
assert.equal(store.getSnapshot().ready,false);assert.ok(store.getSnapshot().error);assert.equal(writes,0);
|
||||
});
|
||||
@@ -130,6 +130,15 @@ test("decoder fails closed on an unknown environment schema", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("retired laboratory quick actions resolve to AI Inference", () => {
|
||||
const payload = serverDocument();
|
||||
payload.pages.polygon.primary_workspace_id = "lab-archive";
|
||||
const decoded = environment.decodeEnvironmentSettings(payload);
|
||||
assert.equal(decoded.pages.polygon.primaryWorkspaceId, "observatory");
|
||||
assert.equal(decoded.revision, payload.revision);
|
||||
assert.deepEqual(decoded.pages.polygon.background.items, []);
|
||||
});
|
||||
|
||||
test("editing a cloned page cannot mutate accepted settings", () => {
|
||||
const accepted = environment.decodeEnvironmentSettings(serverDocument());
|
||||
const draft = environment.cloneEnvironmentSettings(accepted);
|
||||
|
||||
@@ -27,7 +27,7 @@ async function read(relativePath) {
|
||||
test("Observatory is the third independent Polygon workspace", () => {
|
||||
assert.deepEqual(
|
||||
productModel.workspacesForRoot("polygon").map(({ id }) => id),
|
||||
["lab-archive", "simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
["simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
productModel.workspaceById("observatory"),
|
||||
|
||||
@@ -324,7 +324,7 @@ test("Polygon exposes one dataset surface and keeps legacy links compatible", ()
|
||||
assert.equal(workspaceById("datasets").kind, "datasets");
|
||||
assert.deepEqual(
|
||||
workspacesForRoot("polygon").map(({ id }) => id),
|
||||
["lab-archive", "simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
["simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
);
|
||||
assert.equal(
|
||||
workspacesForRoot("system").some(({ id }) => id === "polygon-run"),
|
||||
|
||||
@@ -29,7 +29,7 @@ test("top navigation has no Center and Park owns contour health first", () => {
|
||||
assert.equal(productModel.workspaceById("contour-health")?.root, "fleet");
|
||||
assert.deepEqual(
|
||||
productModel.workspacesForRoot("polygon").map(({ id }) => id),
|
||||
["lab-archive", "simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
["simulations", "observatory", "local-device", "spatial-scene", "mission-planner"],
|
||||
);
|
||||
assert.equal(productModel.workspaceById("spatial-scene")?.root, "polygon");
|
||||
assert.equal(productModel.workspacesForRoot("observation").some(({ id }) => id === "spatial-scene"), false);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
|
||||
async function moduleAt(path) {
|
||||
const result = await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,format:'esm',platform:'node'});
|
||||
return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
}
|
||||
const {defaultProfile:base,mix,motorDemands,parseProfile}=await moduleAt('../../../packages/rover-control/src/profile.ts');
|
||||
const {AuthorityModel}=await moduleAt('../../../packages/rover-control/src/authority.ts');
|
||||
const axes=(leftY=0,rightY=0,leftX=0,rightX=0)=>({leftY,rightY,leftX,rightX});
|
||||
const profile={...base,deadband:0};
|
||||
const arcade={...profile,mode:'arcade'};
|
||||
const policy={maxAgeMs:100,neutralMs:200,maxCommandMs:100,monitoredAxes:['leftY','rightY','leftX','rightX']};
|
||||
const motors=['a','b','c','d'];
|
||||
function frame(now,values=axes(),extra={}) {
|
||||
return {now,link:{state:'live',at:now},
|
||||
axes:Object.fromEntries(Object.entries(values).map(([key,value])=>[key,{value,at:now,sequence:now}])),
|
||||
drives:Object.fromEntries(motors.map(id=>[id,{at:now,healthy:true,stopped:true}])),...extra};
|
||||
}
|
||||
function ready(p=base) {
|
||||
const model=new AuthorityModel(p,motors,policy,'boot-A');
|
||||
for(let t=0;t<=200;t+=50)model.step(frame(t));
|
||||
return model;
|
||||
}
|
||||
function core() {
|
||||
const model=ready();
|
||||
const {token}=model.step(frame(250,axes(),{requestCore:{owner:'autonomy',sequence:1,at:250}}));
|
||||
assert.ok(token);return {model,token};
|
||||
}
|
||||
const command=(token,at,sequence=0)=>({token,at,expires:at+75,sequence,demand:{left:.5,right:.5}});
|
||||
|
||||
test('tank keeps the two motor sides independent, including reversal',()=>{
|
||||
assert.deepEqual(mix(profile,axes(.8,-.4)),{left:.8,right:-.4});
|
||||
assert.deepEqual(mix(profile,axes(0,.4)),{left:0,right:.4});
|
||||
});
|
||||
test('arcade cardinal, diagonal and reverse vectors preserve yaw sign',()=>{
|
||||
for(const [y,x,left,right] of [[0,0,0,0],[1,0,1,1],[-1,0,-1,-1],[0,1,1,-1],[0,-1,-1,1],[1,1,1,0],[1,-1,0,1],[-1,1,0,-1],[-1,-1,-1,0]])
|
||||
assert.deepEqual(mix(arcade,axes(0,y,0,x)),{left,right});
|
||||
assert.deepEqual(mix(arcade,axes(0,.5,0,.5)),{left:.5,right:0});
|
||||
});
|
||||
test('selected stick defines the axes, not the number or position of motors',()=>{
|
||||
assert.deepEqual(mix({...arcade,stick:'left'},axes(.5,-1,.5,-1)),{left:.5,right:0});
|
||||
});
|
||||
test('deadband is continuous and rescaled; response and output scale are separate',()=>{
|
||||
assert.deepEqual(mix(base,axes(-.064,.074)),{left:0,right:0});
|
||||
assert.deepEqual(mix({...profile,deadband:.2,response:'squared',outputScale:.5},axes(.6,-1)),{left:.12499999999999997,right:-.5});
|
||||
assert.ok(Math.abs(mix(base,axes(.150001)).left)<.000002);
|
||||
});
|
||||
test('every point in the input square stays bounded and changes sign symmetrically',()=>{
|
||||
for(let i=-20;i<=20;i++)for(let j=-20;j<=20;j++){
|
||||
const a=mix({...arcade,outputScale:.8},axes(0,i/20,0,j/20));
|
||||
const b=mix({...arcade,outputScale:.8},axes(0,-i/20,0,-j/20));
|
||||
assert.ok(Math.abs(a.left)<=.8+1e-12 && Math.abs(a.right)<=.8+1e-12);
|
||||
assert.ok(Math.abs(a.left+b.left)<1e-12 && Math.abs(a.right+b.right)<1e-12);
|
||||
}
|
||||
});
|
||||
test('profile JSON rejects unknown fields, malformed numbers and unknown schema',()=>{
|
||||
assert.deepEqual(parseProfile(JSON.parse(JSON.stringify(base))),base);
|
||||
for(const bad of [null,[],{...base,schema:'future'},{...base,revision:1.5},{...base,revision:-1},{...base,deadband:NaN},{...base,outputScale:1.1},{...base,writeVesc:true}])assert.throws(()=>parseProfile(bad));
|
||||
for(const value of [NaN,Infinity,1.01,undefined])assert.throws(()=>mix(profile,{...axes(),leftY:value}));
|
||||
});
|
||||
test('2, 4 and 10 motors route by identity and explicit direction, never USB position',()=>{
|
||||
for(const n of [2,4,10]){
|
||||
const bindings=Array.from({length:n},(_,i)=>({uuid:i.toString(16).padStart(24,'0'),side:i<n/2?'left':'right',forwardSign:i%2?1:-1}));
|
||||
const result=motorDemands({left:.3,right:-.6},bindings);
|
||||
assert.equal(Object.keys(result).length,n);
|
||||
assert.deepEqual(result,motorDemands({left:.3,right:-.6},bindings.toReversed()));
|
||||
}
|
||||
const b={uuid:'0'.repeat(24),side:'left',forwardSign:1};
|
||||
assert.throws(()=>motorDemands({left:1,right:1},[b]));
|
||||
assert.throws(()=>motorDemands({left:1,right:1},[b,{...b,side:'right'}]));
|
||||
});
|
||||
test('boot with held stick never permits motion; stable stopped neutral required',()=>{
|
||||
const model=new AuthorityModel(base,motors,policy,'boot');
|
||||
for(let t=0;t<1000;t+=50){const d=model.step(frame(t,axes(1)));assert.equal(d.state,'hold');assert.deepEqual(d.demand,{left:0,right:0});}
|
||||
for(let t=1000;t<1200;t+=50)assert.equal(model.step(frame(t)).state,'hold');
|
||||
assert.equal(model.step(frame(1200)).state,'rc-ready');
|
||||
assert.equal(model.step(frame(1250,axes(1))).state,'rc-manual');
|
||||
});
|
||||
test('first RC gesture stops Core immediately, held packets never count as second gesture',()=>{
|
||||
const {model,token}=core();
|
||||
assert.equal(model.step(frame(300,axes(),{command:command(token,300)})).state,'core');
|
||||
const first=model.step(frame(350,axes(.5),{command:command(token,350,1)}));
|
||||
assert.equal(first.reason,'rc-takeover');assert.ok(first.stopAll&&first.flushMotionQueue&&first.cancelMotionTasks);
|
||||
for(let t=400;t<1500;t+=50)assert.deepEqual(model.step(frame(t,axes(.5))).demand,{left:0,right:0});
|
||||
for(let t=1500;t<=1700;t+=50)model.step(frame(t));
|
||||
const second=model.step(frame(1750,axes(.5)));
|
||||
assert.equal(second.state,'rc-manual');assert.ok(second.demand.left>0);
|
||||
assert.equal(model.step(frame(1800)).state,'rc-manual');
|
||||
assert.equal(model.step(frame(1850,axes(0,.5),{command:command(token,1850,2)})).state,'rc-manual');
|
||||
});
|
||||
test('neutral of one channel or a single moving member never completes rearming',()=>{
|
||||
for(const kind of ['axis','drive']){
|
||||
const {model}=core();model.step(frame(300,axes(1)));
|
||||
for(let t=350;t<=1500;t+=50){const f=frame(t,kind==='axis'?axes(0,.2):axes());if(kind==='drive')f.drives.d.stopped=false;assert.equal(model.step(f).state,'hold');}
|
||||
}
|
||||
});
|
||||
test('loss of any of four controllers stops all sides and invalidates Core',()=>{
|
||||
for(const id of motors){const {model,token}=core();const f=frame(300,axes(),{command:command(token,300)});delete f.drives[id];const d=model.step(f);assert.equal(d.reason,'drive-unverified');assert.ok(d.cancelMotionTasks);assert.deepEqual(d.demand,{left:0,right:0});}
|
||||
});
|
||||
test('unknown/lost radio cannot be treated as neutral even with fresh zero PWM reads',()=>{
|
||||
for(const state of ['lost','unknown']){const {model,token}=core();const d=model.step(frame(300,axes(),{link:{state,at:300},command:command(token,300)}));assert.equal(d.reason,'receiver-unverified');assert.ok(d.stopAll);}
|
||||
});
|
||||
test('old decoded PPM, future samples, modified repeats and sequence rollback are rejected',()=>{
|
||||
for(const patch of [{at:0},{at:351},{sequence:249},{value:.4,at:250,sequence:250},{value:NaN}]){
|
||||
const {model}=core();const f=frame(350);Object.assign(f.axes.leftY,patch);assert.equal(model.step(f).reason,'axis-invalid');
|
||||
}
|
||||
});
|
||||
test('one repeated neutral sample cannot qualify stable neutral',()=>{
|
||||
const model=new AuthorityModel(base,motors,{...policy,neutralMs:50},'boot');
|
||||
model.step(frame(0));const f=frame(50);f.axes.leftY={at:0,sequence:0,value:0};
|
||||
assert.equal(model.step(f).state,'hold');
|
||||
});
|
||||
test('receiver reconnect while held stays stopped until neutral and a new gesture',()=>{
|
||||
const model=ready();model.step(frame(250,axes(.5)));model.step(frame(300,axes(),{link:{state:'lost',at:300}}));
|
||||
for(let t=350;t<1000;t+=50)assert.equal(model.step(frame(t,axes(.5))).state,'hold');
|
||||
for(let t=1000;t<=1200;t+=50)model.step(frame(t));
|
||||
assert.equal(model.step(frame(1250,axes(.5))).state,'rc-manual');
|
||||
});
|
||||
test('Core expiry/replay/wrong boot token/missing commands all require rearming',()=>{
|
||||
for(const change of [c=>({...c,expires:300}),c=>({...c,expires:500}),c=>({...c,token:'old-boot:1'}),()=>undefined,c=>({...c,demand:{left:Infinity,right:0}})]){
|
||||
const {model,token}=core();assert.equal(model.step(frame(300,axes(),{command:change(command(token,300))})).reason,'core-command-invalid');
|
||||
}
|
||||
const {model,token}=core();model.step(frame(300,axes(),{command:command(token,300,1)}));
|
||||
assert.equal(model.step(frame(350,axes(),{command:command(token,350,1)})).reason,'core-command-invalid');
|
||||
});
|
||||
test('clock rewind and missing observation interval cannot bypass the stop gate',()=>{
|
||||
for(const time of [249,500,NaN]){const {model,token}=core();const d=model.step(frame(time,axes(),{command:command(token,time)}));assert.equal(d.state,'hold');assert.ok(d.cancelMotionTasks);}
|
||||
});
|
||||
test('premature or replayed Core request does not acquire authority after neutral',()=>{
|
||||
const model=new AuthorityModel(base,motors,policy,'boot');
|
||||
for(let t=0;t<=300;t+=50){const d=model.step(frame(t,axes(),{requestCore:{owner:'remote',sequence:1,at:t}}));assert.notEqual(d.state,'core');}
|
||||
assert.equal(model.step(frame(350,axes(),{requestCore:{owner:'remote',sequence:2,at:350}})).state,'core');
|
||||
});
|
||||
test('reboot cannot restore authority from serialized profile or old grant',()=>{
|
||||
const {token}=core(), model=ready();
|
||||
assert.equal(model.step(frame(250,axes(),{command:command(token,250)})).state,'rc-ready');
|
||||
const next=new AuthorityModel(base,motors,policy,'boot-B');
|
||||
for(let t=0;t<=200;t+=50)next.step(frame(t));
|
||||
const grant=next.step(frame(250,axes(),{requestCore:{owner:'remote',sequence:1,at:250}}));
|
||||
assert.notEqual(grant.token,token);
|
||||
assert.equal(next.step(frame(300,axes(),{command:command(token,300)})).state,'hold');
|
||||
});
|
||||
test('profile limits do not mask RC takeover intent at zero output scale',()=>{
|
||||
const model=ready({...base,outputScale:0});const grant=model.step(frame(250,axes(),{requestCore:{owner:'remote',sequence:1,at:250}}));
|
||||
assert.ok(grant.token);assert.equal(model.step(frame(300,axes(.5))).reason,'rc-takeover');
|
||||
});
|
||||
|
||||
test('non-driving stick still takes over in Arcade and every monitored axis must return',()=>{
|
||||
const model=ready({...base,mode:'arcade',stick:'right'});
|
||||
model.step(frame(250,axes(),{requestCore:{owner:'autonomy',sequence:1,at:250}}));
|
||||
assert.equal(model.step(frame(300,axes(.5))).reason,'rc-takeover');
|
||||
for(let t=350;t<800;t+=50)assert.equal(model.step(frame(t,axes(0,0,.5))).state,'hold');
|
||||
const f=frame(800);delete f.axes.leftX;assert.equal(model.step(f).reason,'axis-invalid');
|
||||
assert.throws(()=>new AuthorityModel(base,motors,{...policy,monitoredAxes:['leftY']},'boot'));
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`}));
|
||||
}}]});
|
||||
const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const flush=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
async function fixture(run){
|
||||
const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]]));
|
||||
let focus=true,hidden=false;const calls=[],timers=[];globalThis.roverEffects=[];
|
||||
globalThis.window={addEventListener(){},removeEventListener(){}};
|
||||
globalThis.document={get hidden(){return hidden;},hasFocus:()=>focus,addEventListener(){},removeEventListener(){}};
|
||||
globalThis.setInterval=(f,ms)=>{const timer={f,ms};timers.push(timer);return timer;};globalThis.clearInterval=()=>{};
|
||||
globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body});return {ok:true,json:async()=>url.endsWith('/arm')?{session_id:'fixture-session'}:{fresh:true,controlling:true,snapshot:{state:'ready'}}};};
|
||||
const c=useRoverControl('fixture',true);const cleanup=globalThis.roverEffects.map(f=>f());
|
||||
try{await flush();await c.arm(30,2000);await flush();await run({c,calls,timers,blur:()=>{focus=false;},focus:()=>{focus=true;},hide:()=>{hidden=true;}});}
|
||||
finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
|
||||
}
|
||||
test('command heartbeat sends neutral on lost blur, keeps session, and accepts new focused input',async()=>fixture(async f=>{
|
||||
f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush();
|
||||
assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===100).f();await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.focus();f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1);
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
test('expired physical input prevents heartbeat from renewing remembered demand',async()=>fixture(async f=>{
|
||||
let valid=true;f.c.setInputGuard(()=>valid);f.c.setDemand({left:1,right:-1});await flush();valid=false;
|
||||
f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.stop,false);
|
||||
}));
|
||||
test('no registered input scope cannot issue motion',async()=>fixture(async f=>{
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.stop,false);
|
||||
assert.equal(f.calls.some(x=>x.body?.left===1),false);
|
||||
}));
|
||||
test('hidden document sends only neutral without a visibility event',async()=>fixture(async f=>{
|
||||
f.c.setInputGuard(()=>true);f.hide();f.c.setDemand({left:1,right:1});await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.some(x=>x.body?.left===1),false);
|
||||
}));
|
||||
|
||||
test('explicit pause clears demand without revoking session; explicit stop still revokes it',async()=>fixture(async f=>{
|
||||
f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush();f.c.pauseInput();await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1);
|
||||
f.c.stop();await flush();assert.equal(f.calls.at(-1).body.stop,true);
|
||||
const count=f.calls.length;f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.length,count);
|
||||
}));
|
||||
@@ -0,0 +1,49 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`}));
|
||||
}}]});
|
||||
const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const flush=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
|
||||
const response=value=>({ok:true,json:async()=>value});
|
||||
const idle={fresh:true,controlling:false,snapshot:{supported:true,state:'observing'}};
|
||||
async function fixture(run){
|
||||
const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]]));
|
||||
const calls=[],timers=[];globalThis.roverEffects=[];
|
||||
globalThis.window={addEventListener(){},removeEventListener(){}};globalThis.document={hidden:false,hasFocus:()=>true,addEventListener(){},removeEventListener(){}};
|
||||
globalThis.setInterval=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearInterval=()=>{};
|
||||
let armResponse=null,nextPoll=null;
|
||||
globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body});
|
||||
if(url.endsWith('/arm'))return armResponse?armResponse.promise:response({session_id:'new-session'});
|
||||
if(!body)return nextPoll?nextPoll.promise:response(idle);
|
||||
return response({accepted_sequence:body.sequence});
|
||||
};
|
||||
const c=useRoverControl('fixture',true),cleanup=globalThis.roverEffects.map(f=>f());
|
||||
try{await flush();await run({c,calls,poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===100).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});}
|
||||
finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
|
||||
}
|
||||
test('idle poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{
|
||||
const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll();
|
||||
a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush();
|
||||
p.resolve(response(idle));await flush();f.heartbeat();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old idle poll revoked the new session');
|
||||
assert.equal(f.calls.at(-1).body.session_id,'new-session');
|
||||
}));
|
||||
test('failed poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{
|
||||
const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll();
|
||||
a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush();
|
||||
p.resolve({ok:false,json:async()=>({detail:'stale read failure'})});await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old failed poll revoked the new session');
|
||||
}));
|
||||
test('a current poll still revokes control when server reports lease lost',async()=>fixture(async f=>{
|
||||
assert.equal(await f.c.arm(30,2000),true);await flush();f.poll();await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
}));
|
||||
test('duplicate arm clicks while request pending create exactly one lease request',async()=>fixture(async f=>{
|
||||
const a=f.delayArm();const first=f.c.arm(30,2000),second=f.c.arm(30,2000);
|
||||
a.resolve(response({session_id:'new-session'}));await Promise.all([first,second]);await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
@@ -0,0 +1,85 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverHoldInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {bindRoverHoldInput}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
class Events {
|
||||
listeners=new Map();timers=new Map();next=0;
|
||||
addEventListener(type,fn){if(!this.listeners.has(type))this.listeners.set(type,new Set());this.listeners.get(type).add(fn);}
|
||||
removeEventListener(type,fn){this.listeners.get(type)?.delete(fn);}
|
||||
emit(type,detail={}){const e={target:this,isTrusted:true,preventDefault(){},...detail};for(const fn of [...(this.listeners.get(type)??[])])fn(e);}
|
||||
setInterval(fn){const id=++this.next;this.timers.set(id,fn);return id;}
|
||||
clearInterval(id){this.timers.delete(id);}
|
||||
tick(){for(const fn of this.timers.values())fn();}
|
||||
}
|
||||
function fixture(mode='arcade'){
|
||||
let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus;
|
||||
const scope={ownerDocument:doc,closest:()=>null},child={closest:()=>null};scope.contains=x=>x===scope||x===child;doc.activeElement=scope;
|
||||
const states=[],demands=[];let stops=0,pauses=0;
|
||||
const binding=bindRoverHoldInput(scope,mode,{held:k=>states.push([...k]),demand:d=>demands.push(d),stop:()=>stops++,pause:()=>{pauses++;demands.push({left:0,right:0});}},()=>time);
|
||||
const key=(code,repeat=false)=>win.emit('keydown',{code,repeat,target:scope});
|
||||
return {win,doc,scope,child,binding,states,demands,key,stops:()=>stops,pauses:()=>pauses,advance:ms=>{time+=ms;win.tick();},loseFocus:()=>{focus=false;},restoreFocus:()=>{focus=true;},up:code=>win.emit('keyup',{code,target:scope})};
|
||||
}
|
||||
test('blur clears D, ignores a late repeat, but accepts a fresh press without rearming',()=>{
|
||||
const f=fixture();f.key('KeyD');assert.deepEqual(f.demands.at(-1),{left:1,right:-1});
|
||||
f.win.emit('blur');assert.equal(f.pauses(),1);assert.equal(f.stops(),0);assert.deepEqual(f.states.at(-1),[]);
|
||||
assert.deepEqual(f.demands.at(-1),{left:0,right:0});const count=f.demands.length;
|
||||
f.key('KeyD',true);assert.equal(f.demands.length,count);
|
||||
f.key('KeyW');assert.deepEqual(f.demands.at(-1),{left:1,right:1});assert.equal(f.binding.valid(),true);f.binding.dispose();
|
||||
});
|
||||
test('heartbeat validity catches missing blur event using document focus',()=>{
|
||||
const f=fixture();f.key('KeyD');f.loseFocus();assert.equal(f.binding.valid(),false);assert.equal(f.pauses(),1);
|
||||
f.restoreFocus();assert.equal(f.binding.valid(),true);f.binding.dispose();
|
||||
});
|
||||
test('focus polling catches missing event or moving to another control',()=>{
|
||||
const f=fixture();f.key('KeyW');f.doc.activeElement={};f.advance(50);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
});
|
||||
test('lost keyup AND missing focus notifications still expire repeated D',()=>{
|
||||
const f=fixture();f.key('KeyD');f.advance(500);f.key('KeyD',true);f.advance(299);assert.equal(f.pauses(),0);
|
||||
f.advance(1);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.key('KeyD',true);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
});
|
||||
test('first press allows OS repeat delay but never an indefinite hold',()=>{
|
||||
const f=fixture();f.key('KeyW');f.advance(999);assert.equal(f.pauses(),0);f.advance(1);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
});
|
||||
test('continuous repeat renews hold; keyup immediately sends neutral',()=>{
|
||||
const f=fixture();f.key('KeyW');f.advance(600);
|
||||
for(let i=0;i<30;i++){f.key('KeyW',true);f.advance(100);}
|
||||
assert.equal(f.pauses(),0);f.up('KeyW');assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.advance(1200);assert.equal(f.pauses(),0);f.binding.dispose();
|
||||
});
|
||||
test('diagonal input survives single-key OS repeat; release recomputes demand',()=>{
|
||||
const f=fixture();f.key('KeyW');f.key('KeyA');
|
||||
for(let i=0;i<20;i++){f.key('KeyA',true);f.advance(100);}
|
||||
assert.equal(f.pauses(),0);assert.deepEqual(f.demands.at(-1),{left:0,right:1});
|
||||
f.up('KeyA');assert.deepEqual(f.demands.at(-1),{left:1,right:1});f.up('KeyW');f.binding.dispose();
|
||||
});
|
||||
test('repeat without a fresh press and untrusted events never command motion',()=>{
|
||||
const f=fixture();f.key('KeyD',true);f.win.emit('keydown',{code:'KeyW',isTrusted:false,target:f.scope});assert.equal(f.demands.length,0);f.binding.dispose();
|
||||
});
|
||||
test('focus inside the view is allowed; leaving or hiding it stops',()=>{
|
||||
for(const event of ['focusout','visibilitychange','pagehide','outside']){
|
||||
const f=fixture();f.key('KeyW');f.doc.emit('focusout',{target:f.scope,relatedTarget:f.child});assert.equal(f.pauses(),0);
|
||||
if(event==='focusout')f.doc.emit(event,{target:f.scope,relatedTarget:null});
|
||||
else if(event==='visibilitychange'){f.doc.hidden=true;f.doc.emit(event);}
|
||||
else if(event==='pagehide')f.win.emit(event);
|
||||
else f.doc.emit('pointerdown',{target:{}});
|
||||
assert.equal(event==='pagehide'?f.stops():f.pauses(),1,event);f.binding.dispose();
|
||||
}
|
||||
});
|
||||
test('pointer capture lost or cancelled releases every input',()=>{
|
||||
for(const mode of ['arcade','tank']){
|
||||
const f=fixture(mode);f.binding.pointerDown(1,mode==='arcade'?'KeyW':'KeyQ');f.binding.pointerCancel(1);
|
||||
assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.binding.dispose();
|
||||
}
|
||||
});
|
||||
test('document pointerup releases even if button handler does not receive it',()=>{
|
||||
const f=fixture();f.binding.pointerDown(1,'KeyD');f.doc.emit('pointerup',{pointerId:1});assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.pauses(),0);f.binding.dispose();
|
||||
});
|
||||
test('modifier shortcuts pause; cleanup removes listeners, timer and held demand',()=>{
|
||||
const f=fixture();f.key('KeyD');f.win.emit('keydown',{code:'Tab',metaKey:true,target:f.scope});assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.win.timers.size,0);
|
||||
assert.equal([...f.win.listeners.values(),...f.doc.listeners.values()].reduce((sum,x)=>sum+x.size,0),0);
|
||||
});
|
||||
|
||||
test('Space and Escape remain explicit session stops',()=>{
|
||||
for(const code of ['Space','Escape']){const f=fixture();f.key('KeyW');f.key(code);assert.equal(f.stops(),1);assert.equal(f.binding.valid(),false);f.binding.dispose();}
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {keyDemand,roverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const keys=(...k)=>new Set(k.map(v=>'Key'+v));
|
||||
test('arcade mixes directions and opposite keys cancel',()=>{
|
||||
assert.deepEqual(keyDemand('arcade',keys('W')),{left:1,right:1});
|
||||
assert.deepEqual(keyDemand('arcade',keys('A')),{left:-1,right:1});
|
||||
assert.deepEqual(keyDemand('arcade',keys('W','A')),{left:0,right:1});
|
||||
assert.deepEqual(keyDemand('arcade',keys('W','S','A','D')),{left:0,right:0});
|
||||
});
|
||||
test('tank sides and backwards remain independent',()=>{
|
||||
assert.deepEqual(keyDemand('tank',keys('Q','D')),{left:1,right:-1});
|
||||
assert.deepEqual(keyDemand('tank',keys('A','D')),{left:-1,right:-1});
|
||||
assert.deepEqual(keyDemand('tank',keys('Q','A')),{left:0,right:0});
|
||||
});
|
||||
test('invalid stored settings never grant motion or invalid limits',()=>{
|
||||
assert.equal(roverSettings({version:1,currentA:Infinity}).currentA,30);
|
||||
assert.equal(roverSettings({version:1,maxErpm:999999}).maxErpm,3000);
|
||||
assert.equal(roverSettings({version:1,model:'https://other/model.glb'}).model,'');
|
||||
assert.deepEqual(keyDemand('arcade',new Set()),{left:0,right:0});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/model.ts',import.meta.url),'utf8');
|
||||
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {vescLabel,testInput,speedInput,rotationResult,driveTestIds}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const controller={online:true,prepared:true,verified:true,vesc_status:{identity:{uuid:'synthetic'},readable:true}};
|
||||
|
||||
test('speed mode requires board capability and reports measured rotation time',()=>{
|
||||
assert.ok(speedInput('1200',undefined).error);
|
||||
const bounds={min_erpm:300,max_erpm:3000,duration_basis:'measured_speed'};
|
||||
assert.equal(speedInput('1200',bounds).error,null);
|
||||
for(const value of ['', 'NaN','299','3001'])assert.ok(speedInput(value,bounds).error);
|
||||
const text=rotationResult({outcome:'stopped',rotation_s:2.5,release_confirmed:true,limits_restored:true});
|
||||
assert.match(text,/2,5 с/);
|
||||
assert.match(text,/Проверка остановлена/);
|
||||
assert.doesNotMatch(text,/время вращения набрано/);
|
||||
});
|
||||
|
||||
test('USB discovery and model preparation never claim a verified VESC',()=>{
|
||||
assert.equal(vescLabel({...controller,prepared:false},true).label,'Требуется подготовка');
|
||||
assert.equal(vescLabel({...controller,vesc_status:{identity:null,readable:false}},true).tone,'warning');
|
||||
});
|
||||
test('fresh read capability is distinct from unsupported firmware and offline state',()=>{
|
||||
assert.equal(vescLabel(controller,true).label,'Готов к чтению');
|
||||
assert.equal(vescLabel(controller,false).label,'Нет связи');
|
||||
assert.equal(vescLabel({...controller,online:false},true).label,'Нет связи');
|
||||
assert.equal(vescLabel({...controller,vesc_status:{identity:{uuid:'synthetic'},readable:false}},true).label,'Прошивка не поддерживается');
|
||||
});
|
||||
|
||||
test('test fields accept entered values only inside the board capability bounds',()=>{
|
||||
const bounds={min_current_a:0.5,max_current_a:5,min_duration_s:0.5,max_duration_s:10};
|
||||
assert.equal(testInput('3.7','7.2',bounds).valid,true);
|
||||
assert.equal(testInput('5','10',bounds).valid,true);
|
||||
for(const [amps,seconds] of [['','5'],['5',''],['60','10'],['5','11'],['NaN','1'],['Infinity','1']])assert.equal(testInput(amps,seconds,bounds).valid,false);
|
||||
assert.equal(testInput('2','1.5',undefined).valid,false);
|
||||
const overlong=testInput('5','15',bounds);
|
||||
assert.equal(overlong.valid,false);
|
||||
assert.equal(overlong.currentError,null);
|
||||
assert.equal(overlong.durationError,'Длительность должна быть от 0,5 до 10 с.');
|
||||
assert.equal(testInput('5','10',bounds).durationError,null);
|
||||
});
|
||||
|
||||
// Capabilities come from the installed board: a newer Core must retain old bounds.
|
||||
test('extended board accepts 30 A / 30 s without changing older board bounds',()=>{
|
||||
const old={min_current_a:0.5,max_current_a:5,min_duration_s:0.5,max_duration_s:10};
|
||||
const expanded={...old,max_current_a:30,max_duration_s:30,continuous_current:true};
|
||||
assert.equal(testInput('30','30',expanded).valid,true);
|
||||
assert.equal(testInput('30.1','30',expanded).valid,false);
|
||||
assert.equal(testInput('30','30.1',expanded).valid,false);
|
||||
assert.equal(testInput('30','30',old).valid,false);
|
||||
});
|
||||
|
||||
|
||||
test('group spin requires a complete unique profile containing the selected controller',()=>{
|
||||
const profile={layout:'1x1',revision:3,bindings:{'left.1':{device_id:'left',uuid:'a'},'right.1':{device_id:'right',uuid:'b'}}};
|
||||
assert.deepEqual(driveTestIds(profile,'left'),['left','right']);
|
||||
assert.deepEqual(driveTestIds(profile,'unassigned'),[]);
|
||||
assert.deepEqual(driveTestIds({...profile,bindings:{'left.1':profile.bindings['left.1']}},'left'),[]);
|
||||
assert.deepEqual(driveTestIds({...profile,bindings:{...profile.bindings,'right.1':profile.bindings['left.1']}},'left'),[]);
|
||||
assert.deepEqual(driveTestIds(undefined,'left'),[]);
|
||||
});
|
||||
|
||||
test('four-wheel profile preserves front and rear membership for common testing',()=>{
|
||||
const ids=['lf','lr','rf','rr'];
|
||||
const bindings=Object.fromEntries(['left.1','left.2','right.1','right.2'].map((slot,i)=>[slot,{device_id:ids[i],uuid:ids[i]}]));
|
||||
assert.deepEqual(driveTestIds({layout:'2x2',revision:4,bindings},'rf'),ids);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import {build} from 'esbuild';
|
||||
import {mkdir,writeFile} from 'node:fs/promises';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {resolve,join} from 'node:path';
|
||||
|
||||
const root=fileURLToPath(new URL('.',import.meta.url));
|
||||
const destination=process.argv[2];
|
||||
if(!destination)throw Error('Pass an artifact output directory; no server is started.');
|
||||
const result=await build({entryPoints:[join(root,'main.tsx')],bundle:true,write:false,minify:true,
|
||||
format:'iife',platform:'browser',jsx:'automatic',outfile:'preview.js',define:{'process.env.NODE_ENV':'"production"'},
|
||||
alias:{'@nodedc/ui-react':resolve(root,'../../node_modules/@nodedc/ui-react/dist/index.js')},
|
||||
nodePaths:[resolve(root,'../../node_modules')],logLevel:'warning'});
|
||||
const js=result.outputFiles.find(f=>f.path.endsWith('.js')).text.replaceAll('</script','<\\/script');
|
||||
const css=result.outputFiles.find(f=>f.path.endsWith('.css')).text.replaceAll('</style','<\\/style');
|
||||
await mkdir(destination,{recursive:true});
|
||||
const html=`<!doctype html><html lang="ru" data-nodedc-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; connect-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:"><title>Mission Core · Профили управления · Прототип</title><style>${css}</style></head><body data-nodedc-ui><div id="root"></div><script>${js}</script></body></html>`;
|
||||
await writeFile(join(destination,'rover-control-preview.html'),html);
|
||||
console.log(JSON.stringify({artifact:join(destination,'rover-control-preview.html'),bytes:Buffer.byteLength(html),network:'disabled by CSP',hardware:'no adapter'}));
|
||||
@@ -0,0 +1,69 @@
|
||||
import {useState} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {Button,Inspector,InspectorSelectField,RangeControl,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import '@nodedc/ui-core/styles.css';
|
||||
import {defaultProfile,mix,parseProfile,type Axes,type ControlProfile} from '../../../../packages/rover-control/src/profile';
|
||||
import {trace} from './trace';
|
||||
import './preview.css';
|
||||
|
||||
const emptyAxes:Axes={leftY:0,rightY:0,leftX:0,rightX:0};
|
||||
const percent=(n:number)=>`${Math.round(n*100)}%`;
|
||||
const states={'hold':'Остановка / ожидание нейтрали','rc-ready':'Пульт готов','rc-manual':'Ручное управление','core':'Mission Core'};
|
||||
const storageKey='missioncore.rover-control-preview.v1';
|
||||
function load():ControlProfile {
|
||||
try{const raw=localStorage.getItem(storageKey);return raw?parseProfile(JSON.parse(raw)):{...defaultProfile};}
|
||||
catch{return {...defaultProfile};}
|
||||
}
|
||||
function App(){
|
||||
const [profile,setProfile]=useState(load);
|
||||
const [axes,setAxes]=useState<Axes>(emptyAxes);
|
||||
const [open,setOpen]=useState(['settings','preview']);
|
||||
const [saved,setSaved]=useState('');
|
||||
const [light,setLight]=useState(false);
|
||||
const change=(patch:Partial<ControlProfile>)=>{
|
||||
setProfile(parseProfile({...profile,...patch,revision:profile.revision+1}));setAxes(emptyAxes);setSaved('');
|
||||
};
|
||||
const result=mix(profile,axes);
|
||||
const y=profile.mode==='tank'?'leftY':profile.stick==='right'?'rightY':'leftY';
|
||||
const x=profile.mode==='tank'?'rightY':profile.stick==='right'?'rightX':'leftX';
|
||||
const field=(key:keyof Axes,label:string)=><RangeControl label={label} value={axes[key]} min={-1} max={1} step={.01} exactValueBounds={{min:-1,max:1}} formatValue={percent} onChange={value=>setAxes({...axes,[key]:value})}/>;
|
||||
function save(){
|
||||
try{localStorage.setItem(storageKey,JSON.stringify(profile));setSaved('Черновик сохранён в этом браузере.');}
|
||||
catch{setSaved('Браузер не сохранил черновик. Используйте скачивание JSON.');}
|
||||
}
|
||||
function download(){
|
||||
const url=URL.createObjectURL(new Blob([JSON.stringify(profile,null,2)+'\n'],{type:'application/json'}));
|
||||
const a=document.createElement('a');a.href=url;a.download='rover-control-draft.json';a.click();
|
||||
setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}
|
||||
return <main data-nodedc-ui>
|
||||
<header><div><p>MISSION CORE · ПРОТОТИП</p><h1>Настройки управления ровером</h1></div><Button onClick={()=>{setLight(!light);document.documentElement.dataset.nodedcTheme=light?'dark':'light';}}>Тема</Button></header>
|
||||
<p className="notice">Интерактивный макет без подключения к роверу. Все значения ниже — расчёт на экране; кнопки не обращаются к борту и VESC.</p>
|
||||
<Inspector variant="panel" openSections={open} onOpenSectionsChange={setOpen} sections={[
|
||||
{id:'settings',label:'Профиль управления',content:<SettingsCard title="Рычаги и отклик" description="Схема 1×1 / 2×2 и назначения моторов остаются отдельными настройками привода.">
|
||||
<InspectorSelectField label="Управление" value={profile.mode} options={[{value:'tank',label:'Два рычага · Tank'},{value:'arcade',label:'Один рычаг · Arcade'}]} onChange={mode=>change({mode})}/>
|
||||
{profile.mode==='arcade'&&<InspectorSelectField label="Управляющий рычаг" value={profile.stick} options={[{value:'right',label:'Правый'},{value:'left',label:'Левый'}]} onChange={stick=>change({stick})}/>}
|
||||
<p>{profile.mode==='tank'?'Левый рычаг управляет левой стороной, правый — правой.':'Вперёд/назад задаёт движение; влево/вправо — поворот, включая разворот на месте. При движении назад знак поворота корпуса сохраняется.'}</p>
|
||||
<InspectorSelectField label="Отклик рычага" value={profile.response} options={[{value:'linear',label:'Линейный'},{value:'squared',label:'Плавный у центра'}]} onChange={response=>change({response})}/>
|
||||
<RangeControl label="Зона нейтрали" value={profile.deadband} min={0} max={.5} step={.01} exactValueBounds={{min:0,max:.5}} formatValue={percent} onChange={deadband=>change({deadband})}/>
|
||||
<RangeControl label="Масштаб команды" value={profile.outputScale} min={0} max={1} step={.01} exactValueBounds={{min:0,max:1}} formatValue={percent} onChange={outputScale=>change({outputScale})}/>
|
||||
<p>Масштаб команды — относительный отклик рычага. Он не задаёт амперы, ватты или паспортный предел двигателя.</p>
|
||||
<div className="actions"><Button onClick={save}>Сохранить черновик</Button><Button onClick={download}>Скачать JSON</Button></div>
|
||||
{saved&&<p role="status">{saved}</p>}
|
||||
</SettingsCard>},
|
||||
{id:'preview',label:'Проверка профиля на экране',content:<SettingsCard title="Команды сторонам" description="Нормализованная команда от −100% до +100%. Плюс — вперёд по корпусу, минус — назад.">
|
||||
{field(y,profile.mode==='tank'?'Левый рычаг · вперёд / назад':'Движение · вперёд / назад')}
|
||||
{field(x,profile.mode==='tank'?'Правый рычаг · вперёд / назад':'Поворот · влево / вправо')}
|
||||
<div className="actions"><Button onClick={()=>setAxes(emptyAxes)}>Нейтраль</Button><Button onClick={()=>setAxes({...emptyAxes,[y]:1,[x]:profile.mode==='tank'?1:0})}>Вперёд</Button><Button onClick={()=>setAxes({...emptyAxes,[y]:-1,[x]:profile.mode==='tank'?-1:0})}>Назад</Button><Button onClick={()=>setAxes({...emptyAxes,[y]:profile.mode==='tank'?-1:0,[x]:profile.mode==='tank'?1:-1})}>Разворот влево</Button></div>
|
||||
<div className="demands" aria-live="polite">{(['left','right'] as const).map(side=><div key={side}><span>{side==='left'?'Левая сторона':'Правая сторона'}</span><strong>{percent(result[side])}</strong><span>{result[side]===0?'Нейтраль':result[side]>0?'Вперёд':'Назад'}</span></div>)}</div>
|
||||
<p>Команда стороны распространяется на все назначенные ей моторы: два, четыре, шесть и более. Связь — по UUID, а направление проверяется отдельно для каждого мотора.</p>
|
||||
</SettingsCard>},
|
||||
{id:'takeover',label:'Перехват пультом · проверка сценария',content:<SettingsCard title="Стоп → нейтраль → ручное управление" description="Расчётная модель. Существующая прошивка и проводка пока не обеспечивают этот сценарий при отказе Mini.">
|
||||
<div className="trace">{trace(profile).map(({label,decision},i)=><div className="trace-row" key={label}><span>{i+1}. {label}</span><StatusBadge tone={decision.stopAll?'warning':'neutral'}>{states[decision.state]}</StatusBadge><span>{percent(decision.demand.left)} / {percent(decision.demand.right)}</span></div>)}</div>
|
||||
<p>Первый жест отменяет допуск и очередь Mission Core. Новый допуск требует явного действия: нейтраль и восстановление связи не возобновляют автономную задачу.</p>
|
||||
</SettingsCard>},
|
||||
]}/>
|
||||
</main>;
|
||||
}
|
||||
document.documentElement.dataset.nodedcTheme='dark';
|
||||
createRoot(document.getElementById('root')!).render(<App/>);
|
||||
@@ -0,0 +1,16 @@
|
||||
/* Domain composition only; all controls come from the Design Guideline. */
|
||||
body { margin:0; background:var(--nodedc-canvas); color:var(--nodedc-text-primary); font-family:var(--nodedc-font-family); font-size:var(--nodedc-font-size-md); }
|
||||
main { max-width:960px; margin:0 auto; padding:32px 24px 64px; }
|
||||
main>header { display:flex; align-items:center; justify-content:space-between; gap:24px; margin-bottom:24px; }
|
||||
h1 { font-size:var(--nodedc-font-size-title); font-weight:600; margin:8px 0; }
|
||||
p { font-size:var(--nodedc-font-size-sm); line-height:1.6; color:var(--nodedc-text-secondary); }
|
||||
main>header p { font-size:var(--nodedc-font-size-xs); }
|
||||
.notice { margin-bottom:24px; }
|
||||
.actions { display:flex; flex-wrap:wrap; gap:12px; margin:16px 0; }
|
||||
.demands { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:24px; margin:24px 0; }
|
||||
.demands>div { display:flex; flex-direction:column; gap:8px; }
|
||||
.demands strong { font-size:var(--nodedc-font-size-lg); font-variant-numeric:tabular-nums; }
|
||||
.demands span { font-size:var(--nodedc-font-size-sm); }
|
||||
.trace { display:grid; gap:20px; }
|
||||
.trace-row { display:grid; grid-template-columns:minmax(0,1fr) 250px 100px; align-items:center; gap:16px; font-size:var(--nodedc-font-size-sm); }
|
||||
@media (max-width:720px) { main {padding:20px 12px 40px;} .trace-row {grid-template-columns:1fr;} }
|
||||
@@ -0,0 +1,38 @@
|
||||
import {AuthorityModel, type Decision} from '../../../../packages/rover-control/src/authority';
|
||||
import {type ControlProfile} from '../../../../packages/rover-control/src/profile';
|
||||
|
||||
/** Synthetic event replay, with no wall clock, I/O, timers or hardware adapter. */
|
||||
export function trace(profile: ControlProfile): {label: string; decision: Decision}[] {
|
||||
const model = new AuthorityModel(profile, ['left', 'right'], {
|
||||
maxAgeMs:100, neutralMs:200, maxCommandMs:100, monitoredAxes:['leftY','rightY','leftX','rightX'],
|
||||
}, 'preview');
|
||||
const rows: {label:string;decision:Decision}[] = [];
|
||||
let now = -50, token = '';
|
||||
function step(value=0, link: 'live'|'lost'='live', core=false, request=false) {
|
||||
now+=50;
|
||||
const axes = {leftY:0,rightY:0,leftX:0,rightX:0};
|
||||
axes[profile.mode==='tank'?'leftY':profile.stick==='left'?'leftY':'rightY']=value;
|
||||
return model.step({now, link:{state:link,at:now},
|
||||
axes:Object.fromEntries(Object.entries(axes).map(([key,v])=>[key,{value:v,at:now,sequence:now}])),
|
||||
drives:{left:{healthy:true,stopped:value===0,at:now},right:{healthy:true,stopped:value===0,at:now}},
|
||||
requestCore:request?{owner:'autonomy',at:now,sequence:1}:undefined,
|
||||
command:core?{token,at:now,expires:now+75,sequence:now,demand:{left:.4,right:.4}}:undefined,
|
||||
});
|
||||
}
|
||||
const add=(label:string,decision:Decision)=>rows.push({label,decision});
|
||||
for(let i=0;i<5;i++)step();
|
||||
const grant=step(0,'live',false,true);token=grant.token??'';
|
||||
add('Mission Core получил явный допуск',grant);
|
||||
add('Автономная команда движения',step(0,'live',true));
|
||||
add('Первое отклонение рычага',step(.8,'live',true));
|
||||
for(let i=0;i<20;i++)step(.8);
|
||||
add('Тот же рычаг удерживается',step(.8));
|
||||
add('Остановка подтверждена, оба рычага отпущены',step());
|
||||
for(let i=0;i<3;i++)step();
|
||||
add('Непрерывная нейтраль подтверждена',step());
|
||||
add('Второе отклонение — ручное движение',step(.8));
|
||||
add('Запоздавшая команда прежней задачи',step(.8,'live',true));
|
||||
add('Радиосвязь потеряна',step(0,'lost'));
|
||||
add('Связь вернулась с отклонённым рычагом',step(.8));
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends":"../../tsconfig.app.json",
|
||||
"compilerOptions":{"incremental":false,"tsBuildInfoFile":null},
|
||||
"include":["*.tsx","*.ts","../../../../packages/rover-control/src/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const boardLayoutSchema = "missioncore.board-layout/v1"
|
||||
|
||||
var boardSectionIDs = []string{"computer", "settings", "devices"}
|
||||
|
||||
type BoardLayout struct {
|
||||
Schema string `json:"schema"`
|
||||
Revision int64 `json:"revision"`
|
||||
OpenSections []string `json:"open_sections"`
|
||||
}
|
||||
|
||||
func validBoardSection(id string) bool {
|
||||
for _, section := range boardSectionIDs {
|
||||
if id == section {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PresentationStore) readBoardLayout() (BoardLayout, error) {
|
||||
value := BoardLayout{Schema: boardLayoutSchema, OpenSections: append([]string{}, boardSectionIDs...)}
|
||||
file, err := os.Open(filepath.Join(p.dir, "board-layout.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return value, nil
|
||||
}
|
||||
if err != nil {
|
||||
return BoardLayout{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
d := json.NewDecoder(io.LimitReader(file, 4097))
|
||||
d.DisallowUnknownFields()
|
||||
value = BoardLayout{}
|
||||
if d.Decode(&value) != nil || d.Decode(new(any)) != io.EOF || value.Schema != boardLayoutSchema || value.Revision < 0 || value.Revision >= 1<<53-1 || value.OpenSections == nil {
|
||||
return BoardLayout{}, errors.New("invalid board layout")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range value.OpenSections {
|
||||
if !validBoardSection(id) || seen[id] {
|
||||
return BoardLayout{}, errors.New("invalid board section")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (p *PresentationStore) saveBoardLayout(value BoardLayout) error {
|
||||
data, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(p.dir, ".board-layout-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
if _, err = file.Write(append(data, '\n')); err == nil {
|
||||
err = file.Sync()
|
||||
}
|
||||
closeErr := file.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if err = os.Rename(file.Name(), filepath.Join(p.dir, "board-layout.json")); err != nil {
|
||||
return err
|
||||
}
|
||||
dir, err := os.Open(p.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
return dir.Sync()
|
||||
}
|
||||
|
||||
func (s *Server) boardLayoutRoutes(mux *http.ServeMux) {
|
||||
p := s.Presentation
|
||||
mux.HandleFunc("GET /api/presentation/board-layout", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
value, err := p.readBoardLayout()
|
||||
if err != nil {
|
||||
reply(w, 500, map[string]string{"error": "Не удалось прочитать раскладку борта"})
|
||||
return
|
||||
}
|
||||
reply(w, 200, value)
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/presentation/board-layout", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Content-Type") != "application/json" {
|
||||
reply(w, 415, map[string]string{"error": "Ожидался JSON"})
|
||||
return
|
||||
}
|
||||
var change struct {
|
||||
Section string `json:"section"`
|
||||
Open *bool `json:"open"`
|
||||
}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&change) != nil || d.Decode(new(any)) != io.EOF || change.Open == nil || !validBoardSection(change.Section) {
|
||||
reply(w, 400, map[string]string{"error": "Некорректная раскладка борта"})
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
value, err := p.readBoardLayout()
|
||||
if err != nil {
|
||||
reply(w, 500, map[string]string{"error": "Не удалось прочитать раскладку борта"})
|
||||
return
|
||||
}
|
||||
next := []string{}
|
||||
for _, id := range boardSectionIDs {
|
||||
open := false
|
||||
for _, saved := range value.OpenSections {
|
||||
if saved == id {
|
||||
open = true
|
||||
}
|
||||
}
|
||||
if id == change.Section {
|
||||
open = *change.Open
|
||||
}
|
||||
if open {
|
||||
next = append(next, id)
|
||||
}
|
||||
}
|
||||
value.OpenSections = next
|
||||
value.Revision++
|
||||
if p.saveBoardLayout(value) != nil {
|
||||
reply(w, 500, map[string]string{"error": "Не удалось сохранить раскладку борта"})
|
||||
return
|
||||
}
|
||||
reply(w, 200, value)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBoardLayoutPersistsEmptyAndConcurrentSectionChanges(t *testing.T) {
|
||||
s, cookie := presentationServer(t)
|
||||
var wg sync.WaitGroup
|
||||
for _, id := range boardSectionIDs {
|
||||
wg.Add(1)
|
||||
go func(id string) {
|
||||
defer wg.Done()
|
||||
w := call(s, "PATCH", "/api/presentation/board-layout", `{"section":"`+id+`","open":false}`, cookie)
|
||||
if w.Code != 200 {
|
||||
t.Error(w.Code, w.Body.String())
|
||||
}
|
||||
}(id)
|
||||
}
|
||||
wg.Wait()
|
||||
value, err := NewPresentationStore(s.Presentation.dir).readBoardLayout()
|
||||
if err != nil || value.Revision != 3 || len(value.OpenSections) != 0 || value.OpenSections == nil {
|
||||
t.Fatal(value, err)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(s.Presentation.dir, "board-layout.json"))
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
if w := call(s, "GET", "/api/presentation/board-layout", "", nil); w.Code != 401 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBoardLayoutRejectsInvalidAndPreservesCorruptFile(t *testing.T) {
|
||||
s, cookie := presentationServer(t)
|
||||
for _, body := range []string{`{"section":"motor","open":true}`, `{"section":"computer"}`, `{"section":"computer","open":"true"}`, `{"section":"computer","open":true,"extra":0}`} {
|
||||
if w := call(s, "PATCH", "/api/presentation/board-layout", body, cookie); w.Code != 400 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
path := filepath.Join(s.Presentation.dir, "board-layout.json")
|
||||
raw := []byte(`{"schema":"missioncore.board-layout/v1","revision":0,"open_sections":["motor"]}`)
|
||||
if err := os.WriteFile(path, raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := call(s, "PATCH", "/api/presentation/board-layout", `{"section":"computer","open":false}`, cookie); w.Code != 500 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
got, _ := os.ReadFile(path)
|
||||
if string(got) != string(raw) {
|
||||
t.Fatal("Corrupt file replaced")
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"schema": "missioncore.node.environment/v1",
|
||||
"revision": "ubuntu-24.04-amd64/2",
|
||||
"revision": "ubuntu-24.04-amd64/3",
|
||||
"steps": [
|
||||
{"id":"platform","label":"Проверка системы","description":"Операционная система и архитектура БК","requires":[]},
|
||||
{"id":"packages","label":"Установка системных пакетов","description":"OpenSSH Server и зависимости окружения","requires":["platform"]},
|
||||
{"id":"node-service","label":"Настройка службы БК","description":"Автозапуск и доступ к системной инвентаризации","requires":["platform"]},
|
||||
{"id":"desktop-autostart","label":"Автозапуск приложения","description":"Открытие окна при входе в рабочий стол","requires":["node-service"]},
|
||||
{"id":"usb-startup","label":"Обнаружение устройств при загрузке","description":"Автоматическое восстановление незавершённого подключения USB","requires":["platform"]},
|
||||
{"id":"network-inventory","label":"Получение сетевых настроек","description":"Интерфейсы и назначенные адреса","requires":["node-service"]},
|
||||
{"id":"usb-inventory","label":"Получение USB-устройств","description":"Оборудование, обнаруженное операционной системой","requires":["node-service"]},
|
||||
{"id":"ssh-service","label":"Настройка SSH","description":"Запуск сервера и подключение реестра доверенных ключей","requires":["packages","node-service"]},
|
||||
|
||||
@@ -152,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
|
||||
|
||||
func (p *Pairing) Run(ctx context.Context) {
|
||||
go p.channel(ctx)
|
||||
go p.roverChannel(ctx)
|
||||
var server *http.Server
|
||||
endpoint := ""
|
||||
serverIdentity := ""
|
||||
@@ -307,6 +308,9 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
payload["devices"] = inv["items"]
|
||||
payload["sensor_state"] = inv
|
||||
payload["sensor_results"] = p.Sensors.RemoteResults()
|
||||
if batch := p.Sensors.ConfigurationBatch(binding.BindingID); batch != nil {
|
||||
payload["vesc_configurations"] = batch
|
||||
}
|
||||
}
|
||||
if p.DeviceEnrollment != nil {
|
||||
payload["device_enrollment"] = p.DeviceEnrollment.Status()
|
||||
@@ -337,6 +341,7 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
if p.Sensors != nil {
|
||||
p.Sensors.AcknowledgeConfigurations(binding.BindingID, result["vesc_configurations_ack"], payload["vesc_configurations"])
|
||||
var ack []string
|
||||
if json.Unmarshal(result["sensor_acknowledgements"], &ack) == nil {
|
||||
p.Sensors.Acknowledge(ack)
|
||||
|
||||
@@ -182,6 +182,7 @@ func (p *PresentationStore) save(value PresentationSettings) error {
|
||||
}
|
||||
|
||||
func (s *Server) presentationRoutes(mux *http.ServeMux) {
|
||||
s.boardLayoutRoutes(mux)
|
||||
p := s.Presentation
|
||||
mux.HandleFunc("GET /api/presentation/settings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package node
|
||||
|
||||
// Commands stream independently of telemetry. Only the local 20 Hz loop may
|
||||
// deliver the latest unexpired intent to the single VESC owner.
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *Pairing) roverBinding() *CoreBinding {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.state.Phase != "paired" || p.state.Binding == nil {
|
||||
return nil
|
||||
}
|
||||
b := *p.state.Binding
|
||||
return &b
|
||||
}
|
||||
func sameRoverBinding(a, b *CoreBinding) bool {
|
||||
return a != nil && b != nil && a.BindingID == b.BindingID && a.Endpoint == b.Endpoint && a.ClientPEM == b.ClientPEM && a.EndpointRevision == b.EndpointRevision
|
||||
}
|
||||
func roverWait(ctx context.Context, delay time.Duration) bool {
|
||||
if delay < 0 {
|
||||
delay = 0
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-time.After(delay):
|
||||
return true
|
||||
}
|
||||
}
|
||||
func (p *Pairing) roverChannel(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
binding := p.roverBinding()
|
||||
if binding != nil && p.Sensors != nil {
|
||||
p.runRoverChannel(ctx, *binding)
|
||||
}
|
||||
if !roverWait(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
config, err := bindingTLS(b, p.store.pairingKey())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
transport := func() *http.Transport {
|
||||
return &http.Transport{TLSClientConfig: config, Proxy: nil,
|
||||
MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second,
|
||||
TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second,
|
||||
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext}
|
||||
}
|
||||
telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }}
|
||||
stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
|
||||
defer telemetry.CloseIdleConnections()
|
||||
defer stream.CloseIdleConnections()
|
||||
random := make([]byte, 16)
|
||||
if _, err = rand.Read(random); err != nil {
|
||||
return
|
||||
}
|
||||
relay := hex.EncodeToString(random)
|
||||
id, _ := p.store.Public()
|
||||
base := map[string]any{"schema": PairSchema, "node_id": id, "binding_id": b.BindingID,
|
||||
"core_endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision, "relay_id": relay}
|
||||
state := newRoverStreamState(time.Now())
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
var workers sync.WaitGroup
|
||||
defer func() { cancel(); workers.Wait() }()
|
||||
workers.Add(2)
|
||||
go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }()
|
||||
var model *sensorModel
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
model = &sensorModels[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if model == nil {
|
||||
return
|
||||
}
|
||||
var diagnostic roverDiagnostics
|
||||
for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) {
|
||||
select {
|
||||
case <-state.wake:
|
||||
default:
|
||||
}
|
||||
started := time.Now()
|
||||
watch, command, stop := state.delivery(started)
|
||||
frame := roverFrame{}
|
||||
if command != nil {
|
||||
frame.Session, _ = command["id"].(string)
|
||||
frame.Sequence, _ = command["sequence"].(float64)
|
||||
frame.TTLMS, _ = command["ttl_ms"].(float64)
|
||||
}
|
||||
call, done := context.WithTimeout(ctx, 25*time.Millisecond)
|
||||
result, driverErr := p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay})
|
||||
done()
|
||||
frame.DriverMS = time.Since(started).Milliseconds()
|
||||
if driverErr != nil {
|
||||
state.stopStream()
|
||||
frame.Stage = "driver_transport"
|
||||
state.delivered(map[string]any{}, 0)
|
||||
} else {
|
||||
state.delivered(result, stop)
|
||||
frame.State, _ = result["state"].(string)
|
||||
}
|
||||
diagnostic.record(started, frame)
|
||||
// New intent and stop signals bypass the periodic watchdog tick. The
|
||||
// buffered wake channel coalesces arrivals; it never queues commands.
|
||||
timer := time.NewTimer(max(0, 50*time.Millisecond-time.Since(started)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-state.wake:
|
||||
case <-timer.C:
|
||||
}
|
||||
timer.Stop()
|
||||
}
|
||||
// Binding changes and channel shutdown explicitly retire any current intent.
|
||||
call, done := context.WithTimeout(context.Background(), 25*time.Millisecond)
|
||||
_, _ = p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": false, "command": nil, "relay_id": relay})
|
||||
done()
|
||||
}
|
||||
func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
var diagnostic roverDiagnostics
|
||||
for ctx.Err() == nil {
|
||||
started := time.Now()
|
||||
snapshot, _ := state.view()
|
||||
payload := make(map[string]any, len(base)+1)
|
||||
for k, v := range base {
|
||||
payload[k] = v
|
||||
}
|
||||
payload["rover"] = snapshot
|
||||
raw, _ := json.Marshal(payload)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
frame := roverFrame{}
|
||||
frame.State, _ = snapshot["state"].(string)
|
||||
if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" {
|
||||
frame.Session, _ = snapshot["session_id"].(string)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
frame.Stage = "telemetry_transport"
|
||||
} else {
|
||||
frame.Status = response.StatusCode
|
||||
var out roverStreamReply
|
||||
readErr := json.NewDecoder(io.LimitReader(response.Body, 32768)).Decode(&out)
|
||||
response.Body.Close()
|
||||
if readErr != nil || response.StatusCode != 200 {
|
||||
frame.Stage = "telemetry_response"
|
||||
} else if !state.sampleClock(out.Clock, started, time.Now()) {
|
||||
frame.Stage = "clock_invalid"
|
||||
state.stopStream()
|
||||
} else {
|
||||
state.setWatch(out.Watch)
|
||||
}
|
||||
}
|
||||
frame.CoreMS = time.Since(started).Milliseconds()
|
||||
diagnostic.record(started, frame)
|
||||
_, watch := state.view()
|
||||
delay := 500 * time.Millisecond
|
||||
if watch {
|
||||
delay = 100 * time.Millisecond
|
||||
}
|
||||
if !roverWait(ctx, delay-time.Since(started)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
for ctx.Err() == nil {
|
||||
_, watch := state.view()
|
||||
if !watch {
|
||||
if !roverWait(ctx, 50*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
err := roverReadStream(ctx, client, endpoint, base, state)
|
||||
state.stopStream()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\"}")
|
||||
}
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func roverReadStream(parent context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) error {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
raw, _ := json.Marshal(base)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-stream", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
sent := time.Now()
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != 200 {
|
||||
return errors.New("stream rejected")
|
||||
}
|
||||
// The native 200 ms output watchdog is unchanged. A silent stream also
|
||||
// cancels its network read and retires intent; reconnect never rearms it.
|
||||
guard := time.AfterFunc(350*time.Millisecond, cancel)
|
||||
defer guard.Stop()
|
||||
reader := bufio.NewReaderSize(response.Body, 32768)
|
||||
first := true
|
||||
for {
|
||||
line, err := reader.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var out roverStreamReply
|
||||
if json.Unmarshal(line, &out) != nil {
|
||||
return errors.New("invalid command frame")
|
||||
}
|
||||
if first {
|
||||
if !state.sampleClock(out.Clock, sent, time.Now()) {
|
||||
return errors.New("invalid stream clock")
|
||||
}
|
||||
first = false
|
||||
}
|
||||
if !state.accept(out) {
|
||||
return errors.New("invalid stream intent")
|
||||
}
|
||||
if !out.Watch {
|
||||
return nil
|
||||
}
|
||||
if !guard.Reset(350 * time.Millisecond) {
|
||||
return errors.New("stream deadline")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package node
|
||||
|
||||
// A bounded memory flight recorder. It never stores endpoints, certificates,
|
||||
// payloads or raw HTTP errors, and never changes admission or lease deadlines.
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roverFrame struct {
|
||||
AtMS int64 `json:"at_ms"`
|
||||
GapMS int64 `json:"gap_ms"`
|
||||
BindingMS int64 `json:"binding_ms"`
|
||||
CoreMS int64 `json:"core_ms"`
|
||||
DriverMS int64 `json:"driver_ms"`
|
||||
Status int `json:"http_status"`
|
||||
Stage string `json:"error_stage,omitempty"`
|
||||
Session string `json:"session,omitempty"`
|
||||
Sequence float64 `json:"sequence"`
|
||||
TTLMS float64 `json:"ttl_ms"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type roverDiagnostics struct {
|
||||
frames []roverFrame
|
||||
last time.Time
|
||||
started time.Time
|
||||
state string
|
||||
session string
|
||||
emit func([]byte)
|
||||
}
|
||||
|
||||
func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
|
||||
if d.started.IsZero() {
|
||||
d.started = at
|
||||
}
|
||||
frame.AtMS = at.Sub(d.started).Milliseconds()
|
||||
if !d.last.IsZero() {
|
||||
frame.GapMS = at.Sub(d.last).Milliseconds()
|
||||
}
|
||||
d.last = at
|
||||
d.frames = append(d.frames, frame)
|
||||
if len(d.frames) > 128 {
|
||||
d.frames = d.frames[len(d.frames)-128:]
|
||||
}
|
||||
active := frame.Session != "" || d.session != ""
|
||||
changed := frame.State != d.state || frame.Session != d.session
|
||||
if active && (changed || frame.Stage != "" || frame.GapMS >= 200) {
|
||||
raw, _ := json.Marshal(struct {
|
||||
Event string `json:"event"`
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}{"rover-channel", d.frames})
|
||||
if d.emit != nil {
|
||||
d.emit(raw)
|
||||
} else {
|
||||
log.Printf("%s", raw)
|
||||
}
|
||||
}
|
||||
d.state, d.session = frame.State, frame.Session
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverDiagnosticsRetainsCancellationCauseWithoutIdleLogSpam(t *testing.T) {
|
||||
var events [][]byte
|
||||
d := roverDiagnostics{emit: func(b []byte) { events = append(events, b) }}
|
||||
at := time.Unix(100, 0)
|
||||
for i := 0; i < 200; i++ {
|
||||
d.record(at.Add(time.Duration(i)*50*time.Millisecond), roverFrame{State: "observing"})
|
||||
}
|
||||
if len(events) != 0 || len(d.frames) != 128 {
|
||||
t.Fatal("idle must remain bounded and quiet")
|
||||
}
|
||||
at = at.Add(11 * time.Second)
|
||||
d.record(at, roverFrame{Session: "session", Sequence: 1, TTLMS: 350, State: "preparing"})
|
||||
d.record(at.Add(100*time.Millisecond), roverFrame{Session: "session", Sequence: 2, TTLMS: 320, State: "preparing"})
|
||||
if len(events) != 1 {
|
||||
t.Fatal("unchanged healthy frames should remain in memory")
|
||||
}
|
||||
d.record(at.Add(450*time.Millisecond), roverFrame{CoreMS: 300, Stage: "core_transport", State: "preparing"})
|
||||
if len(events) != 2 {
|
||||
t.Fatal("lost command needs diagnostic evidence")
|
||||
}
|
||||
var event struct {
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}
|
||||
if err := json.Unmarshal(events[1], &event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := event.Frames[len(event.Frames)-1]
|
||||
if last.Stage != "core_transport" || last.GapMS != 350 || last.CoreMS != 300 || last.Session != "" {
|
||||
t.Fatal(last)
|
||||
}
|
||||
if event.Frames[len(event.Frames)-2].Sequence != 2 {
|
||||
t.Fatal("last accepted frame lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverDiagnosticsRecordsBindingWaitAndDriverTerminalState(t *testing.T) {
|
||||
var events [][]byte
|
||||
d := roverDiagnostics{emit: func(b []byte) { events = append(events, b) }}
|
||||
at := time.Unix(100, 0)
|
||||
d.record(at, roverFrame{Session: "session", State: "preparing"})
|
||||
d.record(at.Add(500*time.Millisecond), roverFrame{Session: "session", State: "stopped", BindingMS: 400, DriverMS: 2})
|
||||
if len(events) != 2 {
|
||||
t.Fatal("terminal state must flush preceding transport history")
|
||||
}
|
||||
var event struct {
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}
|
||||
if err := json.Unmarshal(events[1], &event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := event.Frames[len(event.Frames)-1]
|
||||
if last.BindingMS != 400 || last.DriverMS != 2 || last.State != "stopped" {
|
||||
t.Fatal(last)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roverClock struct {
|
||||
Instance string `json:"instance"`
|
||||
MonotonicMS float64 `json:"monotonic_ms"`
|
||||
}
|
||||
type roverStreamReply struct {
|
||||
Watch bool `json:"watch"`
|
||||
Command map[string]any `json:"command"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
}
|
||||
|
||||
// Clock bounds use the request-send time, never RTT/2 or synchronized wall
|
||||
// clocks. Server time was sampled after that send, so it gives an upper bound
|
||||
// on server-minus-local monotonic offset even on an asymmetric network.
|
||||
type roverStreamState struct {
|
||||
mu sync.Mutex
|
||||
origin time.Time
|
||||
clockID string
|
||||
upperMS float64
|
||||
anchored time.Time
|
||||
clockSeen time.Time
|
||||
command map[string]any
|
||||
watch bool
|
||||
stopPending bool
|
||||
stopRevision uint64
|
||||
snapshot map[string]any
|
||||
retired map[string]bool
|
||||
inhibited bool
|
||||
wake chan struct{}
|
||||
}
|
||||
|
||||
func newRoverStreamState(now time.Time) *roverStreamState {
|
||||
return &roverStreamState{origin: now, stopPending: true, stopRevision: 1, snapshot: map[string]any{}, retired: map[string]bool{}, wake: make(chan struct{}, 1)}
|
||||
}
|
||||
func finiteNumber(v any) (float64, bool) {
|
||||
n, ok := v.(float64)
|
||||
return n, ok && !math.IsNaN(n) && !math.IsInf(n, 0)
|
||||
}
|
||||
func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) bool {
|
||||
if len(c.Instance) != 32 {
|
||||
return false
|
||||
}
|
||||
if _, err := hex.DecodeString(c.Instance); err != nil {
|
||||
return false
|
||||
}
|
||||
if math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 || received.Before(sent) {
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
upper := c.MonotonicMS - float64(sent.Sub(s.origin).Microseconds())/1000 + 1
|
||||
if c.Instance != s.clockID {
|
||||
s.invalidate()
|
||||
s.clockID = c.Instance
|
||||
s.upperMS = upper
|
||||
s.anchored = received
|
||||
} else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 {
|
||||
s.upperMS = upper
|
||||
s.anchored = received
|
||||
}
|
||||
s.clockSeen = received
|
||||
return true
|
||||
}
|
||||
func (s *roverStreamState) accept(reply roverStreamReply) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if reply.Clock.Instance != s.clockID || s.clockID == "" {
|
||||
return false
|
||||
}
|
||||
if reply.Command == nil {
|
||||
if s.command != nil {
|
||||
s.invalidate()
|
||||
}
|
||||
return true
|
||||
}
|
||||
command := reply.Command
|
||||
if len(command) != 6 {
|
||||
return false
|
||||
}
|
||||
for _, k := range []string{"id", "sequence", "left", "right", "settings", "expires_mono_ms"} {
|
||||
if _, ok := command[k]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
expires, ok := finiteNumber(command["expires_mono_ms"])
|
||||
if !ok || expires > reply.Clock.MonotonicMS+400.001 {
|
||||
return false
|
||||
}
|
||||
id, ok := command["id"].(string)
|
||||
if !ok || len(id) != 32 {
|
||||
return false
|
||||
}
|
||||
if _, err := hex.DecodeString(id); err != nil {
|
||||
return false
|
||||
}
|
||||
sequence, ok := finiteNumber(command["sequence"])
|
||||
if !ok || sequence < 0 || sequence >= 1<<53 || math.Trunc(sequence) != sequence {
|
||||
return false
|
||||
}
|
||||
if s.inhibited || s.retired[id] {
|
||||
return true
|
||||
}
|
||||
// The native driver independently validates identity, settings and sequence.
|
||||
if s.stopPending {
|
||||
s.retire(id)
|
||||
return true
|
||||
}
|
||||
changed := s.command == nil || s.command["id"] != id || s.command["sequence"] != sequence
|
||||
s.command = command
|
||||
if changed {
|
||||
s.notify()
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (s *roverStreamState) notify() {
|
||||
select {
|
||||
case s.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
func (s *roverStreamState) stopStream() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.invalidate()
|
||||
}
|
||||
func (s *roverStreamState) retire(id string) {
|
||||
if len(s.retired) >= 1024 {
|
||||
s.inhibited = true // Fail closed instead of forgetting interrupted sessions.
|
||||
return
|
||||
}
|
||||
s.retired[id] = true
|
||||
}
|
||||
func (s *roverStreamState) invalidate() {
|
||||
wake := !s.stopPending || s.command != nil
|
||||
if s.command != nil {
|
||||
if id, ok := s.command["id"].(string); ok {
|
||||
s.retire(id)
|
||||
}
|
||||
}
|
||||
s.command = nil
|
||||
s.stopPending = true
|
||||
s.stopRevision++
|
||||
if wake {
|
||||
s.notify()
|
||||
}
|
||||
}
|
||||
func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.stopPending {
|
||||
return s.watch, nil, s.stopRevision
|
||||
}
|
||||
if s.command == nil {
|
||||
return s.watch, nil, 0
|
||||
}
|
||||
if now.Sub(s.clockSeen) > 2*time.Second {
|
||||
s.invalidate()
|
||||
return s.watch, nil, s.stopRevision
|
||||
}
|
||||
expires, _ := finiteNumber(s.command["expires_mono_ms"])
|
||||
// Reserve 25 ms for the private driver RPC and 5 ms plus 1000 ppm for clock
|
||||
// quantization/rate uncertainty. Expiry is never extended by receipt time.
|
||||
serverUpper := float64(now.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(now.Sub(s.anchored).Microseconds())/1e6
|
||||
ttl := math.Min(400, expires-serverUpper-25)
|
||||
if ttl <= 0 {
|
||||
s.invalidate()
|
||||
return s.watch, nil, s.stopRevision
|
||||
}
|
||||
out := make(map[string]any, 6)
|
||||
for k, v := range s.command {
|
||||
if k != "expires_mono_ms" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
out["ttl_ms"] = ttl
|
||||
return s.watch, out, 0
|
||||
}
|
||||
func (s *roverStreamState) delivered(snapshot map[string]any, stop uint64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.snapshot = snapshot
|
||||
if stop != 0 && stop == s.stopRevision {
|
||||
s.stopPending = false
|
||||
}
|
||||
}
|
||||
func (s *roverStreamState) view() (map[string]any, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.snapshot, s.watch
|
||||
}
|
||||
func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() }
|
||||
@@ -0,0 +1,235 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testClockID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
|
||||
func streamIntent(sequence int, serverNow, expires float64) roverStreamReply {
|
||||
return roverStreamReply{Watch: true, Clock: roverClock{testClockID, serverNow}, Command: map[string]any{
|
||||
"id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "sequence": float64(sequence), "left": float64(1), "right": float64(1),
|
||||
"settings": map[string]any{"standstill_confirmed": true, "current_a": float64(30), "max_erpm": float64(2000)}, "expires_mono_ms": expires}}
|
||||
}
|
||||
func acknowledgeStop(s *roverStreamState, at time.Time) {
|
||||
_, _, revision := s.delivery(at)
|
||||
s.delivered(map[string]any{"state": "observing"}, revision)
|
||||
}
|
||||
func TestRoverStreamAsymmetricDelayRetainsOriginalExpiry(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
// Core's clock is +10 seconds. Request took 70 ms outbound and 130 ms
|
||||
// inbound: dividing RTT in half would be incorrect on this connection.
|
||||
if !s.sampleClock(roverClock{testClockID, 10070}, origin, origin.Add(200*time.Millisecond)) {
|
||||
t.Fatal("clock")
|
||||
}
|
||||
acknowledgeStop(s, origin.Add(200*time.Millisecond))
|
||||
frame := streamIntent(1, 10200, 10600)
|
||||
if !s.accept(frame) {
|
||||
t.Fatal("intent")
|
||||
}
|
||||
_, command, _ := s.delivery(origin.Add(280 * time.Millisecond))
|
||||
if command == nil {
|
||||
t.Fatal("fresh streamed intent rejected")
|
||||
}
|
||||
ttl := command["ttl_ms"].(float64)
|
||||
if ttl <= 0 || 280+ttl > 600 {
|
||||
t.Fatal("delay extended original browser deadline", ttl)
|
||||
}
|
||||
// Replaying the same frame does not receive a new deadline.
|
||||
if !s.accept(frame) {
|
||||
t.Fatal("repeat")
|
||||
}
|
||||
_, late, _ := s.delivery(origin.Add(650 * time.Millisecond))
|
||||
if late != nil {
|
||||
t.Fatal("expired frame revived motor intent")
|
||||
}
|
||||
}
|
||||
func TestRoverStreamContinuousInputSurvivesMeasuredRelayJitter(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10050}, origin, origin.Add(150*time.Millisecond))
|
||||
acknowledgeStop(s, origin.Add(150*time.Millisecond))
|
||||
priorUntil := float64(0)
|
||||
for i, delay := range []int{60, 90, 45, 110, 80, 50, 100, 60, 90, 50} {
|
||||
sent := 200 + i*100
|
||||
arrival := sent + delay
|
||||
s.accept(streamIntent(i+1, float64(10000+sent), float64(10400+sent)))
|
||||
if i > 0 && float64(arrival) >= priorUntil {
|
||||
t.Fatal("lease gap under measured jitter", i, arrival, priorUntil)
|
||||
}
|
||||
_, command, _ := s.delivery(origin.Add(time.Duration(arrival) * time.Millisecond))
|
||||
if command == nil {
|
||||
t.Fatal("fresh command lost", i)
|
||||
}
|
||||
priorUntil = float64(arrival) + command["ttl_ms"].(float64)
|
||||
if priorUntil > float64(sent+400) {
|
||||
t.Fatal("end-to-end deadline expanded")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRoverStreamDisconnectNeedsAcknowledgedStopBeforeNewFrames(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
s.accept(streamIntent(1, 10000, 10400))
|
||||
s.stopStream()
|
||||
_, _, oldStop := s.delivery(origin)
|
||||
s.stopStream() // Another disconnect races the local driver's response.
|
||||
s.delivered(map[string]any{}, oldStop)
|
||||
s.accept(streamIntent(2, 10000, 10400))
|
||||
_, command, newStop := s.delivery(origin)
|
||||
if command != nil || newStop == 0 || newStop == oldStop {
|
||||
t.Fatal("stale ACK removed stop barrier")
|
||||
}
|
||||
s.delivered(map[string]any{}, newStop)
|
||||
_, command, _ = s.delivery(origin)
|
||||
if command != nil {
|
||||
t.Fatal("frame received before acknowledged stop was queued")
|
||||
}
|
||||
}
|
||||
func TestRoverStreamClockChangeAndStaleClockDisarm(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
s.accept(streamIntent(1, 10000, 10400))
|
||||
s.sampleClock(roverClock{"cccccccccccccccccccccccccccccccc", 2}, origin, origin)
|
||||
_, command, stop := s.delivery(origin)
|
||||
if command != nil || stop == 0 {
|
||||
t.Fatal("Core restart retained intent")
|
||||
}
|
||||
if s.accept(streamIntent(2, 10000, 10400)) {
|
||||
t.Fatal("old clock accepted")
|
||||
}
|
||||
acknowledgeStop(s, origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
// A fresh-looking frame alone cannot renew the clock calibration.
|
||||
fresh := streamIntent(3, 13000, 13400)
|
||||
fresh.Command["id"] = "dddddddddddddddddddddddddddddddd"
|
||||
s.accept(fresh)
|
||||
_, command, stop = s.delivery(origin.Add(3 * time.Second))
|
||||
if command != nil || stop == 0 {
|
||||
t.Fatal("stale clock allowed output")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverStreamUnsentIntentCannotStartAfterReconnect(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
frame := streamIntent(1, 10000, 10400)
|
||||
s.accept(frame)
|
||||
// The network fails before the local driver ever sees this session.
|
||||
s.stopStream()
|
||||
acknowledgeStop(s, origin)
|
||||
s.accept(streamIntent(2, 10010, 10410))
|
||||
_, command, _ := s.delivery(origin)
|
||||
if command != nil {
|
||||
t.Fatal("undelivered old session started after reconnect")
|
||||
}
|
||||
frame.Command["id"] = "dddddddddddddddddddddddddddddddd"
|
||||
s.accept(frame)
|
||||
_, command, _ = s.delivery(origin)
|
||||
if command == nil {
|
||||
t.Fatal("new explicit session rejected after stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverStreamIntentWakesImmediatelyAndCoalescesWithoutReplayWake(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
for i := 1; i <= 3; i++ {
|
||||
s.accept(streamIntent(i, 10000, 10400))
|
||||
}
|
||||
if len(s.wake) != 1 {
|
||||
t.Fatal("intent notifications must coalesce")
|
||||
}
|
||||
<-s.wake
|
||||
_, command, _ := s.delivery(origin)
|
||||
if command["sequence"] != float64(3) {
|
||||
t.Fatal("queued an intermediate command")
|
||||
}
|
||||
s.accept(streamIntent(3, 10000, 10400))
|
||||
if len(s.wake) != 0 {
|
||||
t.Fatal("replayed frame woke driver again")
|
||||
}
|
||||
s.stopStream()
|
||||
if len(s.wake) != 1 {
|
||||
t.Fatal("stop did not wake driver")
|
||||
}
|
||||
<-s.wake
|
||||
s.stopStream()
|
||||
if len(s.wake) != 0 {
|
||||
t.Fatal("repeated failure would spin the local loop")
|
||||
}
|
||||
}
|
||||
func TestRoverStreamRejectsExtendedDeadlineAndUnknownCommandFields(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(s, origin)
|
||||
if s.accept(streamIntent(1, 10000, 10401)) {
|
||||
t.Fatal("extended deadline accepted")
|
||||
}
|
||||
frame := streamIntent(1, 10000, 10400)
|
||||
frame.Command["queued"] = true
|
||||
if s.accept(frame) {
|
||||
t.Fatal("unknown field accepted")
|
||||
}
|
||||
for _, sequence := range []any{map[string]any{}, []any{1}, "1", 1.5, float64(1 << 53)} {
|
||||
bad := streamIntent(1, 10000, 10400)
|
||||
bad.Command["sequence"] = sequence
|
||||
if s.accept(bad) {
|
||||
t.Fatal("malformed sequence accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRoverStreamSilenceCancelsReadWithoutWaitingForTelemetry(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: roverClock{testClockID, 10000}})
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer server.Close()
|
||||
state := newRoverStreamState(time.Now())
|
||||
started := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
if roverReadStream(ctx, server.Client(), server.URL, map[string]any{}, state) == nil {
|
||||
t.Fatal("silent stream accepted")
|
||||
}
|
||||
if time.Since(started) > time.Second {
|
||||
t.Fatal("silent stream did not cancel its read")
|
||||
}
|
||||
}
|
||||
func TestRoverStreamReadsMultipleFramesOnOneResponse(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/node/rover-stream" {
|
||||
t.Error("wrong path")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
for i := 0; i < 3; i++ {
|
||||
raw, _ := json.Marshal(roverStreamReply{Watch: i < 2, Clock: roverClock{testClockID, 10000 + float64(i)}})
|
||||
fmt.Fprintln(w, string(raw))
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
state := newRoverStreamState(time.Now())
|
||||
if err := roverReadStream(context.Background(), server.Client(), server.URL, map[string]any{}, state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Sensors) vescArchive(path string) (map[string]any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
return s.modelDriver(ctx, &sensorModels[i], path, nil)
|
||||
}
|
||||
}
|
||||
panic("shipped VESC model is missing")
|
||||
}
|
||||
|
||||
func archiveCursorName(binding string) string {
|
||||
return "vesc-archive-" + digest(binding)[:24] + ".cursor"
|
||||
}
|
||||
|
||||
// Each pairing receives the complete immutable history, including backups
|
||||
// made locally and while Core was offline. ACK follows durable Core storage.
|
||||
func (s *Sensors) ConfigurationBatch(binding string) map[string]any {
|
||||
var after int64
|
||||
data, _ := os.ReadFile(filepath.Join(s.root, archiveCursorName(binding)))
|
||||
if json.Unmarshal(data, &after) != nil || after < 0 {
|
||||
after = 0
|
||||
}
|
||||
result, err := s.vescArchive("/archive-export?after=" + strconv.FormatInt(after, 10))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Sensors) AcknowledgeConfigurations(binding string, ack json.RawMessage, batch any) {
|
||||
value, ok := batch.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var sequence int64
|
||||
if json.Unmarshal(ack, &sequence) != nil || sequence < 0 {
|
||||
return
|
||||
}
|
||||
next, ok := value["next"].(float64)
|
||||
if !ok || next != float64(sequence) {
|
||||
return
|
||||
}
|
||||
// A failed cursor write causes replay; immutable archive insertion deduplicates it.
|
||||
_ = s.write(archiveCursorName(binding), sequence)
|
||||
}
|
||||
|
||||
func (s *Sensors) configurationRoutes(mux *http.ServeMux, server *Server) {
|
||||
for _, route := range []string{"GET /api/device-configurations/{device}", "GET /api/device-configurations/{device}/{version}"} {
|
||||
mux.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !server.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
device := r.PathValue("device")
|
||||
model := modelForDevice(device)
|
||||
if model == nil || model.ID != "vesc.controller" {
|
||||
reply(w, 404, map[string]string{"error": "История не найдена"})
|
||||
return
|
||||
}
|
||||
path := "/archives/" + url.PathEscape(device)
|
||||
if version := r.PathValue("version"); version != "" {
|
||||
path += "/" + url.PathEscape(version)
|
||||
} else {
|
||||
path += "?before=" + url.QueryEscape(r.URL.Query().Get("before"))
|
||||
}
|
||||
result, err := s.vescArchive(path)
|
||||
if err != nil {
|
||||
reply(w, 503, map[string]string{"error": "Архив конфигураций недоступен"})
|
||||
return
|
||||
}
|
||||
reply(w, 200, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVESCArchiveAckRequiresExactBatchAndPairingScope(t *testing.T) {
|
||||
s := isolatedSensors(t)
|
||||
batch := map[string]any{"next": float64(9)}
|
||||
s.AcknowledgeConfigurations("pair-a", json.RawMessage(`10`), batch)
|
||||
if _, err := os.Stat(filepath.Join(s.root, archiveCursorName("pair-a"))); !os.IsNotExist(err) {
|
||||
t.Fatal("incorrect ACK persisted")
|
||||
}
|
||||
s.AcknowledgeConfigurations("pair-a", json.RawMessage(`9`), batch)
|
||||
data, err := os.ReadFile(filepath.Join(s.root, archiveCursorName("pair-a")))
|
||||
if err != nil || string(data) != "9" {
|
||||
t.Fatalf("durable cursor: %q %v", data, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(s.root, archiveCursorName("pair-b"))); !os.IsNotExist(err) {
|
||||
t.Fatal("history skipped on another pairing")
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,8 @@ type sensorModel struct {
|
||||
Socket, PrepareUnit, Report string
|
||||
Actions map[string]bool
|
||||
ActionTimeouts map[string]time.Duration
|
||||
// This model may prepare an attachment only to read its protocol identity.
|
||||
ProtocolIdentity bool
|
||||
}
|
||||
|
||||
func actions(names ...string) map[string]bool {
|
||||
@@ -44,6 +46,11 @@ var sensorModels = []sensorModel{
|
||||
PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json",
|
||||
ActionTimeouts: map[string]time.Duration{"power.wake": 55 * time.Second},
|
||||
Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer", "recovery.configure", "power.wake")},
|
||||
{ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.7.4",
|
||||
Vendor: "0483", Product: "5740", USBName: "ChibiOS/RT Virtual COM Port", Socket: "/run/mission-core-vesc/driver.sock",
|
||||
PrepareUnit: "mission-core-node-vesc-prepare.service", Report: "/var/lib/mission-core-node-profiles/vesc/preparation.json",
|
||||
ActionTimeouts: map[string]time.Duration{"vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second},
|
||||
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")},
|
||||
}
|
||||
|
||||
func modelForDevice(id string) *sensorModel {
|
||||
@@ -74,6 +81,22 @@ func modelDeviceID(model *sensorModel, serial string) string {
|
||||
return model.Prefix + "_" + hex.EncodeToString(h[:])[:32]
|
||||
}
|
||||
|
||||
func preparedDeviceID(command SensorCommand, result any) string {
|
||||
model := modelForDevice(command.Session.DeviceID)
|
||||
if model == nil {
|
||||
return ""
|
||||
}
|
||||
if !model.ProtocolIdentity {
|
||||
return command.Session.DeviceID
|
||||
}
|
||||
if value, ok := result.(map[string]any); ok {
|
||||
if id, ok := value["device_id"].(string); ok && modelForDevice(id) == model {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sensorClient(socket string) *http.Client {
|
||||
return &http.Client{Timeout: 25 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
@@ -110,7 +133,7 @@ func discoverSensors(root string) []usbSensor {
|
||||
}
|
||||
unique := []usbSensor{}
|
||||
for _, item := range items {
|
||||
if !item.stable || counts[item.id] != 1 {
|
||||
if item.model.ProtocolIdentity || !item.stable || counts[item.id] != 1 {
|
||||
item.stable = false
|
||||
item.id = modelDeviceID(item.model, "provisional:"+item.binding)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func (s *Sensors) preparationPhase(c SensorCommand, model *sensorModel, job *pro
|
||||
}
|
||||
op.Preparation = &sensorPreparation{OperationID: c.ID, DeviceID: c.Session.DeviceID, ModelID: model.ID,
|
||||
StartedAt: float64(started.UnixMilli()) / 1000, ProfileStartedAt: job.started, State: state, Phase: phase,
|
||||
Steps: []preparationStep{{ID: "profile", Label: "Подготовка драйвера", State: deploy}, {ID: "verify", Label: "Проверка выбранной камеры", State: verify}}}
|
||||
Steps: []preparationStep{{ID: "profile", Label: "Подготовка драйвера", State: deploy}, {ID: "verify", Label: "Проверка выбранного устройства", State: verify}}}
|
||||
op.Updated = time.Now().Unix()
|
||||
err := s.write(c.ID+".json", op)
|
||||
s.events.notify()
|
||||
@@ -217,18 +217,20 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any,
|
||||
binding := s.discoverySessions[c.Session.DeviceID].binding
|
||||
s.mu.Unlock()
|
||||
if initialBinding != "" && binding != initialBinding {
|
||||
return nil, errors.New("Камера переподключена во время подготовки. Повторите проверку устройства.")
|
||||
return nil, errors.New("Устройство переподключено во время подготовки. Повторите проверку устройства.")
|
||||
}
|
||||
for _, raw := range inventory["items"].([]any) {
|
||||
item := raw.(map[string]any)
|
||||
if item["id"] != c.Session.DeviceID || item["online"] != true || item["prepared"] != true {
|
||||
matches := item["id"] == c.Session.DeviceID || (model.ProtocolIdentity && item["attachment_id"] == c.Session.DeviceID)
|
||||
if !matches || item["online"] != true || item["prepared"] != true || (model.ProtocolIdentity && item["verified"] != true) {
|
||||
continue
|
||||
}
|
||||
verify := c
|
||||
verify.Action = "verify"
|
||||
verify.Session.DeviceID, _ = item["id"].(string)
|
||||
verify.Session.SessionID = sensorSessionID(item)
|
||||
if verify.Session.SessionID == "" {
|
||||
return nil, errors.New("Драйвер не подтвердил сеанс камеры.")
|
||||
return nil, errors.New("Драйвер не подтвердил сеанс устройства.")
|
||||
}
|
||||
response, e := s.modelDriver(ctx, model, "/operation", verify)
|
||||
if e != nil || response["state"] == "unknown" {
|
||||
@@ -237,7 +239,7 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any,
|
||||
if response["state"] != "complete" {
|
||||
message, _ := response["error"].(string)
|
||||
if message == "" {
|
||||
message = "Не удалось проверить изображение выбранной камеры."
|
||||
message = "Не удалось проверить выбранное устройство."
|
||||
}
|
||||
return nil, errors.New(message)
|
||||
}
|
||||
@@ -249,7 +251,7 @@ func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any,
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Драйвер установлен, но камера не открылась. Проверьте USB-подключение.")
|
||||
return nil, errors.New("Драйвер установлен, но устройство не ответило. Проверьте питание и USB-подключение.")
|
||||
}
|
||||
|
||||
// Project only the matching model run. A previous success or another model's
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVESCDeclaredVersionMatchesBundledDriver(t *testing.T) {
|
||||
model := modelForDevice("vesc_00000000000000000000000000000000")
|
||||
root := filepath.Join("..", "..", "..", "..", "plugins", "vesc")
|
||||
driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver)
|
||||
if model == nil || len(match) != 2 || model.Version != string(match[1]) {
|
||||
t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver))
|
||||
}
|
||||
preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py"))
|
||||
if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) {
|
||||
t.Fatal("VESC preparation must declare the bundled driver version", err)
|
||||
}
|
||||
}
|
||||
|
||||
func fakeVESC(t *testing.T, s *Sensors, port, number string) {
|
||||
t.Helper()
|
||||
fakeUSB(t, s.usbRoot, port, "duplicate", "ChibiOS/RT Virtual COM Port", number)
|
||||
for key, value := range map[string]string{"idVendor": "0483", "idProduct": "5740"} {
|
||||
if err := os.WriteFile(filepath.Join(s.usbRoot, port, key), []byte(value), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVESCProvisionalIdentityIsReadOnlyAndDoesNotWeakenCameras(t *testing.T) {
|
||||
s := isolatedSensors(t)
|
||||
fakeVESC(t, s, "1-2", "2")
|
||||
fakeVESC(t, s, "1-3", "3")
|
||||
items := s.Inventory()["items"].([]any)
|
||||
if len(items) != 2 {
|
||||
t.Fatal("both controllers must be visible")
|
||||
}
|
||||
for _, raw := range items {
|
||||
item := raw.(map[string]any)
|
||||
if item["initializable"] != true || item["prepared"] != false {
|
||||
t.Fatal("identity bootstrap unavailable or falsely prepared")
|
||||
}
|
||||
c := sensorTestCommand()
|
||||
c.Session.DeviceID = item["id"].(string)
|
||||
for _, action := range []string{"start", "stop", "option", "settings.apply", "firmware.write"} {
|
||||
c.Action = action
|
||||
if _, err := s.Submit(c, false); err == nil {
|
||||
t.Fatal("VESC acquired write authority", action)
|
||||
}
|
||||
}
|
||||
}
|
||||
if items[0].(map[string]any)["id"] == items[1].(map[string]any)["id"] {
|
||||
t.Fatal("duplicate USB serial collapsed")
|
||||
}
|
||||
fakeUSB(t, s.usbRoot, "2-2", "same", "Insta360 X4", "4")
|
||||
fakeUSB(t, s.usbRoot, "2-3", "same", "Insta360 X4", "5")
|
||||
for _, raw := range s.Inventory()["items"].([]any) {
|
||||
item := raw.(map[string]any)
|
||||
if item["kind"] == "insta360.x4" && item["initializable"] != false {
|
||||
t.Fatal("camera guard weakened")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVESCPreparePromotesAttachmentToProtocolUUID(t *testing.T) {
|
||||
s := isolatedSensors(t)
|
||||
fakeVESC(t, s, "1-2", "2")
|
||||
first := s.Inventory()["items"].([]any)[0].(map[string]any)
|
||||
attachment := first["id"].(string)
|
||||
model := modelForDevice(attachment)
|
||||
stable := modelDeviceID(model, "uuid:synthetic-controller")
|
||||
var installed atomic.Bool
|
||||
s.runPreparation = func(_ context.Context, unit string) error {
|
||||
if unit != "mission-core-node-vesc-prepare.service" {
|
||||
t.Error("wrong profile")
|
||||
}
|
||||
installed.Store(true)
|
||||
return nil
|
||||
}
|
||||
s.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/inventory" {
|
||||
items := []any{}
|
||||
if installed.Load() {
|
||||
item := s.discovery(stable, "12", true)
|
||||
item["prepared"] = true
|
||||
item["verified"] = true
|
||||
item["configured"] = true
|
||||
item["attachment_id"] = attachment
|
||||
item["snapshot"].(map[string]any)["context"].(map[string]any)["session_id"] = "protocol_session"
|
||||
items = append(items, item)
|
||||
}
|
||||
return testSensorReply(map[string]any{"items": items}), nil
|
||||
}
|
||||
var command SensorCommand
|
||||
_ = json.NewDecoder(r.Body).Decode(&command)
|
||||
if command.Action != "verify" || command.Session.DeviceID != stable || command.Session.SessionID != "protocol_session" {
|
||||
t.Error("verification did not follow protocol identity")
|
||||
}
|
||||
return testSensorReply(map[string]any{"state": "complete", "result": map[string]any{"device_id": stable}}), nil
|
||||
})
|
||||
c := sensorTestCommand()
|
||||
c.Action = "prepare"
|
||||
c.Session = SensorSession{DeviceID: attachment, SessionID: sensorSessionID(first)}
|
||||
if _, err := s.Submit(c, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitSensor(t, func() bool { return s.Get(c.ID).State != "running" })
|
||||
if s.Get(c.ID).State != "complete" {
|
||||
t.Fatal(s.Get(c.ID))
|
||||
}
|
||||
items := s.Inventory()["items"].([]any)
|
||||
if len(items) != 1 || items[0].(map[string]any)["id"] != stable {
|
||||
t.Fatal("provisional row survived promotion")
|
||||
}
|
||||
s.mu.Lock()
|
||||
a, b := s.initialized[stable], s.initialized[attachment]
|
||||
s.mu.Unlock()
|
||||
if !a || b {
|
||||
t.Fatal("initialization persisted transport identity")
|
||||
}
|
||||
// A stale runtime attachment is never presented as a currently connected controller.
|
||||
if err := os.RemoveAll(filepath.Join(s.usbRoot, "1-2")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items = s.Inventory()["items"].([]any)
|
||||
if len(items) != 1 || items[0].(map[string]any)["online"] != false {
|
||||
t.Fatal("unplugged driver observation accepted")
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,9 @@ func OpenSensors(root, nodeID string) (*Sensors, error) {
|
||||
}
|
||||
for _, op := range s.operations {
|
||||
if op.Command.Action == "prepare" && op.State == "complete" {
|
||||
s.initialized[op.Command.Session.DeviceID] = true
|
||||
if id := preparedDeviceID(op.Command, op.Result); id != "" {
|
||||
s.initialized[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := s.write("initialized.json", s.initialized); e != nil {
|
||||
@@ -192,7 +194,7 @@ func (s *Sensors) modelDriver(ctx context.Context, model *sensorModel, path stri
|
||||
}
|
||||
response, e := client.Do(req)
|
||||
if e != nil {
|
||||
return nil, errors.New("Служба камеры недоступна. Подготовьте устройство.")
|
||||
return nil, errors.New("Служба устройства недоступна. Подготовьте устройство.")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var result map[string]any
|
||||
@@ -241,8 +243,24 @@ func (s *Sensors) Inventory() map[string]any {
|
||||
unsafePreparation[id] = item["preparation_safe"] == false || snapshot["acquisition"] != "idle"
|
||||
continue
|
||||
}
|
||||
if model.ProtocolIdentity {
|
||||
if !currentCameraSnapshot(item, model) {
|
||||
continue
|
||||
}
|
||||
attachment, _ := item["attachment_id"].(string)
|
||||
matched := false
|
||||
for _, candidate := range usb {
|
||||
if candidate.model == model && candidate.id == attachment {
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
seen[attachment] = true
|
||||
}
|
||||
s.mu.Lock()
|
||||
if model.PrepareUnit != "" {
|
||||
if model.PrepareUnit != "" && !model.ProtocolIdentity {
|
||||
item["configured"] = s.initialized[id]
|
||||
}
|
||||
if name := s.names[id]; name != "" {
|
||||
@@ -325,13 +343,18 @@ func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
|
||||
if !initializable {
|
||||
stability, basis = "provisional", "transport-local"
|
||||
}
|
||||
// VESC bootstrap grants only a fixed identity read on the selected attachment.
|
||||
// This does not promote the attachment to stable identity or allow motor control.
|
||||
if online && model.ProtocolIdentity {
|
||||
initializable = true
|
||||
}
|
||||
return map[string]any{"id": id, "name": name, "model": model.Name, "kind": model.Kind, "initializable": initializable, "configured": configured, "prepared": false, "verified": false, "online": online, "usb": speed, "layers": []any{}, "snapshot": map[string]any{
|
||||
"context": map[string]any{"session_id": session, "device": map[string]any{"device_id": id, "model": map[string]string{"plugin_id": model.Plugin, "plugin_version": model.Version, "model_id": model.ID}, "stability": stability, "basis": basis}, "execution": map[string]string{"node_id": s.nodeID, "agent_instance_id": s.instance, "platform": "linux"}, "opened_at": now},
|
||||
"revision": 0, "enrollment": enrollment, "connectivity": connectivity, "acquisition": "idle", "observed_at": now}}
|
||||
}
|
||||
|
||||
func sensorViewAction(action string) bool {
|
||||
return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list"
|
||||
return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.config.backup"
|
||||
}
|
||||
|
||||
func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) {
|
||||
@@ -365,10 +388,10 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error)
|
||||
return nil, errors.New("Срок команды истёк. Устройство не изменено.")
|
||||
}
|
||||
for _, v := range s.operations {
|
||||
if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model {
|
||||
if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model {
|
||||
return nil, errors.New("Подготовка модели ещё выполняется.")
|
||||
}
|
||||
if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) {
|
||||
if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) {
|
||||
return nil, errors.New("Другая операция устройства ещё выполняется.")
|
||||
}
|
||||
}
|
||||
@@ -411,11 +434,11 @@ func (s *Sensors) execute(c SensorCommand) {
|
||||
if !deadline.After(time.Now()) {
|
||||
err = errors.New("Срок команды истёк. Устройство не изменено.")
|
||||
} else if item == nil {
|
||||
err = errors.New("Камера не обнаружена. Проверьте подключение.")
|
||||
err = errors.New("Устройство не обнаружено. Проверьте подключение.")
|
||||
} else if c.Action == "prepare" && item["online"] != true {
|
||||
err = errors.New("Камера отключена. Проверьте подключение.")
|
||||
err = errors.New("Устройство отключено. Проверьте подключение.")
|
||||
} else if c.Action == "prepare" && item["initializable"] == false {
|
||||
err = errors.New("Не удалось однозначно определить камеру. Проверьте её идентификатор и подключение.")
|
||||
err = errors.New("Не удалось однозначно определить устройство. Проверьте его идентификатор и подключение.")
|
||||
} else if (c.Action == "prepare" || c.Action == "rename") && sensorSessionID(item) != c.Session.SessionID {
|
||||
err = errors.New("Сеанс устройства изменился. Обновите сведения.")
|
||||
} else if c.Action == "prepare" {
|
||||
@@ -451,7 +474,12 @@ func (s *Sensors) execute(c SensorCommand) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err == nil && c.Action == "prepare" {
|
||||
s.initialized[c.Session.DeviceID] = true
|
||||
initializedID := preparedDeviceID(c, result)
|
||||
if initializedID == "" {
|
||||
err = errors.New("Драйвер не подтвердил личность устройства.")
|
||||
} else {
|
||||
s.initialized[initializedID] = true
|
||||
}
|
||||
if e := s.write("initialized.json", s.initialized); e != nil {
|
||||
err = e
|
||||
uncertain = true
|
||||
@@ -496,6 +524,7 @@ func (s *Sensors) RemoteResults() []any {
|
||||
return out
|
||||
}
|
||||
func (s *Sensors) Routes(mux *http.ServeMux, server *Server) {
|
||||
s.configurationRoutes(mux, server)
|
||||
mux.HandleFunc("GET /api/devices/events", func(w http.ResponseWriter, r *http.Request) { s.stream(w, r, server) })
|
||||
mux.HandleFunc("GET /api/devices", func(w http.ResponseWriter, r *http.Request) {
|
||||
if server.authorized(w, r) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// An authenticated Node action may start only this fixed model job.
|
||||
polkit.addRule(function(action, subject) {
|
||||
var unit = action.lookup("unit");
|
||||
if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") {
|
||||
if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-vesc-prepare.service" || unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") {
|
||||
return polkit.Result.YES;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import sys
|
||||
from build_deb import build, VERSION, BRAND_SHA256
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5"
|
||||
DG_COMMIT = "8dd9190573d6616024ef01b9b34bf90b72960f44"
|
||||
|
||||
|
||||
def guideline_sources():
|
||||
@@ -36,6 +36,7 @@ def provenance():
|
||||
"design_guideline_files": guideline_sources(),
|
||||
"shared_sensor_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/sensor-ui/src").rglob("*")) if p.is_file()},
|
||||
"shared_spatial_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/spatial-ui/src").rglob("*")) if p.is_file()},
|
||||
"vesc_plugin_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/vesc").rglob("*")) if p.is_file() and not any(x in p.relative_to(ROOT.parents[1]).parts for x in ("__pycache__", "build"))},
|
||||
"k1_frontend_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/xgrids-k1/frontend/src").rglob("*")) if p.is_file()},
|
||||
"toolchain": json.loads((ROOT / "toolchain.json").read_text()), "files": files}
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BINARY_VERSION = "0.8.21"
|
||||
VERSION = "0.8.21-3"
|
||||
BINARY_VERSION = "0.8.45"
|
||||
VERSION = "0.8.45-1"
|
||||
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
|
||||
from debian import package
|
||||
|
||||
@@ -44,7 +44,7 @@ Architecture: amd64
|
||||
Maintainer: NODE.DC local build <noreply@example.invalid>
|
||||
Section: admin
|
||||
Priority: optional
|
||||
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, libc6 (>= 2.35), libstdc++6 (>= 12), libgcc-s1, zlib1g
|
||||
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g
|
||||
Description: Mission Core onboard computer configuration
|
||||
Local graphical setup, host inventory, SSH access and persistent node identity.
|
||||
""".encode()
|
||||
@@ -66,6 +66,11 @@ Description: Mission Core onboard computer configuration
|
||||
("tailscale-release.json", "usr/share/mission-core-node/tailscale-release.json", 0o644),
|
||||
("configure-system", "usr/lib/mission-core-node/configure-system", 0o755),
|
||||
("environment_helper.py", "usr/lib/mission-core-node/environment_helper.py", 0o644),
|
||||
("desktop_startup.py", "usr/lib/mission-core-node/desktop_startup.py", 0o644),
|
||||
("mission-core-node-autostart.desktop", "usr/share/mission-core-node/mission-core-node-autostart.desktop", 0o644),
|
||||
("usb-startup.json", "usr/share/mission-core-node/usb-startup.json", 0o644),
|
||||
("usb_startup_recovery.py", "usr/lib/mission-core-node/usb_startup_recovery.py", 0o644),
|
||||
("mission-core-node-usb-startup.service", "usr/lib/systemd/system/mission-core-node-usb-startup.service", 0o644),
|
||||
("mission-core-node-environment.service", "usr/lib/systemd/system/mission-core-node-environment.service", 0o644),
|
||||
("60-environment.conf", "usr/share/mission-core-node/60-environment.conf", 0o644),
|
||||
("setup-monitor", "usr/lib/mission-core-node/setup-monitor", 0o755),
|
||||
@@ -111,6 +116,8 @@ Description: Mission Core onboard computer configuration
|
||||
files.append(("usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/" + str(path.relative_to(sdk)), path.read_bytes(), 0o644))
|
||||
if (ROOT / "build/provenance.json").exists():
|
||||
files.append(("usr/share/doc/mission-core-node/provenance.json", (ROOT / "build/provenance.json").read_bytes(), 0o644))
|
||||
import runpy
|
||||
files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/vesc/packaging/payload.py"))["payload"]())
|
||||
archive = package(controls, files)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_bytes(archive)
|
||||
|
||||
@@ -11,7 +11,7 @@ from pathlib import Path
|
||||
NODE = Path(__file__).resolve().parents[1]
|
||||
REPO = NODE.parents[1]
|
||||
DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE"
|
||||
DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5"
|
||||
DG_COMMIT = "8dd9190573d6616024ef01b9b34bf90b72960f44"
|
||||
|
||||
|
||||
def files(root):
|
||||
@@ -73,6 +73,13 @@ def build(qualified, node_only=False):
|
||||
# board, runtime path override or operator compiler dependency is needed.
|
||||
virtual = str(REPO.name + "/apps/node-agent/build/model-packages/" + package_name)
|
||||
entries[virtual] = qualified
|
||||
native_root = REPO / "plugins/vesc"
|
||||
native = json.loads((native_root / "packaging/native-runtime.json").read_text())
|
||||
native_path = native_root / "build/native-runtime" / native["file"]
|
||||
native_bytes = native_path.read_bytes()
|
||||
if len(native_bytes) != native["bytes"] or hashlib.sha256(native_bytes).hexdigest() != native["sha256"]:
|
||||
raise ValueError("Qualified VESC Tool runtime changed")
|
||||
entries[REPO.name + "/plugins/vesc/build/native-runtime/" + native["file"]] = native_path
|
||||
metadata = {}
|
||||
for name, path in entries.items():
|
||||
data = path.read_bytes()
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Unprivileged XDG startup: wait for Node before opening its ordinary UI."""
|
||||
import http.client
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
def wait_for_service(now=time.monotonic, sleep=time.sleep, connection=http.client.HTTPConnection):
|
||||
deadline = now() + 180
|
||||
while now() < deadline:
|
||||
client = connection('127.0.0.1', 8780, timeout=2)
|
||||
try:
|
||||
client.request('GET', '/')
|
||||
response = client.getresponse()
|
||||
if response.status == 200:
|
||||
return True
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
finally:
|
||||
client.close()
|
||||
sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if os.geteuid() == 0:
|
||||
raise SystemExit('Run in the normal graphical user session')
|
||||
wait_for_service()
|
||||
# Gtk.Application retains one window per desktop session. Its ordinary
|
||||
# polkit authorization and error handling are unchanged.
|
||||
os.execv('/usr/bin/mission-core-node', ['/usr/bin/mission-core-node'])
|
||||
@@ -219,7 +219,33 @@ def tailscale_install():
|
||||
return "Tailscale установлен; системная служба запущена. Вход проверяется отдельно."
|
||||
|
||||
|
||||
OPERATIONS = {"platform": platform, "packages": packages, "node-service": node_service, "network-inventory": network_inventory, "usb-inventory": usb_inventory, "ssh-service": ssh_service, "tailscale-install": tailscale_install}
|
||||
def desktop_autostart():
|
||||
owned_config(Path('/usr/share/mission-core-node/mission-core-node-autostart.desktop'),
|
||||
Path('/etc/xdg/autostart/org.nodedc.MissionCoreNode.desktop'))
|
||||
return "Окно приложения открывается при входе в рабочий стол. Служба БК работает и без входа."
|
||||
|
||||
|
||||
def usb_startup():
|
||||
# Enabling the next boot is distinct from executing recovery now. This
|
||||
# workflow never resets devices in a running operator session.
|
||||
owned_config(Path('/usr/share/mission-core-node/usb-startup.json'),
|
||||
Path('/etc/mission-core-node/usb-startup.json'))
|
||||
command(['/usr/bin/systemctl', 'daemon-reload'])
|
||||
command(['/usr/bin/systemctl', 'enable', 'mission-core-node-usb-startup.service'])
|
||||
command(['/usr/bin/systemctl', 'is-enabled', 'mission-core-node-usb-startup.service'])
|
||||
report = json.loads(command(['/usr/bin/python3', '-I', '-B', '/usr/lib/mission-core-node/usb_startup_recovery.py', '--inspect'], timeout=75))
|
||||
if report.get('state') != 'inspected':
|
||||
raise SetupError("Не удалось проверить поддержку восстановления USB. Повторите настройку.")
|
||||
supported = sum(h.get('individual_power') is True for h in report.get('hubs', []))
|
||||
if not supported:
|
||||
return "Проверка при загрузке включена. Поддержка отдельного переключения USB-портов не подтверждена; они будут пропущены."
|
||||
return "Восстановление при загрузке включено для поддерживаемых USB-портов. Обнаруженные устройства сохраняют подключение."
|
||||
|
||||
|
||||
OPERATIONS = {"platform": platform, "packages": packages, "node-service": node_service,
|
||||
"desktop-autostart": desktop_autostart, "usb-startup": usb_startup,
|
||||
"network-inventory": network_inventory, "usb-inventory": usb_inventory,
|
||||
"ssh-service": ssh_service, "tailscale-install": tailscale_install}
|
||||
|
||||
|
||||
def run_steps(profile, operations, save):
|
||||
|
||||
@@ -5,7 +5,7 @@ mc_node_release_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
if [ ! -t 0 ]; then
|
||||
exec /usr/bin/gnome-terminal --wait --title="Mission Core Node" -- "$mc_node_release_dir/install"
|
||||
fi
|
||||
printf '%s\n' 'Mission Core Node' 'Обновление приложения и встроенных пакетов камер на этом Ubuntu-компьютере.' 'Подготовка X4 выполняется затем из списка устройств в Node или Core.' 'Пароль администратора вводится только в этом локальном окне Ubuntu.'
|
||||
printf '%s\n' 'Mission Core Node' 'Обновление приложения и встроенных драйверов на этом Ubuntu-компьютере.' 'Подготовка VESC и X4 выполняется затем из списка устройств в Node или Core.' 'Пароль администратора вводится только в этом локальном окне Ubuntu.'
|
||||
set +e
|
||||
/usr/bin/sudo /usr/bin/python3 -I "$mc_node_release_dir/install_release.py" 2>&1 | /usr/bin/tee -a "$mc_node_release_dir/install-output.log"
|
||||
mc_node_install_result=${PIPESTATUS[0]}
|
||||
|
||||
@@ -351,7 +351,7 @@ def main():
|
||||
if report["state"] != "complete":
|
||||
raise RuntimeError(report["error"])
|
||||
print(
|
||||
"Mission Core Node обновлён. X4 можно подготовить из списка устройств в Node или Core.",
|
||||
"Mission Core Node обновлён. VESC и X4 можно подготовить из списка устройств в Node или Core.",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -243,6 +243,10 @@ def main():
|
||||
sys.path.insert(0, str(node / "packaging"))
|
||||
from build_deb import BINARY_VERSION, VERSION, build
|
||||
|
||||
run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_usb_startup_recovery", "test_desktop_startup", "-v"], cwd=node / "packaging")
|
||||
run("owner-release-staging-tests", ["/usr/bin/python3", "plugins/insta360-x4/packaging/test_owner_release_entry.py"], cwd=repo)
|
||||
run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service")], cwd=node)
|
||||
run("vesc-reader-tests", ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "plugins/vesc/tests", "-v"], cwd=repo)
|
||||
binary = node / "build/node-agent-linux-amd64"
|
||||
run(
|
||||
"node-binary",
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Type=Application
|
||||
Name=Mission Core Node
|
||||
Comment=Настройка и диагностика бортового компьютера
|
||||
TryExec=/usr/bin/mission-core-node
|
||||
Exec=/usr/bin/python3 -I -B /usr/lib/mission-core-node/desktop_startup.py
|
||||
Icon=org.nodedc.MissionCoreNode
|
||||
Terminal=false
|
||||
StartupNotify=false
|
||||
@@ -0,0 +1,35 @@
|
||||
[Unit]
|
||||
Description=Mission Core bounded USB startup recovery
|
||||
Wants=systemd-udev-settle.service
|
||||
After=systemd-udev-settle.service
|
||||
Before=mission-core-node.service mission-core-vesc.service
|
||||
ConditionPathExists=/etc/mission-core-node/usb-startup.json
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-node/usb_startup_recovery.py
|
||||
ExecStopPost=/usr/bin/python3 -I -B /usr/lib/mission-core-node/usb_startup_recovery.py --restore
|
||||
TimeoutStartSec=130
|
||||
TimeoutStopSec=15
|
||||
RuntimeDirectory=mission-core-usb-startup
|
||||
RuntimeDirectoryMode=0755
|
||||
RuntimeDirectoryPreserve=yes
|
||||
UMask=0077
|
||||
NoNewPrivileges=yes
|
||||
PrivateNetwork=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
RestrictSUIDSGID=yes
|
||||
RestrictAddressFamilies=AF_UNIX AF_NETLINK
|
||||
CapabilityBoundingSet=
|
||||
ReadWritePaths=/sys/devices /run/mission-core-usb-startup
|
||||
DevicePolicy=closed
|
||||
DeviceAllow=char-usb_device rw
|
||||
TasksMax=16
|
||||
MemoryMax=64M
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -2,6 +2,7 @@
|
||||
set -eu
|
||||
case "$1" in
|
||||
configure)
|
||||
/usr/bin/python3 -I /usr/lib/mission-core-vesc/clear_runtime_cache.py
|
||||
if ! getent passwd mission-core-node >/dev/null; then
|
||||
adduser --system --group --home /var/lib/mission-core-node --no-create-home --disabled-login mission-core-node
|
||||
fi
|
||||
@@ -15,6 +16,9 @@ case "$1" in
|
||||
systemctl enable mission-core-node.service
|
||||
systemctl restart mission-core-node.service
|
||||
systemctl try-restart mission-core-realsense.service
|
||||
if [ -f /var/lib/mission-core-node-profiles/vesc/preparation.json ]; then
|
||||
systemctl start mission-core-node-vesc-prepare.service
|
||||
fi
|
||||
if [ -f /run/mission-core-node-k1-upgrade-active ]; then
|
||||
# A jointly upgraded plugin starts itself after its own configuration.
|
||||
# Restore it here only when that package is already configured.
|
||||
|
||||
@@ -14,10 +14,22 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
mc_node_usb_job=$(systemctl show --property=ActiveState --value mission-core-node-usb-startup.service 2>/dev/null || true)
|
||||
case "$mc_node_usb_job" in
|
||||
activating|deactivating) echo "Mission Core Node: дождитесь завершения обнаружения USB при загрузке." >&2; exit 1 ;;
|
||||
esac
|
||||
if [ -f /run/mission-core-usb-startup/pending.json ]; then
|
||||
echo "Mission Core Node: восстановление USB ещё не завершило включение порта; пакет сохранён." >&2
|
||||
exit 1
|
||||
fi
|
||||
mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true)
|
||||
case "$mc_node_x4_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;;
|
||||
esac
|
||||
mc_node_vesc_job=$(systemctl show --property=ActiveState --value mission-core-node-vesc-prepare.service 2>/dev/null || true)
|
||||
case "$mc_node_vesc_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки VESC." >&2; exit 1 ;;
|
||||
esac
|
||||
mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true)
|
||||
case "$mc_node_device_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;;
|
||||
@@ -38,6 +50,7 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then
|
||||
(umask 077; : > /run/mission-core-node-k1-upgrade-active)
|
||||
systemctl stop mission-core-k1.service
|
||||
fi
|
||||
systemctl stop mission-core-vesc.service 2>/dev/null || true
|
||||
systemctl stop mission-core-node-monitor.service 2>/dev/null || true
|
||||
fi
|
||||
. /etc/os-release
|
||||
|
||||
@@ -13,10 +13,22 @@ if [ -d /run/systemd/system ]; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
mc_node_usb_job=$(systemctl show --property=ActiveState --value mission-core-node-usb-startup.service 2>/dev/null || true)
|
||||
case "$mc_node_usb_job" in
|
||||
activating|deactivating) echo "Mission Core Node: дождитесь завершения обнаружения USB при загрузке." >&2; exit 1 ;;
|
||||
esac
|
||||
if [ -f /run/mission-core-usb-startup/pending.json ]; then
|
||||
echo "Mission Core Node: восстановление USB ещё не завершило включение порта; пакет сохранён." >&2
|
||||
exit 1
|
||||
fi
|
||||
mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true)
|
||||
case "$mc_node_x4_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;;
|
||||
esac
|
||||
mc_node_vesc_job=$(systemctl show --property=ActiveState --value mission-core-node-vesc-prepare.service 2>/dev/null || true)
|
||||
case "$mc_node_vesc_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки VESC." >&2; exit 1 ;;
|
||||
esac
|
||||
mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true)
|
||||
case "$mc_node_device_job" in
|
||||
active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;;
|
||||
@@ -30,8 +42,39 @@ if [ -d /run/systemd/system ]; then
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
retire_startup_settings() {
|
||||
for mc_node_owned in /etc/xdg/autostart/org.nodedc.MissionCoreNode.desktop /etc/mission-core-node/usb-startup.json; do
|
||||
case "$mc_node_owned" in
|
||||
*.desktop) mc_node_template=/usr/share/mission-core-node/mission-core-node-autostart.desktop ;;
|
||||
*.json) mc_node_template=/usr/share/mission-core-node/usb-startup.json ;;
|
||||
esac
|
||||
if [ ! -L "$mc_node_owned" ] && cmp -s "$mc_node_template" "$mc_node_owned"; then
|
||||
rm "$mc_node_owned"
|
||||
fi
|
||||
done
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl disable --now mission-core-node-usb-startup.service
|
||||
fi
|
||||
}
|
||||
# A downgrade removes helpers introduced in 0.8.37. Retire their owned
|
||||
# configuration first; do not leave an enabled unit or XDG entry dangling.
|
||||
if [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.37-1; then
|
||||
retire_startup_settings
|
||||
fi
|
||||
case "$1" in
|
||||
upgrade|remove|deconfigure)
|
||||
if [ -d /run/systemd/system ] && [ -f /usr/lib/systemd/system/mission-core-vesc.service ]; then
|
||||
systemctl disable --now mission-core-vesc.service
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
case "$1" in
|
||||
remove|deconfigure)
|
||||
if cmp -s /usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules /etc/udev/rules.d/70-mission-core-vesc.rules; then
|
||||
rm /etc/udev/rules.d/70-mission-core-vesc.rules
|
||||
if [ -d /run/systemd/system ]; then udevadm control --reload-rules; fi
|
||||
fi
|
||||
retire_startup_settings
|
||||
mc_node_ssh_snippet=/etc/ssh/sshd_config.d/60-mission-core-node.conf
|
||||
if [ -e "$mc_node_ssh_snippet" ]; then
|
||||
if cmp -s /usr/share/mission-core-node/60-mission-core-node.conf "$mc_node_ssh_snippet"; then
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
import desktop_startup as startup
|
||||
|
||||
|
||||
class DesktopStartupTests(unittest.TestCase):
|
||||
def test_waits_for_service_without_credentials_and_closes_each_connection(self):
|
||||
clock = [0]
|
||||
def sleep(seconds): clock[0] += seconds
|
||||
client = Mock()
|
||||
client.getresponse.side_effect = [OSError('not started'), Mock(status=503), Mock(status=200)]
|
||||
factory = Mock(return_value=client)
|
||||
self.assertTrue(startup.wait_for_service(lambda: clock[0], sleep, factory))
|
||||
self.assertEqual(clock[0], 2)
|
||||
self.assertEqual(client.close.call_count, 3)
|
||||
self.assertEqual(client.request.call_args.args, ('GET', '/'))
|
||||
|
||||
def test_stopped_service_does_not_hold_startup_forever(self):
|
||||
clock = [0]
|
||||
def sleep(seconds): clock[0] += seconds
|
||||
client = Mock()
|
||||
client.request.side_effect = OSError('offline')
|
||||
self.assertFalse(startup.wait_for_service(lambda: clock[0], sleep, lambda *a, **kw: client))
|
||||
self.assertEqual(clock[0], 180)
|
||||
self.assertEqual(client.close.call_count, 180)
|
||||
@@ -15,6 +15,24 @@ PROFILE = json.loads((Path(__file__).parents[1] / "internal/node/environment-pro
|
||||
|
||||
|
||||
class EnvironmentWorkflowTests(unittest.TestCase):
|
||||
def test_profile_and_shipped_operations_match(self):
|
||||
self.assertEqual({s['id'] for s in PROFILE['steps']}, set(helper.OPERATIONS))
|
||||
|
||||
def test_usb_setup_enables_next_boot_without_resetting_live_devices(self):
|
||||
def command(argv, **_):
|
||||
return json.dumps({'state': 'inspected', 'hubs': [{'individual_power': True}]}) if '--inspect' in argv else ''
|
||||
with patch.object(helper, 'owned_config') as config, patch.object(helper, 'command', side_effect=command) as run:
|
||||
self.assertIn('включено', helper.usb_startup())
|
||||
config.assert_called_once()
|
||||
for call in run.call_args_list:
|
||||
self.assertFalse({'--now', 'start', 'restart'} & set(call.args[0]))
|
||||
self.assertTrue(any('--inspect' in call.args[0] for call in run.call_args_list))
|
||||
|
||||
def test_autostart_preserves_foreign_configuration_and_does_not_start_a_gui_as_root(self):
|
||||
with patch.object(helper, 'owned_config', side_effect=helper.SetupError('conflict')), patch.object(helper, 'command') as run:
|
||||
with self.assertRaises(helper.SetupError): helper.desktop_autostart()
|
||||
run.assert_not_called()
|
||||
|
||||
def test_failure_blocks_dependents_but_inventory_still_runs_and_retry_rechecks(self):
|
||||
saved = []
|
||||
operations = {item['id']: Mock(return_value='verified') for item in PROFILE['steps']}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Synthetic sysfs/journal only: these tests never open a physical USB port."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import usb_startup_recovery as recovery
|
||||
|
||||
|
||||
def event(second, message, transport='kernel'):
|
||||
return {'__MONOTONIC_TIMESTAMP': str(int(second * 1000000)),
|
||||
'_TRANSPORT': transport, 'MESSAGE': message}
|
||||
|
||||
|
||||
class JournalTests(unittest.TestCase):
|
||||
def test_only_terminal_boot_failures_with_no_later_connection_are_candidates(self):
|
||||
records = [event(20, 'usb usb1-port2: unable to enumerate USB device'),
|
||||
event(18, 'usb usb1-port3: unable to enumerate USB device'),
|
||||
event(23, 'usb 1-3: new full-speed USB device number 8 using xhci_hcd'),
|
||||
event(12, 'usb 1-1-port2: unable to enumerate USB device'),
|
||||
event(65, 'usb usb2-port1: unable to enumerate USB device'),
|
||||
event(15, 'usb usb2-port3: unable to enumerate USB device', 'stdout'),
|
||||
event(18, 'usb 1-4: device descriptor read/64, error -71')]
|
||||
self.assertEqual(recovery.failed_ports(list(reversed(records))), ['1-1-port2', 'usb1-port2'])
|
||||
|
||||
def test_success_or_user_disconnect_invalidates_old_failure(self):
|
||||
for message in ['New USB device found, idVendor=0000', 'USB disconnect, device number 8']:
|
||||
self.assertEqual(recovery.failed_ports([
|
||||
event(20, 'usb usb1-port2: unable to enumerate USB device'), event(21, 'usb 1-2: ' + message)]), [])
|
||||
|
||||
def test_invalid_port_names_cannot_be_paths(self):
|
||||
for name in ['../../etc/passwd', 'usb0-port0', 'usb1-port1/disable']:
|
||||
with self.assertRaises(ValueError): recovery.child_name(name)
|
||||
self.assertEqual(recovery.child_name('1-2.3-port4'), '1-2.3.4')
|
||||
|
||||
|
||||
class SysfsTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
base = Path(self.temp.name)
|
||||
self.root, self.physical = base/'bus', base/'devices'
|
||||
self.root.mkdir(); self.physical.mkdir()
|
||||
self.usb = recovery.USB(self.root, self.physical)
|
||||
self.ports = []
|
||||
for n in (1, 2):
|
||||
hub = self.physical/f'usb{n}'; hub.mkdir()
|
||||
for key, value in {'bDeviceClass':'09', 'busnum':str(n), 'devnum':'1'}.items():
|
||||
(hub/key).write_text(value)
|
||||
(self.root/hub.name).symlink_to(hub, target_is_directory=True)
|
||||
interface = hub/f'{n}-0:1.0'; interface.mkdir()
|
||||
(self.root/interface.name).symlink_to(interface, target_is_directory=True)
|
||||
port = interface/f'usb{n}-port2'; port.mkdir()
|
||||
for key, value in {'state':'not attached', 'disable':'0\n', 'over_current_count':'0', 'connect_type':'unknown'}.items():
|
||||
(port/key).write_text(value)
|
||||
self.ports.append(port)
|
||||
(self.ports[0]/'peer').symlink_to(self.ports[1], target_is_directory=True)
|
||||
(self.ports[1]/'peer').symlink_to(self.ports[0], target_is_directory=True)
|
||||
|
||||
def plan(self):
|
||||
with patch.object(recovery, 'run', return_value=' wHubCharacteristic 0x0009\n'):
|
||||
return self.usb.plan('usb1-port2')
|
||||
|
||||
def test_individual_power_pair_can_be_disabled_and_restored(self):
|
||||
entries = self.plan()
|
||||
self.assertEqual([e['name'] for e in entries], ['usb1-port2', 'usb2-port2'])
|
||||
for entry in entries: self.usb.write(entry, True)
|
||||
self.assertTrue(all((p/'disable').read_text() == '1\n' for p in self.ports))
|
||||
for entry in reversed(entries): self.usb.write(entry, False)
|
||||
self.assertTrue(all((p/'disable').read_text() == '0\n' for p in self.ports))
|
||||
|
||||
def test_connected_companion_blocks_both_ports_before_descriptor_query(self):
|
||||
(self.ports[1]/'device').symlink_to(self.physical/'camera')
|
||||
with patch.object(recovery, 'run') as run:
|
||||
with self.assertRaises(OSError): self.usb.plan('usb1-port2')
|
||||
run.assert_not_called()
|
||||
self.assertEqual((self.ports[0]/'disable').read_text(), '0\n')
|
||||
|
||||
def test_non_individual_power_or_missing_descriptor_cannot_reset(self):
|
||||
for output in ['wHubCharacteristics 0x0000', 'wHubCharacteristics 0x0002', '']:
|
||||
with self.subTest(output=output), patch.object(recovery, 'run', return_value=output):
|
||||
with self.assertRaises(OSError): self.usb.plan('usb1-port2')
|
||||
|
||||
def test_internal_disabled_overcurrent_and_mid_enumeration_ports_skipped(self):
|
||||
for attribute, value in [('connect_type', 'hardwired'), ('disable', '1'), ('over_current_count', '1'), ('state', 'powered')]:
|
||||
p = self.ports[0]/attribute; original = p.read_text(); p.write_text(value)
|
||||
with self.subTest(attribute=attribute), self.assertRaises(OSError): self.plan()
|
||||
p.write_text(original)
|
||||
|
||||
def test_attachment_after_planning_prevents_write(self):
|
||||
entries = self.plan()
|
||||
(self.ports[0]/'device').symlink_to(self.physical/'new-device')
|
||||
with self.assertRaises(OSError): self.usb.write(entries[0], True)
|
||||
self.assertEqual((self.ports[0]/'disable').read_text(), '0\n')
|
||||
|
||||
def test_hub_replacement_after_planning_prevents_write(self):
|
||||
entries = self.plan()
|
||||
(self.physical/'usb1'/'devnum').write_text('4')
|
||||
with self.assertRaises(OSError): self.usb.write(entries[0], True)
|
||||
|
||||
def test_first_hub_replaced_while_inspecting_companion_invalidates_plan(self):
|
||||
def inspect(name):
|
||||
if name == 'usb2-port2': (self.physical/'usb1'/'devnum').write_text('4')
|
||||
return True
|
||||
with patch.object(self.usb, 'individual_power', side_effect=inspect):
|
||||
with self.assertRaises(OSError): self.usb.plan('usb1-port2')
|
||||
|
||||
def test_enabled_port_is_not_written_during_cleanup(self):
|
||||
entries = self.plan()
|
||||
with patch.object(recovery.os, 'open', side_effect=AssertionError('No write expected')):
|
||||
self.usb.write(entries[0], False)
|
||||
|
||||
def test_foreign_companion_path_is_rejected(self):
|
||||
(self.ports[0]/'peer').unlink()
|
||||
(self.ports[0]/'peer').symlink_to(self.root)
|
||||
with self.assertRaises(OSError): self.usb.companions('usb1-port2')
|
||||
|
||||
|
||||
class RecoveryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.state = Path(self.temp.name)
|
||||
self.clock = 30
|
||||
self.usb = Mock()
|
||||
self.entries = [{'name': 'usb1-port2', 'generation': {'address': 1}},
|
||||
{'name': 'usb2-port2', 'generation': {'address': 1}}]
|
||||
self.usb.plan.return_value = self.entries
|
||||
self.usb.empty.return_value = True
|
||||
self.usb.generation.return_value = {'address': 1}
|
||||
self.usb.outcome.return_value = {'idVendor': '0000', 'idProduct': '0001', 'product': 'Synthetic'}
|
||||
|
||||
def sleep(self, seconds): self.clock += seconds
|
||||
|
||||
def run_recovery(self, ports=None):
|
||||
return recovery.recover(self.usb, self.state, 'boot', ports or ['usb1-port2'], lambda: self.clock, self.sleep)
|
||||
|
||||
def test_pair_is_attempted_only_once_and_restored_before_enumeration_check(self):
|
||||
result = self.run_recovery(['usb1-port2', 'usb2-port2'])
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertEqual(result[0]['state'], 'enumerated')
|
||||
self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False])
|
||||
self.assertFalse((self.state/'pending.json').exists())
|
||||
|
||||
def test_second_disable_failure_restores_both_and_keeps_failure_detail(self):
|
||||
def write(entry, disabled):
|
||||
if disabled and entry['name'] == 'usb2-port2': raise OSError('failed second write')
|
||||
self.usb.write.side_effect = write
|
||||
result = self.run_recovery()
|
||||
self.assertIn('failed second write', result[0]['reason'])
|
||||
self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False])
|
||||
self.assertFalse((self.state/'pending.json').exists())
|
||||
|
||||
def test_termination_during_off_period_restores_ports(self):
|
||||
def interrupted(_): raise InterruptedError('stop')
|
||||
result = recovery.recover(self.usb, self.state, 'boot', ['usb1-port2'], lambda: self.clock, interrupted)
|
||||
self.assertIn('stop', result[0]['reason'])
|
||||
self.assertFalse((self.state/'pending.json').exists())
|
||||
self.assertEqual([c.args[1] for c in self.usb.write.call_args_list], [True, True, False, False])
|
||||
|
||||
def test_restore_failure_preserves_pending_and_stops_other_ports(self):
|
||||
def write(_, disabled):
|
||||
if not disabled: raise OSError('restore failed')
|
||||
self.usb.write.side_effect = write
|
||||
result = self.run_recovery(['usb1-port2', 'usb1-port3'])
|
||||
self.assertEqual(result[0]['state'], 'restore_failed')
|
||||
self.usb.plan.assert_called_once()
|
||||
self.assertTrue((self.state/'pending.json').exists())
|
||||
self.usb.write.side_effect = None
|
||||
recovery.restore(self.usb, self.state, 'boot')
|
||||
self.assertFalse((self.state/'pending.json').exists())
|
||||
|
||||
def test_slow_planning_cannot_start_a_late_reset(self):
|
||||
def plan(_): self.clock = 179; return self.entries
|
||||
self.usb.plan.side_effect = plan
|
||||
result = self.run_recovery()
|
||||
self.assertIn('deadline', result[0]['reason'])
|
||||
self.usb.write.assert_not_called()
|
||||
|
||||
def test_failed_enumeration_has_no_repeated_power_loop(self):
|
||||
self.usb.outcome.return_value = None
|
||||
result = self.run_recovery()
|
||||
self.assertEqual(result[0]['state'], 'retried')
|
||||
self.assertEqual(self.clock, 39)
|
||||
self.assertEqual(self.usb.write.call_count, 4)
|
||||
|
||||
def test_previous_boot_pending_state_cannot_address_current_ports(self):
|
||||
recovery.atomic(self.state/'pending.json', {'boot_id': 'old', 'ports': self.entries})
|
||||
with self.assertRaises(OSError): recovery.restore(self.usb, self.state, 'new')
|
||||
self.usb.write.assert_not_called()
|
||||
|
||||
def test_boot_wait_occurs_before_journal_snapshot_and_second_run_preserves_report(self):
|
||||
boot_file = self.state/'boot-id'; boot_file.write_text('boot')
|
||||
self.clock = 5
|
||||
def journal():
|
||||
self.assertGreaterEqual(self.clock, recovery.MIN_AGE)
|
||||
return []
|
||||
with patch.object(recovery, 'STATE', self.state), patch.object(recovery, 'BOOT_ID', boot_file), \
|
||||
patch.object(recovery, 'state_directory'), patch.object(recovery, 'enabled'), \
|
||||
patch.object(recovery.os, 'geteuid', return_value=0), patch.object(recovery.sys, 'argv', ['helper']), \
|
||||
patch.object(recovery.time, 'monotonic', side_effect=lambda: self.clock), \
|
||||
patch.object(recovery.time, 'sleep', side_effect=self.sleep), \
|
||||
patch.object(recovery, 'journal', side_effect=journal) as read, patch('builtins.print'):
|
||||
self.assertEqual(recovery.main(), 0)
|
||||
first = (self.state/'result.json').read_bytes()
|
||||
self.assertEqual(recovery.main(), 0)
|
||||
self.assertEqual((self.state/'result.json').read_bytes(), first)
|
||||
read.assert_called_once()
|
||||
|
||||
def test_late_service_start_cannot_read_or_reset_ports(self):
|
||||
boot_file = self.state/'boot-id'; boot_file.write_text('boot')
|
||||
with patch.object(recovery, 'STATE', self.state), patch.object(recovery, 'BOOT_ID', boot_file), \
|
||||
patch.object(recovery, 'state_directory'), patch.object(recovery.os, 'geteuid', return_value=0), \
|
||||
patch.object(recovery.sys, 'argv', ['helper']), patch.object(recovery.time, 'monotonic', return_value=200), \
|
||||
patch.object(recovery, 'journal') as read, patch.object(recovery, 'recover') as reset, patch('builtins.print'):
|
||||
self.assertEqual(recovery.main(), 0)
|
||||
read.assert_not_called(); reset.assert_not_called()
|
||||
self.assertEqual(json.loads((self.state/'result.json').read_text())['reason'], 'Outside startup window')
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1 @@
|
||||
{"schema":"missioncore.node.usb-startup-policy/v1","enabled":true,"mode":"terminal-enumeration-failures"}
|
||||
@@ -0,0 +1,332 @@
|
||||
"""One bounded boot-time retry of failed USB enumeration; no device commands.
|
||||
|
||||
Only root's fixed systemd job may apply. No request supplies a path or command.
|
||||
Healthy ports (including USB3 companions) and non-individual-power hubs are
|
||||
excluded. The application still identifies controllers by firmware UUID.
|
||||
"""
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
STATE = Path('/run/mission-core-usb-startup')
|
||||
BOOT_ID = Path('/proc/sys/kernel/random/boot_id')
|
||||
POLICY = Path('/etc/mission-core-node/usb-startup.json')
|
||||
EXPECTED_POLICY = {'schema': 'missioncore.node.usb-startup-policy/v1', 'enabled': True,
|
||||
'mode': 'terminal-enumeration-failures'}
|
||||
BOOT_WINDOW = 180
|
||||
FAILURE_WINDOW = 60
|
||||
MIN_AGE = 30
|
||||
BUDGET = 90
|
||||
PORT = re.compile(r'(usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*)-port([1-9][0-9]*)')
|
||||
FAILURE = re.compile(r'usb ((?:usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*)-port[1-9][0-9]*): unable to enumerate USB device')
|
||||
|
||||
|
||||
def child_name(port):
|
||||
match = PORT.fullmatch(port)
|
||||
if not match:
|
||||
raise ValueError('Invalid USB port')
|
||||
hub, number = match.groups()
|
||||
return hub[3:] + '-' + number if hub.startswith('usb') else hub + '.' + number
|
||||
|
||||
|
||||
def failed_ports(records):
|
||||
"""Ignore failures superseded by a later connection/disconnection event."""
|
||||
failures, changes = {}, {}
|
||||
for entry in sorted(records, key=lambda r: int(r.get('__MONOTONIC_TIMESTAMP', 0))):
|
||||
if entry.get('_TRANSPORT') != 'kernel':
|
||||
continue
|
||||
stamp = int(entry.get('__MONOTONIC_TIMESTAMP', 0)) / 1000000
|
||||
message = entry.get('MESSAGE', '')
|
||||
if not isinstance(message, str):
|
||||
continue
|
||||
match = FAILURE.fullmatch(message)
|
||||
if match and 0 < stamp <= FAILURE_WINDOW:
|
||||
failures[match[1]] = stamp
|
||||
match = re.match(r'usb ([0-9]+-[0-9]+(?:\.[0-9]+)*): (?:new |New USB device found|USB disconnect)', message)
|
||||
if match:
|
||||
changes[match[1]] = stamp
|
||||
return [p for p, stamp in sorted(failures.items()) if changes.get(child_name(p), 0) <= stamp]
|
||||
|
||||
|
||||
def run(args):
|
||||
try:
|
||||
result = subprocess.run(args, capture_output=True, text=True, timeout=5,
|
||||
env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C'})
|
||||
except subprocess.SubprocessError as error:
|
||||
raise OSError('USB inspection command timed out or failed') from error
|
||||
if result.returncode or len(result.stdout) > 2 * 1024**2:
|
||||
raise OSError('USB inspection command failed')
|
||||
return result.stdout
|
||||
|
||||
|
||||
def journal():
|
||||
raw = run(['/usr/bin/journalctl', '-k', '-b', '0', '--no-pager', '-o', 'json', '-n', '2000',
|
||||
'--grep=unable to enumerate USB device|new .* USB device|New USB device found|USB disconnect'])
|
||||
return [json.loads(line) for line in raw.splitlines()]
|
||||
|
||||
|
||||
def atomic(path, value):
|
||||
temporary = path.with_suffix('.tmp')
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, sort_keys=True)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
class USB:
|
||||
def __init__(self, root=Path('/sys/bus/usb/devices'), physical=Path('/sys/devices')):
|
||||
self.root, self.physical = root, physical.resolve()
|
||||
|
||||
def resolve(self, name):
|
||||
match = PORT.fullmatch(name)
|
||||
if not match:
|
||||
raise ValueError('Invalid port name')
|
||||
hub = match[1]
|
||||
interface = hub[3:] + '-0' if hub.startswith('usb') else hub
|
||||
paths = list(self.root.glob(interface + ':*/' + name))
|
||||
if len(paths) != 1:
|
||||
raise OSError('USB port topology unavailable')
|
||||
path = paths[0].resolve(strict=True)
|
||||
if not path.is_relative_to(self.physical) or path.name != name:
|
||||
raise OSError('USB port outside sysfs devices')
|
||||
return path
|
||||
|
||||
def generation(self, name):
|
||||
hub = self.root / PORT.fullmatch(name)[1]
|
||||
if (hub / 'bDeviceClass').read_text().strip() != '09':
|
||||
raise OSError('Parent is not a USB hub')
|
||||
return {'bus': int((hub / 'busnum').read_text()), 'address': int((hub / 'devnum').read_text()),
|
||||
'path': str(hub.resolve(strict=True)), 'inode': hub.stat().st_ino}
|
||||
|
||||
def empty(self, name):
|
||||
p = self.resolve(name)
|
||||
return (not os.path.lexists(p / 'device') and
|
||||
(p / 'state').read_text().strip() == 'not attached' and
|
||||
(p / 'disable').read_text().strip() == '0' and
|
||||
(p / 'over_current_count').read_text().strip() == '0' and
|
||||
(p / 'connect_type').read_text().strip() in ('hotplug', 'unknown'))
|
||||
|
||||
def companions(self, name):
|
||||
p = self.resolve(name)
|
||||
names = [name]
|
||||
if os.path.lexists(p / 'peer'):
|
||||
peer = (p / 'peer').resolve(strict=True)
|
||||
if not peer.is_relative_to(self.physical) or self.resolve(peer.name) != peer:
|
||||
raise OSError('USB companion topology changed')
|
||||
if (peer / 'peer').resolve(strict=True) != p:
|
||||
raise OSError('USB companion is not reciprocal')
|
||||
names.append(peer.name)
|
||||
return names
|
||||
|
||||
def individual_power(self, name):
|
||||
before = self.generation(name)
|
||||
raw = run(['/usr/bin/lsusb', '-v', '-s', f"{before['bus']:03}:{before['address']:03}"])
|
||||
characteristics = re.findall(r'^\s*wHubCharacteristic[s]?\s+0x([0-9a-fA-F]+)\s*$', raw, re.M)
|
||||
return (before == self.generation(name) and len(characteristics) == 1 and
|
||||
int(characteristics[0], 16) & 3 == 1)
|
||||
|
||||
def plan(self, name):
|
||||
names = self.companions(name)
|
||||
entries = [{'name': n, 'generation': self.generation(n)} for n in names]
|
||||
# Test every companion before querying hub descriptors or opening any port.
|
||||
if not all(self.empty(n) for n in names):
|
||||
raise OSError('Port or USB companion already attached, disabled, internal or over-current')
|
||||
if not all(self.individual_power(n) for n in names):
|
||||
raise OSError('Individual USB port power switching is not confirmed')
|
||||
if any(self.generation(e['name']) != e['generation'] for e in entries):
|
||||
raise OSError('USB hub changed during companion inspection')
|
||||
return entries
|
||||
|
||||
def write(self, entry, disabled):
|
||||
name = entry['name']
|
||||
if self.generation(name) != entry['generation']:
|
||||
raise OSError('USB hub generation changed')
|
||||
if disabled and not self.empty(name):
|
||||
raise OSError('USB port became occupied')
|
||||
p = self.resolve(name) / 'disable'
|
||||
# Pending state is durable before the first write. An interrupted or
|
||||
# rejected first write must not cause a redundant enable on a port
|
||||
# which has since successfully enumerated.
|
||||
if not disabled and p.read_text().strip() == '0':
|
||||
return
|
||||
fd = os.open(p, os.O_WRONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
if self.generation(name) != entry['generation'] or (disabled and not self.empty(name)):
|
||||
raise OSError('USB topology changed before write')
|
||||
if os.write(fd, b'1\n' if disabled else b'0\n') != 2:
|
||||
raise OSError('Incomplete USB port write')
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def outcome(self, name):
|
||||
p = self.resolve(name)
|
||||
if not (p / 'device').exists():
|
||||
return None
|
||||
child = (p / 'device').resolve(strict=True)
|
||||
if not child.is_relative_to(self.physical):
|
||||
raise OSError('Unexpected USB child')
|
||||
return {key: (child / key).read_text().strip() for key in ('idVendor', 'idProduct', 'product')}
|
||||
|
||||
|
||||
def restore(usb, state, boot):
|
||||
p = state / 'pending.json'
|
||||
if not p.exists():
|
||||
return
|
||||
pending = json.loads(p.read_text())
|
||||
if pending['boot_id'] != boot:
|
||||
raise OSError('Pending recovery belongs to another boot')
|
||||
errors = []
|
||||
for entry in reversed(pending['ports']):
|
||||
try:
|
||||
usb.write(entry, False)
|
||||
except OSError as error:
|
||||
errors.append(str(error))
|
||||
if errors:
|
||||
raise OSError('; '.join(errors))
|
||||
p.unlink()
|
||||
|
||||
|
||||
def recover(usb, state, boot, candidates, now=time.monotonic, sleep=time.sleep):
|
||||
deadline = min(now() + BUDGET, BOOT_WINDOW)
|
||||
results, processed = [], set()
|
||||
for name in candidates[:32]:
|
||||
if name in processed:
|
||||
continue
|
||||
item = {'port': name, 'state': 'skipped'}
|
||||
results.append(item)
|
||||
if now() + 12 >= deadline:
|
||||
item['reason'] = 'Boot recovery deadline reached'
|
||||
break
|
||||
try:
|
||||
entries = usb.plan(name)
|
||||
if now() + 12 >= deadline:
|
||||
raise OSError('Boot recovery deadline reached during planning')
|
||||
# Recheck all companions after descriptor reads and before any write.
|
||||
if not all(usb.empty(e['name']) and usb.generation(e['name']) == e['generation'] for e in entries):
|
||||
raise OSError('USB port changed during planning')
|
||||
processed.update(e['name'] for e in entries)
|
||||
item['ports'] = [e['name'] for e in entries]
|
||||
atomic(state / 'pending.json', {'boot_id': boot, 'ports': entries})
|
||||
try:
|
||||
for entry in entries:
|
||||
usb.write(entry, True)
|
||||
sleep(1)
|
||||
finally:
|
||||
restore(usb, state, boot)
|
||||
item['state'] = 'retried'
|
||||
until = min(now() + 8, deadline)
|
||||
while now() < until:
|
||||
result = usb.outcome(name)
|
||||
if result:
|
||||
item.update(state='enumerated', descriptor=result)
|
||||
break
|
||||
sleep(0.25)
|
||||
except (OSError, ValueError) as error:
|
||||
item['reason'] = str(error)
|
||||
if (state / 'pending.json').exists():
|
||||
item['state'] = 'restore_failed'
|
||||
break
|
||||
return results
|
||||
|
||||
|
||||
def state_directory():
|
||||
STATE.mkdir(mode=0o755, exist_ok=True)
|
||||
info = STATE.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
|
||||
raise OSError('Untrusted recovery state directory')
|
||||
|
||||
|
||||
def enabled():
|
||||
info = POLICY.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 or info.st_size > 1024:
|
||||
raise OSError('Untrusted startup recovery policy')
|
||||
if json.loads(POLICY.read_text()) != EXPECTED_POLICY:
|
||||
raise OSError('Startup recovery policy is not supported')
|
||||
|
||||
|
||||
def inspect(usb):
|
||||
hubs = []
|
||||
deadline = time.monotonic() + 60
|
||||
for p in sorted(usb.root.glob('*')):
|
||||
if time.monotonic() >= deadline or len(hubs) >= 16:
|
||||
break
|
||||
if not re.fullmatch(r'usb[1-9][0-9]*|[1-9][0-9]*-[1-9][0-9]*(?:\.[1-9][0-9]*)*', p.name):
|
||||
continue
|
||||
try:
|
||||
if (p / 'bDeviceClass').read_text().strip() != '09':
|
||||
continue
|
||||
hubs.append({'hub': p.name, 'individual_power': usb.individual_power(p.name + '-port1')})
|
||||
except OSError as error:
|
||||
hubs.append({'hub': p.name, 'error': str(error)})
|
||||
return hubs
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() != 0 or sys.argv[1:] not in ([], ['--inspect'], ['--restore']):
|
||||
raise ValueError('Fixed root-owned startup job only')
|
||||
mode = sys.argv[1:] or ['apply']
|
||||
state_directory()
|
||||
lock = os.open(STATE / 'lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
boot = BOOT_ID.read_text().strip()
|
||||
usb = USB()
|
||||
if mode == ['--restore']:
|
||||
try:
|
||||
restore(usb, STATE, boot)
|
||||
finally:
|
||||
os.close(lock)
|
||||
return 0
|
||||
if mode == ['apply'] and (STATE / 'attempted').exists():
|
||||
# Preserve the first result, including restore failures, across a later
|
||||
# daemon/package restart. Recovery is never retriggered by refresh.
|
||||
try:
|
||||
restore(usb, STATE, boot)
|
||||
finally:
|
||||
os.close(lock)
|
||||
return 0
|
||||
report = {'schema': 'missioncore.node.usb-startup-recovery/v1', 'boot_id': boot,
|
||||
'observed_at_unix': time.time(), 'boot_seconds': time.monotonic(),
|
||||
'mode': mode[0], 'state': 'skipped', 'results': []}
|
||||
destination = STATE / ('inspection.json' if mode == ['--inspect'] else 'result.json')
|
||||
try:
|
||||
if mode == ['--inspect']:
|
||||
report['hubs'] = inspect(usb)
|
||||
report['state'] = 'inspected'
|
||||
elif time.monotonic() >= BOOT_WINDOW:
|
||||
report['reason'] = 'Outside startup window'
|
||||
else:
|
||||
enabled()
|
||||
atomic(STATE / 'attempted', {'boot_id': boot})
|
||||
restore(usb, STATE, boot)
|
||||
# udev-settle can return before the hub driver's delayed retries
|
||||
# give up. Wait before taking the first snapshot, including when
|
||||
# the journal currently contains no terminal failure yet.
|
||||
time.sleep(max(0, MIN_AGE - time.monotonic()))
|
||||
candidates = failed_ports(journal())
|
||||
if candidates:
|
||||
report['results'] = recover(usb, STATE, boot, candidates)
|
||||
report['state'] = 'complete'
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
||||
report.update(state='error', reason=str(error))
|
||||
finally:
|
||||
atomic(destination, report)
|
||||
destination.chmod(0o644)
|
||||
os.close(lock)
|
||||
print(json.dumps(report, sort_keys=True))
|
||||
return 1 if report['state'] == 'error' or any(r['state'] == 'restore_failed' for r in report['results']) else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
def interrupted(*_):
|
||||
raise InterruptedError('Startup recovery interrupted')
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
sys.exit(main())
|
||||
@@ -1,8 +1,13 @@
|
||||
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
|
||||
import {xgridsK1SensorUi} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin';
|
||||
import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin';
|
||||
import {createIsolatedRerunHost} from '../../../control-station/src/components/rerun/isolatedRerunHost';
|
||||
import {SensorWorkspace} from '../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||
import type {SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {request} from './api';
|
||||
const transport:SensorTransport={localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))};
|
||||
export function NodeSensors(){return <SensorWorkspace contributions={[xgridsK1SensorUi,insta360X4SensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>;}
|
||||
import {request,type Status} from './api';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
import {createBoardLayoutStore} from '../../../../packages/sensor-ui/src/boardLayout';
|
||||
const layout=createBoardLayoutStore({read:()=>request('/api/presentation/board-layout'),patch:(section,open)=>request('/api/presentation/board-layout','PATCH',{section,open})});
|
||||
const configurationArchive:NonNullable<SensorTransport['configurationArchive']>={list:(device,before)=>request(`/api/device-configurations/${encodeURIComponent(device)}${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>request(`/api/device-configurations/${encodeURIComponent(device)}/${encodeURIComponent(version)}`)};
|
||||
const transport:SensorTransport={configurationArchive,localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))};
|
||||
export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return <SensorWorkspace board={{layout,description:value.name,computer:<SettingsCard title={value.name} description={value.host.hostname}><dl className="node-facts"><div><dt>Бортовой компьютер</dt><dd>{value.node_id}</dd></div><div><dt>Операционная система</dt><dd>{value.host.os}</dd></div><div><dt>Архитектура</dt><dd>{value.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{value.host.cpus}</dd></div><div><dt>Память</dt><dd>{value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}</dd></div><div><dt>Mission Core Node</dt><dd>{value.version}</dd></div></dl><Button onClick={openSettings}><Icon name="settings"/>Подготовка среды</Button></SettingsCard>}} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>;}
|
||||
|
||||
@@ -38,7 +38,7 @@ function App() {
|
||||
function openView(id: ViewId) { if(environment.running) return; setAdding(false); setRoot(views.find(item => item.id === id)!.root); workspace.openView(id); }
|
||||
function selectRoot(id: RootId) { const first = roots.find(item => item.id === id)!.first; if (first) openView(first); }
|
||||
const content = !value ? null : workspace.activeView === "environment" ? <EnvironmentView environment={environment} failure={failure} success={node.success} /> : workspace.activeView === "overview" ? <NodeOverview value={value} refresh={refresh} failure={failure} openView={openView} />
|
||||
: workspace.activeView === "sensors" ? <NodeSensors />
|
||||
: workspace.activeView === "sensors" ? <NodeSensors value={value} openSettings={()=>openView("environment")} />
|
||||
: workspace.activeView === "network" ? <NetworkView value={value} />
|
||||
: workspace.activeView === "usb" ? <USBView value={value} />
|
||||
: workspace.activeView === "core" ? <CoreConnectionView failure={failure} />
|
||||
|
||||
@@ -353,3 +353,17 @@ Before A3 or any subsequent LAB UI change:
|
||||
7. visually inspect normal and expanded modes at representative viewport sizes.
|
||||
8. verify every bounded `ENNResult.tsx` uses the v1 summary and result
|
||||
components without raw canonical report markup.
|
||||
|
||||
|
||||
## Hardware synchronization feedback — owner requirement, 2026-09-25
|
||||
|
||||
When an operator action must wait for equipment synchronization, preparation
|
||||
or completion of a previous operation, show its current phase next to the
|
||||
action using canonical status components. Do not silently disable the entry
|
||||
point or present an unexplained frozen control. Keep settings accessible;
|
||||
gate the actual hardware action on readiness and explain the reason.
|
||||
A busy phase uses the canonical warning status; confirmed readiness alone
|
||||
uses success. Missing/stale data or failure must say so, never imply endless
|
||||
active synchronization. Status follows real lifecycle responses, not a timer
|
||||
that pretends completion. This is an application-wide interaction requirement;
|
||||
other equipment workflows need their own lifecycle verification.
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
# AI-полигон: отдельный профиль Gaussian / Isaac
|
||||
|
||||
Этот документ фиксирует первый интеграционный этап. Текущее состояние UI,
|
||||
две скачанные локации, исправление Stop и измерения полного цикла описаны в
|
||||
[операторской ревизии](2026-09-21-ai-polygon-operator-revision.md).
|
||||
Действующий release — `0af432ce95816402`; результаты старых release ниже
|
||||
сохранены как история экспериментов.
|
||||
|
||||
Решение владельца: лабораторная симуляция с виртуальным дифференциальным ровером,
|
||||
камерой и существующими AI-моделями на Worker 006. Работа с VESC/ASVD, физическими
|
||||
аппаратами и перенос inference на борт в этот этап не входит. World Labs исключён.
|
||||
Основной источник визуальных миров — скачиваемые Gaussian-сканы с явной лицензией.
|
||||
|
||||
## Продуктовая поверхность
|
||||
|
||||
Оператор открывает «Симуляции», выбирает профиль, импортирует локацию, проверяет её
|
||||
ориентацию, масштаб, высоту грунта и старт, затем наблюдает камеру и решения AI.
|
||||
Выбран существующий workspace с верхним Select профиля: это прямое решение
|
||||
владельца. Альтернатива — новый workspace/пункт главной навигации — разделила бы
|
||||
одну операторскую работу между разными поверхностями. Нового продуктового корня
|
||||
или элемента Design Guideline нет: используются существующие Select, Window,
|
||||
GlassSurface, Button, IconButton, StatusBadge, LoadingRegion и ToastStack.
|
||||
|
||||
LCC Gaussian Mirror сохраняет прежний renderer, каталог и pipeline. AI-полигон
|
||||
имеет отдельные world/run namespaces. Старый lab-archive скрыт из обычной
|
||||
навигации; сохранённые быстрые действия переводятся на AI Inference. Исторические
|
||||
данные, пакеты моделей и контейнеры не удаляются.
|
||||
|
||||
Состояния: пустая библиотека → загрузка/возобновление → проверка локации →
|
||||
подготовленная локация; simulator disconnected/connected; starting, running,
|
||||
paused, stopping, completed/stopped/failed. Камера и просмотр локации имеют
|
||||
expand/restore; перед первым кадром показывается ожидание, а не фиктивное видео.
|
||||
|
||||
## Существующий Worker
|
||||
|
||||
Изучены Ops MISSIONCOR-75 «AI Inference · Принципы работы и архитектура»,
|
||||
MISSIONCOR-73, прежние материалы Worker и фактический Docker Desktop Windows.
|
||||
Активная modular generation — observatory-ai-modules/20260904-v14. Это выполнение
|
||||
записанных задач; уже работающий основной Triton не содержит DDRNet/RF-DETR.
|
||||
Логический image digest модуля отличается от component image установленного
|
||||
пакета: профиль использует фактически установленные component images.
|
||||
|
||||
До изменений: 21 контейнер, 8 запущены, 108 образов, 9 volumes; RTX 4090 24 GiB,
|
||||
driver 610.47. Сохранены ID, mounts, ports и package bindings без переменных
|
||||
окружения/токенов в private outputs этой задачи. Прежние контейнеры, Compose,
|
||||
модельные конфигурации, immutable releases, source-CAS и rollback не изменяются.
|
||||
Исправлен устаревший DNS только в существующем SSH-профиле mission-gpu, с резервной
|
||||
копией и сохранением проверки host key.
|
||||
|
||||
## Новый runtime
|
||||
|
||||
На Windows используется официальный native Isaac Sim 6.1.0. Его Docker/Web Viewer
|
||||
вариант не выбран: официальный Compose Web Viewer не поддерживает Windows/WSL.
|
||||
Архив 10 370 228 313 bytes проверен vendor MD5 и локальным SHA-256
|
||||
`dc7cfc966cd0aea105e97bb1b9b30a8e91306a3254f231bca9caa5c97ae74ae9`.
|
||||
Подготовка находится только в `D:\NDC_MISSIONCORE\runtime\simulation`;
|
||||
драйвер, PATH и существующие services не менялись.
|
||||
|
||||
Два новых временных Docker service запускаются один раз на episode:
|
||||
|
||||
- DDRNet: исходная PyTorch-модель GOOSE из установленного component image,
|
||||
checkpoint, preprocessing runner и таблица классов сверяются по SHA-256.
|
||||
- RF-DETR: сохранённый стандартный FP16 TensorRT engine с входом 704×704.
|
||||
Это отдельный pinhole-профиль, без KB4 valid-FOV mask. Действующий native-KB4
|
||||
пакет AI Inference не подменяется.
|
||||
|
||||
Найденный DDRNet TensorRT export не допущен: его сохранённая проверка показывает
|
||||
4 009 отличающихся пикселей на 128 кадрах и пометку experimental-unqualified.
|
||||
Полная декларация нового профиля — `simulation/ai-polygon/models.worker-006.json`.
|
||||
Новый Compose использует ndc- namespace, labels и loopback 18091/18092; mounts
|
||||
weights/configs read-only. Новые images/volumes не создаются и старые не чистятся.
|
||||
|
||||
Core выдаёт GPU reservation через существующую SQLite очередь AI Inference до
|
||||
запуска native simulator и моделей. Потеря heartbeat прекращает episode и не
|
||||
считает GPU автоматически свободным. Release принимается после выхода Isaac
|
||||
и удаления собственных временных model containers по точным ID. Не завершённый
|
||||
active.json требует reconciliation; старые команды автоматически не повторяются.
|
||||
|
||||
## Камера, движение и доказательства
|
||||
|
||||
Core ↔ Worker использует отдельный SSH reverse forward на Windows loopback 18081,
|
||||
Bearer credential нового профиля; существующий Observatory 18080 не меняется.
|
||||
Credential хранится mode 0600 на Mac и с owner-only ACL на Worker.
|
||||
|
||||
Сцена импортируется штатным NVIDIA `omni.kit.converter.gsplat` 0.1.16 из Isaac.
|
||||
Робот — готовый Jetbot и DifferentialController. Это проверка дифференциального
|
||||
управления в симуляции, а не цифровой двойник конкретного ровера пользователя.
|
||||
Восемь штатных USD-зависимостей Jetbot (31 942 456 bytes) подготовлены отдельным
|
||||
`Prepare-RobotAssets.ps1`: повторный запуск больше не ждёт сетевой загрузки робота.
|
||||
Перед регистрацией Worker сверяет все файлы с локальным SHA-256 manifest.
|
||||
Трава — только визуальные splats. Начальный физический ground — скрытая плоскость;
|
||||
рельеф, сцепление и сгибание растительности этим не моделируются.
|
||||
|
||||
Каждый шаг: новая камера RGB → DDRNet + RF-DETR → RoadPolicy → журнал решения →
|
||||
speed/yaw-rate → 6 физических тактов по 1/60 с → отдельное подтверждение pose/time.
|
||||
Физика не должна идти во время inference или рендера. Проверяется счётчик шагов.
|
||||
Позы физического движка используются для размещения камеры и диагностики,
|
||||
не передаются в RoadPolicy. Сохраняются кадры с SHA-256, decisions.jsonl,
|
||||
motion.jsonl, snapshot локации/профиля и терминальный результат.
|
||||
|
||||
RoadPolicy — начальный camera-only follower: видимый связный участок дороги,
|
||||
остановка при препятствии/отсутствии дороги и три свободных кадра до возобновления.
|
||||
Это не Nav2, не метрическая оценка дистанции и не доказанный объезд препятствий.
|
||||
Динамические люди/животные, тормозной путь, обход и повторы/coverage должны
|
||||
проверяться отдельными сценариями. Первый природный проезд описан ниже.
|
||||
|
||||
## Фактически выполненная проверка
|
||||
|
||||
Первый bounded native probe: настоящий RTX RGB 800×600 → обе реальные модели.
|
||||
Inference 156 / 78 / 79 ms на трёх одинаковых технических кадрах; решение no-road,
|
||||
нулевая команда. Пауза не увеличила счётчик физики; явный step увеличил его на 6.
|
||||
Это не FPS benchmark и не navigation acceptance. После probe подтверждено
|
||||
отсутствие его kit process и model containers, сохранены прежние 21 container ID.
|
||||
|
||||
Локально: 69 backend tests по lifecycle/импорту/shared queue; дополнительно 51
|
||||
проверка существующих AI Inference/LCC; 888 frontend tests до последнего малого
|
||||
изменения ярлыка, затем 7 focused environment tests; production build и Ruff.
|
||||
Браузером проверены оба профиля, прежние три LCC-локации, сохранение профиля,
|
||||
форма импорта, сворачивание окна, отсутствие legacy в обычной навигации.
|
||||
|
||||
Первый полный PLY episode выявил отсутствие нового Python API
|
||||
UsdVol.ParticleField3DGaussianSplat в bundled USD Isaac; заменён на штатный
|
||||
совместимый GSplat Converter. Следующая попытка зависла на внешнем stock USD
|
||||
робота и была завершена ограниченным таймаутом; поэтому зависимости сохранены
|
||||
локально. Полный episode `airun-de5fdd342cff4d8994b0016ded5348f0` завершился с
|
||||
3 samples / 3 applied steps / 18 физических тактов. Просмотр кадра выявил поворот
|
||||
камеры; исправлен world-to-camera look-at transform, не изменяя модели.
|
||||
|
||||
Повтор `airun-6dc2d164cde04c70bec3348486bd63cc` использует исправленную камеру:
|
||||
на изображении подтверждён горизонтальный грунт. Пауза удержала 4 applied steps,
|
||||
один шаг увеличил счётчик строго до 5, Stop завершил прогон. Это 0.5 секунды
|
||||
симуляции, все решения no-road, скорость 0.0. Проверенный release
|
||||
`84302295451de631`, archive SHA-256
|
||||
`440f6241af119ac9f63df94a68c99e2d7b724f0796dd999f12d23586a0b117b3`.
|
||||
Совместная команда launcher+tunnel также проверена: отдельный episode остановлен
|
||||
во время подготовки с нулём кадров и корректным освобождением ресурсов.
|
||||
|
||||
После GPU-проверок сохранён private `worker-preservation-report.json`: тот же
|
||||
набор всех 21 container ID, без изменений image/status/restart/mounts/ports;
|
||||
те же 108 image identities/tags и 9 volumes. Временных simulation processes нет.
|
||||
Сравнение mounts нормализовано по Destination, поскольку Docker меняет порядок
|
||||
их перечисления. Существующие конфигурационные файлы моделей не изменены.
|
||||
|
||||
Запуск и аварийное восстановление описаны в
|
||||
`docs/runbooks/AI_POLYGON_WORKER_006.md`. Автоматический постоянный service не
|
||||
устанавливался: coordinator запускается одной foreground-командой, idle не
|
||||
занимает GPU. Глобальная эксклюзивность относительно отдельного Gaussian pipeline
|
||||
не доказана; его задачи нельзя выполнять параллельно с этим профилем.
|
||||
|
||||
## Природный мир Forest Scan
|
||||
|
||||
После входа владельца в SuperSplat получен Forest Scan, Joshua Trapani (draftmode),
|
||||
[источник](https://superspl.at/scene/259c0051), CC BY 4.0. Автор и лицензия
|
||||
проверены по Download UI и `license.txt` экспортируемого архива. Browser export
|
||||
оборвался; разрешённые публичные SOG assets той же сцены сохранены versioned
|
||||
`fetch_sog.py` с SHA-256 manifest. Credentials/cookies не извлекались.
|
||||
|
||||
Исходные SOG/WebP assets занимают 31 446 214 bytes. Официальный
|
||||
`@playcanvas/splat-transform` 3.4.0 подготовлен `Prepare-SplatTools.ps1` в отдельном
|
||||
simulation/tools с pinned package-lock; глобальные npm/system settings не менялись.
|
||||
Конвертация дала стандартный PLY: 2 142 439 splats, 505 617 082 bytes,
|
||||
SHA-256 `432ee329fc75d86b50d0b577542adca579b0749b4939044fc3980f27b2618ece`.
|
||||
PLY импортирован через штатный возобновляемый API и повторно проверен Worker.
|
||||
В библиотеке доступен `aiworld-689fce22369f41158ffd1030bad35c0a`.
|
||||
На момент первого этапа Bamboo Trail ещё не был загружен. В последующей
|
||||
операторской ревизии он скачан, импортирован и проверен реальным episode.
|
||||
|
||||
Авторская камера и фактическое преобразование viewer сопоставлены с Isaac Z-up:
|
||||
rotation [-90, 0, 180], spawn [0.522299, -0.517838], heading 137.690214°,
|
||||
ground Z -0.065, camera height 0.8, max speed 0.15. Масштаб 1 unit = 1 m принят
|
||||
условно: метрическая калибровка по измеренному объекту ещё не выполнена.
|
||||
|
||||
Короткий episode `airun-5ff180262220435faa39a814260dae7b` дал 5 samples / 5 applied
|
||||
и ненулевую команду по видимой лесной тропе. Следующий
|
||||
`airun-321bb7cb732b4ab59aee77d60ee978af` завершён: 100 samples / 100 applied /
|
||||
600 physics ticks, 10 секунд времени симуляции. Первые 2 решения uncertain с
|
||||
нулевой скоростью, затем 98 road с движением. Длина траектории по физическим
|
||||
позам — 1.421741 м в принятом масштабе сцены. Inference: min 94, median 156,
|
||||
p95 172, max 296 ms. Проверены последовательность receipts, шаг времени и SHA-256
|
||||
всех 100 кадров. Это latency моделей в lockstep, не FPS реального времени.
|
||||
|
||||
На исходной картинке есть деревянная ступень поперёк тропы. Текущая модель не
|
||||
считала её препятствием; у неё нет collision, поскольку физический ground пока
|
||||
плоский. Поездка подтверждает связку реальная Gaussian-камера → существующие
|
||||
модели → решения → движение, но не безопасное преодоление ступеней, объезд,
|
||||
тормозной путь или реакцию на людей/животных. Такие сценарии остаются открытыми.
|
||||
|
||||
Private evidence: `outputs/ai-polygon-2026-09-21/forest-drive-report.json`,
|
||||
`forest-drive-run.json`, `forest-drive-decisions.jsonl`, `forest-drive-motion.jsonl`,
|
||||
`forest-drive-final.jpg`, source manifest и `worker-preservation-final.json`.
|
||||
После природного episode прежние 21 контейнер / 108 образов / 9 volumes сохранены;
|
||||
свои native processes, временные model containers и active/lock markers очищены.
|
||||
Техническая синтетическая сцена и её 5 прогонов архивированы отдельно от обычной
|
||||
библиотеки; Forest и оба природных результата оставлены оператору.
|
||||
|
||||
Камера результата и preview используют общий fullscreen hook; Escape возвращает
|
||||
обычный размер и не вызывает действие оболочки. Направление preview исправлено:
|
||||
CameraControls получает focus point по стартовому heading, а не центр координат.
|
||||
Полноэкранный лесной preview и Escape проверены после final production build;
|
||||
затем 3D закрыт для освобождения ресурсов Mac. В кадре показаны скорость и
|
||||
поворот, отсутствие кадров после раннего Stop обозначено явно.
|
||||
|
||||
Для операторского handoff оставлен foreground coordinator через `start_worker.py`
|
||||
без `--once`: он поддерживает соединение, но не запускает Isaac/модели до команды
|
||||
в UI. OS service/автозапуск не установлен. Core 8000 оставлен работающим.
|
||||
|
||||
|
||||
## Первичные источники
|
||||
|
||||
- https://docs.isaacsim.omniverse.nvidia.com/6.1.0/installation/download.html
|
||||
- https://docs.isaacsim.omniverse.nvidia.com/6.1.0/installation/install_workstation.html
|
||||
- https://docs.omniverse.nvidia.com/materials-and-rendering/latest/particle-fields.html
|
||||
- https://superspl.at/scene/259c0051
|
||||
- https://superspl.at/scene/dd49e9a8
|
||||
|
||||
Контрольная точка не выдаёт допуск к физическому аппарату. Все команды имеют
|
||||
virtual-only authority; VESC/ASVD adapters отсутствуют.
|
||||
@@ -0,0 +1,142 @@
|
||||
# AI-полигон: операторская ревизия
|
||||
|
||||
## Причина и результат
|
||||
|
||||
Владелец обнаружил реальные дефекты первой поверхности: разделение на «Мои» и
|
||||
«Готовые» локации, внешние синие ссылки вместо подготовленных файлов, автоматически
|
||||
открытый кадр старого прогона, отсутствие видимого ровера и неясное состояние Stop.
|
||||
Техническая связка камеры и моделей ещё не давала удобной наблюдаемой симуляции.
|
||||
|
||||
Теперь библиотека содержит только «Доступные локации»: скачанные Forest Scan и
|
||||
Bamboo Trail с действием «Открыть». Нижний preview, внешний каталог, список
|
||||
исторических кадров и raw links удалены из этой поверхности. Авторство и лицензия
|
||||
сохранены у каждой сцены. LCC Gaussian Mirror и AI Inference остаются отдельными.
|
||||
|
||||
Открытая локация имеет явный заголовок, включая fullscreen. Один viewer переключает
|
||||
«За ровером», «Обзор» и «Камера AI». Первый показывает упрощённый ровер с размерами
|
||||
колёс/колеи Jetbot по фактическим XY/yaw из applied receipt; второй даёт свободный
|
||||
обзор; третий показывает именно RGB из Isaac, переданный моделям. Это не экспорт
|
||||
точной модели Jetbot и не цифровой двойник физического аппарата владельца.
|
||||
Отрисовка интерполирует только уже полученные позы, не вычисляет свои команды или
|
||||
физику и не подменяет кадры inference. В режиме камеры 3D rendering приостановлен.
|
||||
|
||||
Кнопки паузы/шага/Stop и состояние находятся внутри fullscreen viewer. Подготовка
|
||||
показывает стадии мира, моделей и камеры. Stop сначала показывает остановку,
|
||||
после cleanup — «Остановлено · inference выключен». Пауза показывает нулевое
|
||||
движение, без устаревшего показателя скорости. Конечная поза текущего прогона
|
||||
сохраняется; старые прогоны сами в библиотеке не открываются. При отсутствии
|
||||
первого кадра завершённый прогон не продолжает показывать ожидание камеры.
|
||||
|
||||
Использованы существующие Button, IconButton, SegmentedControl, StatusBadge,
|
||||
LoadingRegion, GlassSurface из NODEDC Design Guideline и отдельный domain renderer.
|
||||
Новых продуктовых корней или локальных замен дизайн-компонентов нет.
|
||||
|
||||
## Bamboo Trail
|
||||
|
||||
[Источник](https://superspl.at/scene/dd49e9a8), автор luckysplat, CC BY 4.0.
|
||||
Лицензия и разрешённая загрузка проверены в авторизованном SuperSplat Download UI.
|
||||
Его Source action не дал файл; сохранены публичные assets именно опубликованного
|
||||
viewer и SHA manifest, без извлечения cookies или credentials.
|
||||
|
||||
`fetch_lod.py` выбирает полный опубликованный LOD0 из manifest и архивирует 11 SOG
|
||||
chunks через `fetch_sog.py`. Добавлена обработка gzip JSON. Официальный закреплённый
|
||||
SplatTransform 3.4.0 через `Prepare-Scene.ps1` собрал обычный PLY без перезаписи
|
||||
предыдущего результата; LOD0 содержит 5 818 957 splats, SH degree 0.
|
||||
|
||||
- PLY: 325 861 955 bytes.
|
||||
- SHA-256: `d7f2aad3240cc1a7369eb0d8b0d4c96a9cadbe07ee352c25d297b1037a812824`.
|
||||
- World: `aiworld-7a58431a5551469cbbf0e8a4efef2a8b`.
|
||||
- Rotation [-90, 0, 180], ground Z -2.418, spawn [-0.696364224, -0.696364224],
|
||||
heading 22.55°, camera height 0.8, max speed 0.15, условный scale 1.
|
||||
|
||||
Файл импортирован штатными блоками по 4 MiB, хеш проверен при завершении и на
|
||||
Worker. Native Isaac успешно создал camera RGB; конвертированный USD закеширован.
|
||||
Первый запуск был долгим из-за конвертации 5.8 млн splats. При исходном heading
|
||||
47.55° камера смотрела на край тропы и камни, первые 15 решений были no-road.
|
||||
Heading повёрнут на 25° вдоль видимой тропы, после чего выполнен полный тест ниже.
|
||||
|
||||
## Причины задержки и сбоя Stop
|
||||
|
||||
В пользовательском `airun-2b1d079ab6b04df3a39019d664c75329` фактически выполнено
|
||||
54 samples / 54 applied. Native process завершился одновременно с taskkill;
|
||||
его exit code 255 был ошибочно принят coordinator как сбой. Isaac и временные
|
||||
модельные контейнеры уже отсутствовали, но UI получил failed вместо stopped.
|
||||
|
||||
`worker.py` теперь ожидает действительное завершение дочернего процесса и допускает
|
||||
гонку с уже вышедшим процессом. После cleanup он заново читает control/state, чтобы
|
||||
конкурентный Stop не превратился в completed или failed. `model_stack.py` проверяет
|
||||
отмену при подготовке моделей. Core принимает промежуточные стадии подготовки,
|
||||
не объявляя running до первого sample. Reservation освобождается только после
|
||||
завершения native process и удаления собственных container IDs.
|
||||
|
||||
UI ранее опрашивал каталог раз в 1.5 с и пропускал промежуточные кадры; теперь
|
||||
активный прогон опрашивается с интервалом 200 мс, с одним последовательным запросом.
|
||||
Постоянные HTTP connections сокращают повторные TCP handshakes; соединение
|
||||
пересоздаётся после простоя >2 с, чтобы не переиспользовать истёкший server keepalive.
|
||||
Неопределённые mutation requests автоматически не повторяются. RTX subframes: 1.
|
||||
|
||||
Applied receipts получили yaw и измерения полного цикла/render/transport.
|
||||
Physics остаётся lockstep: ровно 100 мс симуляции за решение, 6 ticks по 1/60 с;
|
||||
во время ожидания моделей мир не движется. Плавность browser viewer не означает
|
||||
такую же частоту камеры или решений. Это ещё не realtime 1×.
|
||||
|
||||
## Проверки на Worker
|
||||
|
||||
| Проверка | Фактический результат |
|
||||
| --- | --- |
|
||||
| Forest через UI, `airun-5950929b54754077a3f21ae64ea1e8a5` | 87 samples / 87 applied; stopped |
|
||||
| Пауза Forest | Счётчик удержан на 86 через 1.2 с; один шаг дал строго 87 |
|
||||
| Полный цикл Forest | Медиана 313 мс; render 62 мс; transport до receipt 47 мс; inference 156 мс |
|
||||
| Bamboo, `airun-a10fe72eddca48548ab8ec23e4f59d38` | 120 samples / 120 applied; completed; 26 road, 17 uncertain, 77 no-road |
|
||||
| Полный цикл Bamboo | Медиана 297 мс; inference 156 мс |
|
||||
| Stop во время движения, `airun-9015f6ab095848e78db24b6dcda5045d` | 6 samples / 6 applied; stopped через 2.17 с после запроса |
|
||||
| Stop при загрузке моделей, `airun-1c2c258e1211459dbbfe471a9fb1b958` | 0 samples; stopped; подготовка отменена |
|
||||
| Stop из fullscreen, `airun-e9be1e3e45e84f71862a9c0b7eddcda0` | 0 samples; «Останавливаем…» → «Остановлено · inference выключен» |
|
||||
|
||||
Проверены SHA-256 всех 87 Forest-кадров. Bamboo дал движение, затем остановку
|
||||
при недостатке уверенно распознанной дороги; это не прохождение всей тропы.
|
||||
Полный цикл соответствует примерно 3.2–3.4 решениям/с и 0.32–0.34× simulation time.
|
||||
Ранее указанные 156 мс — только latency моделей, не полный FPS системы.
|
||||
|
||||
Локально: 71 backend test (AI-полигон и shared recorded queue) прошёл, после
|
||||
корректировки starting/running повторены 19 AI-полигон tests. Добавлены регрессии
|
||||
для startup progress и гонки taskkill. Frontend full pass: 891/892; единственная
|
||||
ошибка была старым ожиданием соседнего Rerun camera-journal теста. Оно исправлено
|
||||
в его задаче; затем все 11 focused architecture/simulation/camera-journal tests
|
||||
прошли. Финальные production build/typecheck, Ruff и diff whitespace check прошли.
|
||||
|
||||
В фактическом браузере проверены обе сцены, движущийся pose marker, камера AI,
|
||||
пауза, step, Stop, свободный обзор, fullscreen с доступным Stop и Escape. После
|
||||
финального build проверены название в fullscreen и библиотека без нижнего preview.
|
||||
Тяжёлый 3D закрыт, оставлена библиотека из двух локаций на Core 8000.
|
||||
|
||||
## Сохранение окружения и handoff
|
||||
|
||||
Release `0af432ce95816402`, SHA-256 архива
|
||||
`47230a1d1a2cffe3dd448e5e0fb5aef354bba4ee4ad6a0d7008791593cd1e0b9`.
|
||||
После проверки сохранены все прежние 21 container ID и их image/status/restart,
|
||||
mounts, memory/GPU bindings и настроенные PortBindings; все прежние 108 image
|
||||
identities/tags и 9 volumes. Runtime NetworkSettings.Ports не подменяет сравнение
|
||||
настроенных PortBindings. Отдельная соседняя задача добавила CPU-only контейнер
|
||||
`ndc-rerun-navigation-build` и свой образ; они не относятся к AI-полигону.
|
||||
|
||||
В 18:48 UTC собственных kit.exe и model containers нет, active_run null.
|
||||
Оставлен один idle coordinator PID 19724 с worker.lock, через foreground launcher
|
||||
session 21791 и private reverse forward 18081. Автозапуска OS нет. Core 8000 жив;
|
||||
8765 не слушает. Существующие AI Inference/KB4 конфигурации не менялись.
|
||||
Запуск/остановка описаны в [runbook](../runbooks/AI_POLYGON_WORKER_006.md).
|
||||
|
||||
Private evidence: `outputs/ai-polygon-2026-09-21/revision-2/`: forest-performance,
|
||||
bamboo-performance, pause-verification, stop-qualification, worker-inventory,
|
||||
worker-preservation, operator-handoff JSON; исходные receipts и RGB рядом.
|
||||
Архивы Bamboo и manifests находятся в родительском private outputs directory.
|
||||
Промежуточные неуспешные попытки и пользовательский failed run сохранены.
|
||||
|
||||
## Оставшаяся граница
|
||||
|
||||
Это наблюдаемая лабораторная симуляция с реальным inference, но ещё не принятая
|
||||
автономная навигация. Масштаб некалиброван, физическая земля плоская. Деревянная
|
||||
ступень Forest не имеет collision и раньше не была распознана как препятствие.
|
||||
Трава только визуальная. Объезд, тормозной путь, устойчивое движение по длинной
|
||||
тропе, динамические люди/животные и глобальный GPU arbitration требуют отдельных
|
||||
контролируемых сценариев. Физические VESC/ASVD-аппараты в этом контуре отсутствуют.
|
||||
@@ -0,0 +1,190 @@
|
||||
# AI-полигон: исполнение на Worker и потоковый операторский просмотр
|
||||
|
||||
## Решение и текущий статус
|
||||
|
||||
Требование владельца от 21.09.2026 реализовано: в профиле AI-полигона мир,
|
||||
физика, камера, AI, управление виртуальным ровером и журналы исполняются на
|
||||
Worker 006. Mac принимает готовое NVIDIA WebRTC-видео и небольшой snapshot.
|
||||
Локальный `AiWorldPreview` с PlayCanvas/PLY удалён. LCC Gaussian Mirror остаётся
|
||||
отдельным профилем; изменения не переносятся на его собственный renderer.
|
||||
|
||||
Размещение принято на основе MISSIONCOR-76 / Mission Core Node: один локальный
|
||||
владелец исполнения, отдельные control/media/telemetry и локальное хранение.
|
||||
Повторно использованы существующие Worker tunnel18080 и модельные образы.
|
||||
Go/Linux Node service не скопирован на Windows; готового AI-autonomy service в
|
||||
Node нет. Добавлен узкий host coordinator симулятора.
|
||||
|
||||
Новый runtime — лабораторная основа для проверки AI. Его realtime-размещение
|
||||
и цикл подтверждены; прохождение длинной грунтовой дороги, объезд, точный
|
||||
тормозной путь и реакции на динамических людей/животных пока не приняты.
|
||||
|
||||
## Схема
|
||||
|
||||
```text
|
||||
Worker 006, Windows / RTX4090
|
||||
Isaac6.1: Gaussian + метрический ровер + physics60Hz + sensor800×600
|
||||
RGB -> очередь последнего кадра -> локальные DDRNet / RF-DETR
|
||||
-> RoadPolicy -> виртуальные приводы
|
||||
viewport -> NVIDIA encoder -> Tailscale WebRTC -> HTML video на Mac
|
||||
timestamps / motion / decisions / camera archive -> локальный диск
|
||||
persistent coordinator <-> существующий tunnel18080 <-> Core8000
|
||||
|
||||
Mac: операторские команды, подтверждённые состояния, telemetry и video decoder
|
||||
```
|
||||
|
||||
В render/physics loop нет CoreClient, HTTP к Mac, per-frame ACK или ожидания
|
||||
моделей. Coordinator обменивается управляющими файлами/snapshots с native child;
|
||||
зависший управляющий HTTP не является частью физического tick. AI имеет отдельный
|
||||
поток и одно ожидающее изображение: новый кадр заменяет старый, очередь не растёт.
|
||||
Наблюдение/команда старше500мс дают нулевую команду, физическое время идёт дальше.
|
||||
Pause инвалидирует уже начатый inference; Resume требует новые ясные наблюдения.
|
||||
|
||||
Штатный Isaac6.1 throttling при Play включал manual loop, из-за чего первая
|
||||
проверка дала0.47×. Исправлены все три управляющие настройки — fixed timeline,
|
||||
manual main loop и enable_manualmode расширения throttling. PhysX продолжает
|
||||
исполнять дискретные шаги1/60с, накапливая их по wall-clock. Измерение основано
|
||||
на фактическом числе physics steps; 30FPS видео отдельно измеряет браузер.
|
||||
|
||||
## Runtime и установка
|
||||
|
||||
- Native Isaac6.1.0 и существующий `observatory-ai-modules/20260904-v14` сохранены.
|
||||
- NVIDIA `@nvidia/ov-web-rtc`6.7.0 взят из официального registry, версия закреплена.
|
||||
- Windows Scheduled Task `ndc-ai-polygon-worker`: при входе текущего пользователя,
|
||||
не зависит от foreground SSH или viewer. Не заявляется работа до Windows login.
|
||||
- Windows Job Object закрывает native потомков при аварии coordinator; точные
|
||||
container IDs сохраняются для восстановления и очистки. Core не освобождает
|
||||
GPU reservation только по пропавшему heartbeat: требуется реальный finish.
|
||||
- Управление через существующий приватный туннель18080; отдельного18081 больше нет.
|
||||
- Direct stream1280×720 по TCP49100/UDP47998. Allow ограничен процессом Kit,
|
||||
приватным адресом Worker и текущим Tailscale-адресом Mac. Существующие Windows
|
||||
Block rules сохраняются для всех остальных портов/адресов; rollback записан.
|
||||
- Операторский video input inert: клавиатура/мышь не управляют произвольным KitUI.
|
||||
Camera переключается явной командой Worker. NVIDIA допускает один viewer.
|
||||
|
||||
Финальный release: `a25fa4f008a18cbf`, 551 файлов; SHA-256 архива:
|
||||
`177aeb640398ef2aeac46f07ddbe731078ea36f85c811111d57a82ea3b5ddd55`.
|
||||
Проверены архив и все файловые hashes до установки. Модельный профиль:
|
||||
`e505cc842575d96a4993765cfba19fea8a95e6c98ff613996d87e3887be79ecb`.
|
||||
Scene provenance включает runtime, очередь, IPC, inference adapter, policy и
|
||||
контракты; robot и models имеют отдельные hashes. Private archives/manifests:
|
||||
`outputs/ai-polygon-2026-09-21/realtime/`.
|
||||
|
||||
Промежуточный Forest performance release `ed210b04d0fd858b` имел те же clocks,
|
||||
renderer и robot; финальный release дополнительно сбрасывает накопленную ясность
|
||||
дороги при Resume, корректно различает первоначальную загрузку AI и последующий
|
||||
отказ inference, расширяет source identity и ограниченно повторяет локальный IPC при кратком Windows sharing conflict. Установщик сам проверяет плоский файловый manifest и сохраняет verified_files; пустой manifest не допускается.
|
||||
|
||||
## Геометрия и данные
|
||||
|
||||
Ровер заменён с Jetbot на four-wheel differential articulation. Полный footprint
|
||||
1×1м; radius0.15м, track0.9м, масса24кг — явно временные параметры. Визуальная
|
||||
геометрия и collision находятся в одном профиле. Камера расположена перед мачтой:
|
||||
первая проверка обнаружила самоокклюзию, после исправления модели видят дорогу.
|
||||
Физические VESC/ASVD и управление настоящими аппаратами отсутствуют.
|
||||
|
||||
Forest:2 142 439 splats,505 617 082bytes,CCBY4.0,draftmode,
|
||||
SHA432ee329fc75d86b50d0b577542adca579b0749b4939044fc3980f27b2618ece.
|
||||
Bamboo:5 818 957splats,325 861 955bytes,CCBY4.0,luckysplat,
|
||||
SHAd7f2aad3240cc1a7369eb0d8b0d4c96a9cadbe07ee352c25d297b1037a812824.
|
||||
PLY/USD кэшируются на Worker; при открытии браузер их не загружает.
|
||||
Grass visual-only, физическая земля — скрытая плоскость. Единицы Gaussian пока
|
||||
не подтверждены измеренной опорой. Это не калиброванный физический двойник.
|
||||
|
||||
Inference получает локальный несжатый RGB до streaming encoder. Evidence
|
||||
сохраняется на Worker: motion/decisions timestamps, commands, boxes, JPEG90
|
||||
копии использованных кадров и ихSHA. JPEG архив не называется lossless raw.
|
||||
Полного автоматического archive sync на Mac в этом этапе нет.
|
||||
|
||||
## Операторский интерфейс
|
||||
|
||||
Сохранена существующая поверхность «Симуляции» с переключателем профиля.
|
||||
Библиотека содержит только доступные Forest/Bamboo, без магазинных ссылок,
|
||||
нижних превью и автоматически показанных старых кадров. «Открыть» отдельно
|
||||
от «Запустить AI». Круглая стрелка назад закрывает просмотр, сохраняя episode.
|
||||
Повторное открытие присоединяет тот же run. Pause и Stop имеют подтверждение
|
||||
Worker; Stop становится терминальным после освобождения native/model ресурсов.
|
||||
Fullscreen сохраняет кнопки и имя сцены. Камеры follow/overview/AI исполняются
|
||||
на Worker. Поля FPS/AIHz/RTF/возраст кадра больше не смешиваются.
|
||||
|
||||
## Измеренная приёмка
|
||||
|
||||
Forest run `airun-b2275571be9941e7b2e45ad104af1ec9`,35 snapshots в steady-state:
|
||||
|
||||
| Метрика | Минимум | Медиана | Максимум |
|
||||
|---|---:|---:|---:|
|
||||
| Физическое/реальное время |0.969×|1.000×|1.033×|
|
||||
| Render loop |23.62FPS|28.00FPS|28.00FPS|
|
||||
| Камера→очередь AI |9.69FPS|11.29FPS|12.00FPS|
|
||||
| Завершённые решения |8.00Hz|10.83Hz|12.00Hz|
|
||||
| Inference |62мс|93мс|109мс|
|
||||
| Возраст кадра |140мс|172мс|219мс|
|
||||
|
||||
Браузер показывал27–30декодируемыхFPS. Внутри замера ровер изменил позицию;
|
||||
наблюдались решения road/uncertain/no-road/obstacle. Обнаружение obstacle здесь
|
||||
не доказательство правильного распознавания реального препятствия: требуется
|
||||
отдельная размеченная приёмка.
|
||||
|
||||
Pause удержал6сек: sim70.9с,4254physics steps,686решений и одна pose без изменений.
|
||||
При закрытом viewer за6сек physics time вырос98.8→104.583с, решения993→1059;
|
||||
повторное открытие восстановило видео того же run. Stop завершился за3.23с
|
||||
включая освобождение native process и двух model containers.
|
||||
|
||||
Backend26/26: ownership/ACK, идемпотентность, disconnect/restart reconciliation,
|
||||
сохранение reservation, отсутствие Mac frames, bounded queue, stale-source stop,
|
||||
отсечение результата послеPause и свежие наблюдения послеResume. Frontend895/895,
|
||||
architecture4/4,typecheck,production build прошли последовательно. Ruff прошёл.
|
||||
Bamboo run `airun-43bc42b3def04d5091330c5ea3c28062` на release7536f11d4ae78371:
|
||||
25 steady-state snapshots, RTF0.969–1.022× (медиана1.000), render28FPS,
|
||||
camera12FPS, AI11Hz, inference79мс, frame age172мс (медианы). До выборки
|
||||
были11road и13uncertain решений, затем no-road и остановка. Это не прохождение
|
||||
всей тропы. Во время сцены GPU50%, VRAM7606MiB из24564MiB.
|
||||
|
||||
После финального frontend build браузером проверены follow/overview/AI,
|
||||
fullscreen с именем и управлением, Escape и Stop изfullscreen. DOM во время
|
||||
реального Bamboo-видео содержал0canvas; сцена в браузере не рисуется.
|
||||
Переключение вида меняет Workercamera, видео восстанавливается после возврата.
|
||||
Последующее исправление Windows IPC не меняет scene/clock/model algorithms.
|
||||
|
||||
Финальный smoke `airun-99d524b99f8444819ba299841805353b` на release
|
||||
a25fa4f008a18cbf естественно завершился: 30сек,297решений,медианаRTF1.0.
|
||||
Отдельная проверка `airun-9669437638ec499fa63b165ad75e63b6` подтвердила29FPS
|
||||
видеопотока после конечной установки firewall: прежние Kit rules явноBlock,
|
||||
остальные адреса на streaming ports блокируются, Allow только оператору.
|
||||
Оба прогона завершены. Installer receipt: verified_files=551.
|
||||
|
||||
Финальная Docker-сверка: все21исходных container ID, полныеConfig/HostConfig,
|
||||
109image identities/tags и9volumes сохранены без различий. Private evidence:
|
||||
`preservation-proof.json`, `worker-before.json`, `worker-after.json`. После QA
|
||||
нет active.json, nativeKit и временных AI modelcontainers; сервисWorker idle,
|
||||
Core8000 доступен, обе локации available. Ops MISSIONCOR-83 обновлён фактическими
|
||||
результатами; общая автономия остаётся InProgress.
|
||||
|
||||
## Ограничения и следующий этап
|
||||
|
||||
Функциональная симуляция с наблюдением принята отдельно от качества autonomy.
|
||||
RoadPolicy — camera-only baseline, не маршрутный планировщик и не оценка
|
||||
метрической дистанции. Нужны калиброванный масштаб, грунтовый collision/terrain,
|
||||
профиль динамики аппарата, сценарии obstacle/braking/avoidance/dynamic actors.
|
||||
Одновременно квалифицирован один виртуальный ровер и один комплект моделей;
|
||||
две параллельные симуляции требуют отдельного GPU-бюджета.
|
||||
|
||||
Разрыв viewer проверен на работающем Worker. Core restart/lease recovery проверены
|
||||
контрактными тестами; общий действующий tunnel не отключался ради эксперимента.
|
||||
Полный end-to-end hard network outage и host crash drill не заявлены пройденными.
|
||||
При потере Core лабораторный run продолжает последнюю команду до локального
|
||||
лимита времени с локальным AI watchdog; потеря связи не означает подтверждённыйStop.
|
||||
|
||||
Existing AI Inference reservation соблюдён. Отдельные Gaussian jobs пока не
|
||||
используют общий GPU broker и не запускаются параллельно. Задержки на4090 не
|
||||
доказывают быстродействие будущего onboard hardware. Docker profiles/images/
|
||||
weights сохранены; неподтверждённый ускоренный DDRNetTRT не подменяет reference.
|
||||
|
||||
## Официальные источники
|
||||
|
||||
- [Native streaming](https://docs.isaacsim.omniverse.nvidia.com/6.1.0/installation/manual_livestream_clients.html)
|
||||
- [Web Streaming Library](https://docs.omniverse.nvidia.com/ov-web-sdk/latest/web-streaming-library/overview.html)
|
||||
- [Isaac clocks](https://docs.isaacsim.omniverse.nvidia.com/latest/sensors/isaacsim_sensors_multitick_rendering.html)
|
||||
- [Throttling/manual loop flags](https://docs.isaacsim.omniverse.nvidia.com/6.0.0/overview/troubleshooting.html)
|
||||
- [Timing examples](https://docs.isaacsim.omniverse.nvidia.com/latest/replicator_tutorials/tutorial_replicator_isaac_snippets.html)
|
||||
|
||||
Рабочая инструкция: [Worker006 runbook](../runbooks/AI_POLYGON_WORKER_006.md).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user