Persist rover observation configuration and calibrate Insta360 panorama

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 18:17:54 +03:00
parent c43b097a3a
commit b4dab01f2a
36 changed files with 1271 additions and 50 deletions
+30
View File
@@ -0,0 +1,30 @@
# Panorama optical conventions
`frontend/src/panoramaCalibration.ts` adapts calibration layouts and projection
conventions from [GyroView](https://github.com/bubo-squared/GyroView), revision
`ae5c22b155ab4ec9c28d141e61340ca2d6f94994`. This is not Insta360 Media SDK.
Legacy radius angles, polynomial normalization and lens-pose signs are
open-source interpretations; they require qualification on the actual live camera.
No GyroView application, recording parser or dependency tree is included.
MIT License
Copyright (c) 2026 Bubo²
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,9 @@
// JSON objects may be reordered by the onboard serializer. A lost ACK must
// reconcile the already committed draft instead of creating a false conflict.
export function sameConfiguration(a:unknown,b:unknown):boolean {
if(a===b)return true;
if(a===null||b===null||typeof a!=='object'||typeof b!=='object')return false;
if(Array.isArray(a)||Array.isArray(b))return Array.isArray(a)&&Array.isArray(b)&&a.length===b.length&&a.every((value,index)=>sameConfiguration(value,b[index]));
const x=a as Record<string,unknown>,y=b as Record<string,unknown>,keys=Object.keys(x);
return keys.length===Object.keys(y).length&&keys.every(key=>Object.hasOwn(y,key)&&sameConfiguration(x[key],y[key]));
}
@@ -16,11 +16,11 @@ export interface FleetPreview {
preview_id: string; node_id: string; name: string; host: BoardHost;
endpoint: string; expires_at: number;
}
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown): Promise<T> {
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000): Promise<T> {
const response = await fetch(`/api/v1/fleet${path}`, {
method, credentials: "same-origin", cache: "no-store",
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(12000),
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
@@ -0,0 +1,82 @@
import {useEffect,useRef,useState,type SetStateAction} from 'react';
import type {CameraPresentation} from '../../../../../packages/sensor-ui/src/observation';
import type {ObservationLayout} from './observationLayout';
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
import {fleetRequest} from './useFleet';
import {sameConfiguration} from './configurationEquality';
interface Document {layouts:ObservationPresets;cameras:Record<string,CameraPresentation>}
interface Receipt {schema:'missioncore.rover-configuration/v1';revision:number;document:Document|null;draft?:Document|null;source:'onboard'|'mirror';writable:boolean;available:boolean}
interface Draft {revision:number;document:Document}
export function useVehicleObservation(vehicleID:string) {
const draftKey=`missioncore.observation.draft.v1:${vehicleID}`;
const stored=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
const initial=():Document=>({layouts:decodeObservationPresets(null,stored(`missioncore.observation.v1:${vehicleID}`)),cameras:{}});
const [document,setDocument]=useState(initial),[ready,setReady]=useState(false),[error,setError]=useState<string|null>(null),[edit,setEdit]=useState(0),[pending,setPending]=useState(false),[errorDismissed,setErrorDismissed]=useState(false);
const state=useRef({document,edit:0,saved:0,revision:0,ready:false});
const mounted=useRef(true),writes=useRef(Promise.resolve());
const path=`/${encodeURIComponent(vehicleID)}/observation-configuration`;
const normalize=(value:Document):Document=>({...value,layouts:decodeObservationPresets(value.layouts)});
const remember=()=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:state.current.revision,document:state.current.document}));}catch{/* The board acknowledgement remains the durable save. */}};
const flush=()=>{
const write=async()=>{
const current=state.current;if(!current.ready||current.saved===current.edit)return;
const version=current.edit,payload=current.document;
if(mounted.current)setPending(true);
try {
const receipt=await fleetRequest<Receipt>(path,'PUT',{expected_revision:current.revision,document:payload},20000);
current.revision=receipt.revision;current.saved=version;
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember();
if(mounted.current)setError(null);
}catch(cause){if(mounted.current){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
finally{if(mounted.current)setPending(current.saved!==current.edit);}
};
writes.current=writes.current.then(write,write);return writes.current;
};
useEffect(()=>{
mounted.current=true;let active=true;
fleetRequest<Receipt>(path).then(receipt=>{
if(!active)return;
const saved=receipt.document?normalize(receipt.document):initial();
const draft=stored(draftKey) as Draft|null;
const candidate=draft?.document??(!receipt.document?receipt.draft:null);
const same=candidate&&sameConfiguration(candidate,receipt.document);
const dirty=!!candidate&&!same;
const value=dirty?normalize(candidate):saved;
const revision=draft&&dirty?draft.revision:receipt.revision;
state.current={document:value,edit:dirty?1:0,saved:0,revision,ready:true};
setDocument(value);setReady(true);setEdit(dirty?1:0);setPending(dirty);
if(!receipt.writable)setError('Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
}).catch(cause=>{if(active)setError(cause instanceof Error?cause.message:'Настройки недоступны.');});
return()=>{active=false;mounted.current=false;void flush();};
},[vehicleID]);
useEffect(()=>{if(!ready||edit===0)return;const timer=setTimeout(()=>void flush(),350);return()=>clearTimeout(timer);},[edit,ready]);
const update=(change:(value:Document)=>Document)=>{
if(!state.current.ready)return;
const current=state.current;current.document=change(current.document);current.edit++;remember();
setDocument(current.document);setEdit(current.edit);setPending(true);
};
const changeLayouts=(change:(value:ObservationPresets)=>ObservationPresets)=>{
try{update(value=>({...value,layouts:change(value.layouts)}));return state.current.ready;}
catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
};
const reload=async()=>{
await writes.current;
try{
const receipt=await fleetRequest<Receipt>(path);
if(!receipt.writable)throw Error('Не удалось получить актуальную конфигурацию с борта. Черновик сохранён.');
const value=receipt.document?normalize(receipt.document):initial();
state.current={document:value,edit:0,saved:0,revision:receipt.revision,ready:true};
setDocument(value);setReady(true);setEdit(0);setPending(false);setError(null);
try{localStorage.removeItem(draftKey);}catch{}
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');}
};
const setLayout=(value:SetStateAction<ObservationLayout>)=>changeLayouts(current=>({...current,layout:typeof value==='function'?value(current.layout):value}));
return {...document.layouts,ready,pending,cameras:document.cameras,setLayout,
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
rename:(id:string,name:string)=>changeLayouts(current=>renameObservationPreset(current,id,name)),
remove:(id:string)=>changeLayouts(current=>removeObservationPreset(current,id)),
error,toastError:errorDismissed?null:error,clearError:()=>setErrorDismissed(true),retry:flush,reload};
}
@@ -1,9 +1,12 @@
import {useEffect,useLayoutEffect,useMemo,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,ToastStack,Window} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
import {decodeObservationLayout,emptyObservationLayout,moveObservation,withObservationTree,orderedObservationIDs} from '../../../core/fleet/observationLayout';
import {moveObservation,withObservationTree,orderedObservationIDs,observationTree} from '../../../core/fleet/observationLayout';
import {useVehicleObservation} from '../../../core/fleet/useVehicleObservation';
import {observationArrangements,retainDormantObservationTree} from '../../../core/fleet/observationPresets';
import {ObservationLayoutSaveWindow} from '../../../components/observation/ObservationLayoutSaveWindow';
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
@@ -21,8 +24,10 @@ import {useRoverControl} from '../../../core/fleet/useRoverControl';
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();}});
const inventory=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {layout,setLayout}=presets;
const [saving,setSaving]=useState(false),[editing,setEditing]=useState<string|null>(null);
const edited=presets.presets.find(p=>p.id===editing);
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
const [layersOpen,setLayersOpen]=useState(false);
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
@@ -44,15 +49,14 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice;
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;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,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),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;
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,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)&&navigationActions}<Button onClick={()=>{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>
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,tree))}>
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{presets.pending&&<StatusBadge tone="neutral">{presets.error?"Изменения не сохранены":"Сохранение на борт…"}</StatusBadge>}{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<div className="observation-panel">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
@@ -71,16 +75,21 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
</GlassSurface>
</div>,mounts.current.get(source.key)!,source.key))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
{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))!}))}/>)}
{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} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} 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))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить в конфигураторе</Button></div></div>,media.current.get(source.key)!,source.key))}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
{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="Доступные слои" size="md"><div className="observation-settings">
<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,tree:undefined,splits:{}}))}/>
{presets.error&&<><Button onClick={()=>void presets.retry()}>Повторить сохранение</Button><Button onClick={()=>void presets.reload()}>Загрузить настройки с борта</Button></>}
<Select label="Расположение окон" disabled={!presets.ready} value={presets.selected} options={[...observationArrangements,...presets.presets.map(p=>({value:p.id,label:p.name,action:{label:`Редактировать раскладку «${p.name}»`,icon:<Icon name="edit"/>,onAction:()=>{setLayersOpen(false);setEditing(p.id);}}}))]} onChange={value=>{presets.select(value);setFull(null);}}/>
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.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>;})}
<Button onClick={()=>{setLayout(current=>({...current,tree:undefined,order:[],splits:{},arrangement:'auto'}));setFull(null);}}>Восстановить расположение</Button>
<Button disabled={!presets.ready} onClick={()=>{const tree=observationTree(layout,visible);if(tree)setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)));setLayersOpen(false);setSaving(true);}}>Сохранить расположение</Button>
<Button disabled={!presets.ready} onClick={()=>{presets.select('auto');setFull(null);}}>Восстановить расположение</Button>
</div></Window>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
<ToastStack items={presets.toastError?[{id:'observation-save',tone:'error',title:'Настройки центра наблюдения',description:presets.toastError}]:[]} onDismiss={presets.clearError}/>
</section>,portal)}</>;
}
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from 'vite';
let server,optics,exposure;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});optics=await server.ssrLoadModule('../../plugins/insta360-x4/frontend/src/panoramaCalibration.ts');exposure=await server.ssrLoadModule('../../plugins/insta360-x4/frontend/src/panoramaExposure.ts');});
after(async()=>{await server?.close();});
const block=(cx)=>[1,240,240,cx,300,0,0,90,0,0,0,0,0,0,0,0,1600,600,71];
const fixture=()=>({offsets:[[2,...block(400),...block(1200),3*65536].join('_')],crop:{source_width:800,source_height:600,width:576,height:576,x:0,y:0}});
const close=(a,b)=>assert.ok(Math.abs(a-b)<1e-9,`${a} != ${b}`);
test('rectangular sensor calibration maps each centred preview crop independently',()=>{
const c=optics.liveCalibration(fixture());assert.equal(c.version,3);assert.equal(c.width,2);
assert.deepEqual(c.lenses.map(l=>l.center),[[.5,.5],[1.5,.5]]);
assert.deepEqual(optics.projectLens(c,0,[-1,0,0],90),[.25,.5]);
assert.deepEqual(optics.projectLens(c,1,[1,0,0],270),[.75,.5]);
const f=fixture();f.crop.x=12;f.crop.y=-6;const shifted=optics.liveCalibration(f);
close(shifted.lenses[0].center[0],.5-12/576);close(shifted.lenses[1].center[1],.5+6/576);
});
test('unrecognised, malformed and incompatible optics cannot appear calibrated',()=>{
for(const v of [null,{},'x',NaN,{offsets:['2_NaN']}, {...fixture(),offsets:['2__1']}, {...fixture(),offsets:[fixture().offsets[0].replace('_196608','_393216')]}, {...fixture(),crop:{...fixture().crop,width:900}}, {...fixture(),crop:{...fixture().crop,x:999}}, {...fixture(),crop:{...fixture().crop,width:575}}])assert.equal(optics.liveCalibration(v),null);
});
test('rays in both seam bands remain within the correct lens windows at all mounting rotations',()=>{
const c=optics.liveCalibration(fixture());
for(const turn of [0,90,180,270])for(const sign of [-1,1])for(let lat=-70;lat<=70;lat+=10){const a=lat*Math.PI/180,ray=[0,sign*Math.cos(a),Math.sin(a)];
for(const i of [0,1]){const uv=optics.projectLens(c,i,ray,turn);assert.ok(uv);assert.ok(uv[0]>=i*.5&&uv[0]<=(i+1)*.5);assert.ok(uv[1]>=0&&uv[1]<=1);}
}
assert.equal(optics.projectLens(c,0,[1,0,0],0),null);
});
test('overlap exposure matching brings equal scenes together without chasing black or saturated pixels',()=>{
const c=optics.liveCalibration(fixture()),width=384,height=192,data=new Uint8ClampedArray(width*height*4);
for(let y=0;y<height;y++)for(let x=0;x<width;x++){const k=(y*width+x)*4;data.fill(x<width/2?100:150,k,k+3);data[k+3]=255;}
const gains=exposure.overlapGains(data,width,height,c,[90,270]);assert.ok(gains);
for(let k=0;k<3;k++)close(100*gains[0][k],150*gains[1][k]);
data.fill(0);assert.equal(exposure.overlapGains(data,width,height,c,[90,270]),null);
data.fill(255);assert.equal(exposure.overlapGains(data,width,height,c,[90,270]),null);
});
test('extreme brightness mismatch is bounded rather than producing unlimited gain',()=>{
const c=optics.liveCalibration(fixture()),width=384,height=192,data=new Uint8ClampedArray(width*height*4);
for(let y=0;y<height;y++)for(let x=0;x<width;x++){const k=(y*width+x)*4;data.fill(x<width/2?25:225,k,k+3);data[k+3]=255;}
const gains=exposure.overlapGains(data,width,height,c,[90,270]);for(const lens of gains)for(const gain of lens)assert.ok(gain>=.75&&gain<=4/3);
});
@@ -0,0 +1,19 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from 'vite';
let server,sameConfiguration;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({sameConfiguration}=await server.ssrLoadModule('/src/core/fleet/configurationEquality.ts'));});
after(async()=>server?.close());
test('lost onboard acknowledgement reconciles across JSON key ordering',()=>{
const draft={cameras:{x4:{rotations:{left:90,right:270},panoramaYaw:15}},layouts:{version:1,presets:[]}};
const board={layouts:{presets:[],version:1},cameras:{x4:{panoramaYaw:15,rotations:{right:270,left:90}}}};
assert.equal(sameConfiguration(draft,board),true);
board.cameras.x4.rotations.left=180;
assert.equal(sameConfiguration(draft,board),false);
});
test('array order and absent fields remain meaningful configuration changes',()=>{
assert.equal(sameConfiguration({order:['left','right']},{order:['right','left']}),false);
assert.equal(sameConfiguration({yaw:0},{}),false);
assert.equal(sameConfiguration({yaw:0},{yaw:null}),false);
assert.equal(sameConfiguration(null,{}),false);
});
+19 -16
View File
@@ -41,26 +41,29 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"`
}
type Pairing struct {
Monitor *Monitor
Sensors *Sensors
DeviceEnrollment *DeviceEnrollment
mu sync.Mutex
path string
store *Store
state PairState
now func() time.Time
inventory func() Inventory
version string
lastSeen int64
connection string
listenError string
failureWindow int64
failures int
clients map[string]*http.Client
RoverConfiguration *RoverConfigurationStore
Monitor *Monitor
Sensors *Sensors
DeviceEnrollment *DeviceEnrollment
mu sync.Mutex
path string
store *Store
state PairState
now func() time.Time
inventory func() Inventory
version string
lastSeen int64
connection string
listenError string
failureWindow int64
failures int
clients map[string]*http.Client
}
func OpenPairing(store *Store, dir, version string, inventory func() Inventory) (*Pairing, error) {
p := &Pairing{store: store, path: filepath.Join(dir, "core-binding.json"), now: time.Now, inventory: inventory, version: version, connection: "offline", clients: make(map[string]*http.Client), state: PairState{Schema: PairSchema, Phase: "unpaired"}}
id, name := store.Public()
p.RoverConfiguration = OpenRoverConfiguration(dir, id, name)
data, e := os.ReadFile(p.path)
if os.IsNotExist(e) {
return p, nil
@@ -301,6 +301,9 @@ func (p *Pairing) channel(ctx context.Context) {
if binding != nil {
id, name := p.store.Public()
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": p.inventory(), "devices": []any{}}
if p.RoverConfiguration != nil {
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
}
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil {
@@ -320,9 +323,13 @@ func (p *Pairing) channel(ctx context.Context) {
payload["monitor"] = p.Monitor.Snapshot()
}
result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload)
var configurationChange json.RawMessage
p.mu.Lock()
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
if e == nil && status == 200 {
if p.RoverConfiguration != nil {
configurationChange = result["rover_configuration_change"]
}
if p.Monitor != nil {
p.Monitor.Acknowledge(result["monitor_ack"])
}
@@ -373,6 +380,10 @@ func (p *Pairing) channel(ctx context.Context) {
}
}
p.mu.Unlock()
// Durable preference IO must not hold the pairing/control mutex.
if p.RoverConfiguration != nil {
p.RoverConfiguration.Apply(configurationChange)
}
}
for _, b := range revocations {
id, _ := p.store.Public()
@@ -0,0 +1,184 @@
package node
// RoverConfiguration is the onboard authority for portable rover preferences.
// Trust keys and live control state deliberately remain outside this document.
import (
"bytes"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"sync"
"time"
)
const roverConfigurationSchema = "missioncore.rover-configuration/v1"
const roverConfigurationLimit = 512 * 1024
type RoverConfiguration struct {
Schema string `json:"schema"`
NodeID string `json:"node_id"`
Name string `json:"name"`
Revision int64 `json:"revision"`
Observation json.RawMessage `json:"observation"`
LastChange string `json:"last_change,omitempty"`
}
type RoverConfigurationChange struct {
ID string `json:"id"`
ExpectedRevision int64 `json:"expected_revision"`
ExpiresAt int64 `json:"expires_at"`
Name string `json:"name"`
Observation json.RawMessage `json:"observation"`
}
type RoverConfigurationResult struct {
ID string `json:"id"`
State string `json:"state"`
}
type RoverConfigurationStore struct {
mu sync.Mutex
path string
nodeID string
name string
result *RoverConfigurationResult
}
func OpenRoverConfiguration(dir, nodeID, name string) *RoverConfigurationStore {
return &RoverConfigurationStore{path: filepath.Join(dir, "Rover Config.json"), nodeID: nodeID, name: name}
}
func decodeRoverJSON(raw []byte, value any) error {
if len(raw) > roverConfigurationLimit {
return errors.New("configuration too large")
}
d := json.NewDecoder(bytes.NewReader(raw))
d.DisallowUnknownFields()
if err := d.Decode(value); err != nil {
return err
}
if d.Decode(new(any)) != io.EOF {
return errors.New("trailing configuration data")
}
return nil
}
func validRoverObservation(raw json.RawMessage) error {
var document struct {
Layouts map[string]json.RawMessage `json:"layouts"`
Cameras map[string]struct {
Rotations map[string]int `json:"rotations"`
PanoramaYaw float64 `json:"panoramaYaw"`
} `json:"cameras"`
}
if err := decodeRoverJSON(raw, &document); err != nil {
return err
}
if document.Layouts == nil || document.Cameras == nil || len(document.Cameras) > 128 {
return errors.New("invalid observation document")
}
var version int
if json.Unmarshal(document.Layouts["version"], &version) != nil || version != 1 {
return errors.New("invalid layout version")
}
for id, camera := range document.Cameras {
if len(id) == 0 || len(id) > 512 || camera.Rotations == nil || camera.PanoramaYaw < 0 || camera.PanoramaYaw >= 360 {
return errors.New("invalid camera")
}
for lens, rotation := range camera.Rotations {
if (lens != "left" && lens != "right") || (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) {
return errors.New("invalid lens rotation")
}
}
}
return nil
}
func (s *RoverConfigurationStore) read() (RoverConfiguration, error) {
var value RoverConfiguration
info, err := os.Lstat(s.path)
if errors.Is(err, os.ErrNotExist) {
value = RoverConfiguration{Schema: roverConfigurationSchema, NodeID: s.nodeID, Name: s.name, Observation: json.RawMessage("null")}
// Even the initial configuration exists on the board before Core sees it.
err = savePrivateJSON(s.path, value)
return value, err
}
if err != nil {
return value, err
}
if !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > roverConfigurationLimit {
return value, errors.New("invalid rover configuration file")
}
raw, err := os.ReadFile(s.path)
if err != nil {
return value, err
}
if err = decodeRoverJSON(raw, &value); err != nil {
return value, err
}
if value.Schema != roverConfigurationSchema || value.NodeID != s.nodeID || value.Revision < 0 || value.Revision >= 1<<53-1 || len(value.Name) > 256 {
return value, errors.New("invalid rover configuration identity")
}
if string(value.Observation) != "null" {
if err = validRoverObservation(value.Observation); err != nil {
return value, err
}
}
return value, nil
}
func (s *RoverConfigurationStore) Snapshot() map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
value, err := s.read()
if err != nil {
return map[string]any{"state": "unavailable"}
}
return map[string]any{"state": "ready", "configuration": value, "result": s.result}
}
func (s *RoverConfigurationStore) Apply(raw json.RawMessage) {
if len(raw) == 0 || string(raw) == "null" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
var change RoverConfigurationChange
if decodeRoverJSON(raw, &change) != nil || len(change.ID) != 32 {
return
}
result := &RoverConfigurationResult{ID: change.ID, State: "invalid"}
s.result = result
if change.ExpectedRevision < 0 || change.ExpectedRevision >= 1<<53-2 || len(change.Name) > 256 || validRoverObservation(change.Observation) != nil {
return
}
before, err := s.read()
if err != nil {
result.State = "unavailable"
return
}
if before.LastChange == change.ID {
var a, b any
_ = json.Unmarshal(before.Observation, &a)
_ = json.Unmarshal(change.Observation, &b)
x, _ := json.Marshal(a)
y, _ := json.Marshal(b)
if before.Revision == change.ExpectedRevision+1 && bytes.Equal(x, y) && before.Name == change.Name {
result.State = "complete"
}
return
}
now := time.Now().Unix()
if change.ExpiresAt < now || change.ExpiresAt > now+60 {
result.State = "expired"
return
}
if before.Revision != change.ExpectedRevision {
result.State = "conflict"
return
}
next := before
next.Revision++
next.Name = change.Name
next.Observation = change.Observation
next.LastChange = change.ID
if savePrivateJSON(s.path, next) != nil {
result.State = "unavailable"
return
}
result.State = "complete"
}
@@ -0,0 +1,83 @@
package node
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
const testObservation = `{"layouts":{"version":1,"presets":[]},"cameras":{"camera-a":{"rotations":{"left":90,"right":270},"panoramaYaw":45}}}`
func configChange(id string, revision int64) json.RawMessage {
raw, _ := json.Marshal(RoverConfigurationChange{ID: id, ExpectedRevision: revision, ExpiresAt: time.Now().Unix() + 30, Name: "Rover 006", Observation: json.RawMessage(testObservation)})
return raw
}
func TestRoverConfigurationDurableAckAndRestart(t *testing.T) {
dir := t.TempDir()
s := OpenRoverConfiguration(dir, "node-a", "Rover")
initial := s.Snapshot()
if initial["state"] != "ready" {
t.Fatal(initial)
}
info, err := os.Stat(filepath.Join(dir, "Rover Config.json"))
if err != nil || info.Mode().Perm() != 0600 {
t.Fatal(info, err)
}
id := "11111111111111111111111111111111"
s.Apply(configChange(id, 0))
if s.result.State != "complete" {
t.Fatal(s.result)
}
restarted := OpenRoverConfiguration(dir, "node-a", "Rover")
value, err := restarted.read()
if err != nil || value.Revision != 1 || value.LastChange != id {
t.Fatal(value, err)
}
restarted.Apply(configChange(id, 0))
if restarted.result.State != "complete" {
t.Fatal(restarted.result)
}
restarted.Apply(configChange("22222222222222222222222222222222", 0))
if restarted.result.State != "conflict" {
t.Fatal(restarted.result)
}
value, _ = restarted.read()
if value.Revision != 1 {
t.Fatal(value)
}
}
func TestRoverConfigurationRejectsInvalidExpiredAndForeign(t *testing.T) {
dir := t.TempDir()
s := OpenRoverConfiguration(dir, "node-a", "Rover")
s.Snapshot()
var change RoverConfigurationChange
json.Unmarshal(configChange("11111111111111111111111111111111", 0), &change)
change.ExpiresAt = time.Now().Unix() - 1
raw, _ := json.Marshal(change)
s.Apply(raw)
if s.result.State != "expired" {
t.Fatal(s.result)
}
foreign := OpenRoverConfiguration(dir, "node-b", "Rover")
if foreign.Snapshot()["state"] != "unavailable" {
t.Fatal("foreign node accepted")
}
for _, raw := range []string{`null`, `{}`, `{"layouts":{"version":1},"cameras":{"a":{"rotations":{"left":45},"panoramaYaw":0}}}`, `{"layouts":{"version":1},"cameras":{"a":{"rotations":{"left":true},"panoramaYaw":0}}}`} {
if validRoverObservation(json.RawMessage(raw)) == nil {
t.Fatal("invalid accepted", raw)
}
}
if err := os.WriteFile(s.path, []byte("{broken"), 0600); err != nil {
t.Fatal(err)
}
s.Apply(configChange("33333333333333333333333333333333", 0))
if s.result.State != "unavailable" {
t.Fatal(s.result)
}
content, _ := os.ReadFile(s.path)
if string(content) != "{broken" {
t.Fatal("corrupt file replaced")
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ import sys
from build_deb import build, VERSION, BRAND_SHA256
ROOT = Path(__file__).resolve().parents[1]
DG_COMMIT = "8dd9190573d6616024ef01b9b34bf90b72960f44"
DG_COMMIT = "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
def guideline_sources():
+2 -2
View File
@@ -11,8 +11,8 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
BINARY_VERSION = "0.8.45"
VERSION = "0.8.45-1"
BINARY_VERSION = "0.8.46"
VERSION = "0.8.46-1"
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from debian import package
@@ -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 = "8dd9190573d6616024ef01b9b34bf90b72960f44"
DG_COMMIT = "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
def files(root):