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):
@@ -1922,3 +1922,110 @@ Map network acceptance also completed: after Windows connector became healthy,
71774→71798/bytes1519820206→1534981513, while failure count remained5. Previous
AMD connection refusal is resolved; cold data still requires its documented
Windows Docker/VPN path. Cached map and all camera views left open.
### OBS05 — onboard observation preferences, 2026-10-09
Node 0.8.46-1 is the versioned owner of `Rover Config.json` in its existing
private state directory. This increment owns observation layouts, named layout
presets, independent left/right display rotations and panorama heading. Physical
calibration, device assignments, pairing keys and motor configuration retain
their existing owners; display rotation does not alter sensor extrinsics.
Core proposes revision-checked changes over the established authenticated
heartbeat channel. Node validates and atomically replaces the file with file
and directory fsync before acknowledging. Core persists only the confirmed
board snapshot. An offline browser keeps an explicitly unsaved draft; it cannot
report local-only persistence as an onboard save. Existing local method.json
may supply a migration draft only for an empty board document. A lost ACK is
reconciled from the subsequent board snapshot. Conflicts require explicit reload.
Qualification and installation use the existing bounded Ubuntu source-build
artifact and owner-release launcher. No ad-hoc service, permission, USB, SDK or
package repair is part of this change. Preview/recording ownership is preserved;
no physical motion is requested. The previous qualified Node package is the
rollback path; downgrade preserves the new preferences file but does not read it.
The panorama is a nominal dual-fisheye projection from the existing single
preview decoder, with adjustable heading. Optical stitching/calibration and
seamless output are not claimed.
Live acceptance completed on the prepared Rover 006. All 18 Ubuntu qualification
jobs passed (265.03 s), including Node UI, race-enabled Go tests, environment,
installer and VESC reader checks. Package SHA256
`4175bb1ffdd697f464f2874c8497e85e018483e54a6d3206410293fe2a4aed63`.
Owner release `48958eedc8fce70afa6e26d9` upgraded only Node to 0.8.46-1;
installation completed in 23.99 s, UI ready, Node/K1/RealSense services active
with zero restart counts. Core has 87 passing fleet tests, 1050 existing UI
tests plus two acknowledgement reconciliation tests, typecheck and build.
Actual Core UI checks confirmed independent clockwise rotation cycles, heading
shift to 90 degrees, edge docking, panel swap, resize, named preset selection,
and restoration after page reload. The final board-confirmed revision is 13;
the current preset is retained on board. Both X4 lenses and panorama are live
from one decoder. Core8000 is left healthy and the Observation Center is open.
No motor operation, camera recording, SDK change or simulation stop was issued.
Private acceptance manifest: `.runtime/observation-live-acceptance-20261009.json`.
### OBS06 — X4 identity and calibrated live panorama, 2026-10-09
X4 plugin 0.1.3-10 exposes the camera serial and preview optical calibration
through the existing open Camera SDK session. These are read-only metadata;
no second SDK producer, capture settings or recording operation is introduced.
The serial is displayed in X4 Details. Real serials and calibration payloads
remain in private runtime evidence, outside source fixtures.
Owner release `cbcda3adc95f934dd0034d08` installed only the X4 upgrade through
the existing Ubuntu installer. The first attempt correctly refused an active
preview; after preview was stopped through its existing API, the same release
completed in 13.59 s. Package SHA256:
`ec65c384aac40f1e5ee8a8f13df01aa2ea2cc582d2cfbb6d9bc2b4508c7b6ca5`.
Node 0.8.46-1 and its existing services were preserved. Rollback uses the retained
qualified 0.1.3-9 release through the same installer with capture idle. The older
Node bundle still pins 0.1.3-9; its downgrade guard is unchanged, and future Node
bundles must qualify and pin the newer plugin separately.
The flat panorama now consumes the actual X4 v3 MEI lens model and centered
live-sensor crop. Independent operator display rotations are preserved. A
bounded overlap feather and temporally smoothed per-channel gain matching use
corresponding seam directions from the existing shared decoder. The heading
arrow advances 90 degrees through the existing board-acknowledged preference
path. Missing or unsupported metadata retains the nominal projection fallback.
Open-source calibration conventions were reviewed from GyroView at
`ae5c22b155ab4ec9c28d141e61340ca2d6f94994`; MIT attribution ships with Core.
This is calibrated projection and blending, not the proprietary Media SDK or
optical-flow stitching. Near-field parallax and scene-dependent seam artifacts
remain possible. No claim of seamless output for arbitrary scenes is made.
Qualification passed 10 synthetic native ABI checks on macOS and Ubuntu,
existing Ubuntu package qualification, 1057 Control Station tests, four
architecture checks, typecheck and production build. New tests cover crop
mapping, invalid calibration, seam coverage across mount rotations and bounded
exposure matching. An actual-calibration model check covered 16200 rays without
an uncovered ray; this is projection coverage, not a physical accuracy bound.
Live Core8000 acceptance confirmed the serial in Details, calibrated live
panorama, the complete heading cycle, board acknowledgement and reload.
Compared with the prior nominal view, the hard central seam was reduced in the
observed scene. Final readback: preview=1, recording=0, calibration present,
onboard configuration available; heading 270 degrees at revision 40 matches the
reloaded view. Existing left90/right270 and six-window layout remain. Core and
bundled license return HTTP 200. No motor operation or simulation stop occurred.
Private acceptance SHA256:
`e37e0eed4ac888100781ec0b53af0606ae566bdaf4bada88e8192c75110b0e6d`.
### OBS06B — serial in Park device settings, 2026-10-09
The shared device-settings window in Park now renders read-only identity facts
provided by its sensor plugin. X4 supplies its SDK-reported serial from the
latest inventory, with an explicit unavailable value when absent. The value is
selectable and is not submitted as part of rename or preparation. This completes
the Park path in addition to the existing camera Details view. No board install,
SDK operation or camera setting was changed.
Acceptance: refreshed Core8000, opened Park / Rover 006 configuration / X4
settings and verified the real serial in the read-only field; Escape and reopen
passed. Four architecture checks, 1057 frontend tests, Control Station and Node
UI typechecks, and production build passed. Node UI validation also corrected
readonly-tuple WebGL uniform typing using scalar uniform calls with unchanged
values. Private UI evidence SHA256: `40b6dfec3bd52927a4571b89d13709bfc2e832421c736bf532f06d65e661b2ad`.
Rollback is the previous Control Station frontend build.
+3 -1
View File
@@ -44,6 +44,8 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer
const device=inventory?.items.find(v=>v.id===selected);
const connected=inventory?.items.filter(v=>readOfflineInventory||v.online||sensorContribution(contributions,v)?.retainOffline)??[];
const editingCurrent=inventory?.items.find(v=>v.id===editing?.id);
const settingsDevice=editingCurrent??editing;
const settingsFacts=settingsDevice?sensorContribution(contributions,settingsDevice)?.settingsFacts?.(settingsDevice)??[]:[];
useEffect(()=>{onDetailChange?.(!!device);},[!!device,onDetailChange]);
const Detail=device?(sensorContribution(contributions,device)?.Detail??(device.kind?null:SensorDetail)):null;
const inventoryView=<>
@@ -61,7 +63,7 @@ export function SensorWorkspace({transport,enabled=true,onDetailChange,createRer
const boardSettings=contributions.filter(value=>value.BoardSettings&&contributions.filter(other=>other.kind===value.kind).length===1);
const settingsView=<div className="sensor-content">{boardSettings.map(contribution=>{const View=contribution.BoardSettings!;return <View key={contribution.kind} inventory={inventory} transport={transport} enabled={enabled&&fresh} refresh={refresh} failure={failure} openDevice={setSelected}/>;})}{!boardSettings.length&&<p>Для подключённых устройств общие настройки пока недоступны.</p>}</div>;
return <div className="sensor-workspace">{device?Detail?<Detail key={device.snapshot.context.session_id} enabled={enabled&&fresh} device={device} transport={transport} back={()=>setSelected(null)} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:<div className="sensor-content"><Button onClick={()=>setSelected(null)}>К устройствам</Button><SettingsCard title="Просмотр устройства недоступен" description="Интеграция этого устройства не установлена."/></div>:(renderBoard?renderBoard({settings:settingsView,devices:inventoryView,showingSavedDevices:connected.length>0&&(!enabled||!fresh),refresh,addDevice:()=>setAdding(true),canAddDevice:!!transport.enrollment&&wirelessContributions(contributions).length>0}):board?<BoardSections {...board} settings={settingsView} devices={inventoryView}/>:inventoryView)}
<Window open={editing!==null} title="Настройки устройства" onClose={()=>setEditing(null)} footer={<WindowFooterActions><Button disabled={localBusy.has(editing?.id??'')} onClick={()=>setEditing(null)}>Отмена</Button><Button loading={localBusy.get(editing?.id??'')==='rename'} disabled={localBusy.has(editing?.id??'')||!name.trim()||!enabled||!fresh} onClick={()=>{if(editing)void action(editing,'rename',{name});}}>Сохранить</Button></WindowFooterActions>}><div className="sensor-content"><TextField label="Название устройства" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={localBusy.has(editing?.id??'')}/>{editing&&sensorContribution(contributions,editing)?.supportsPreparation!==false&&(editing.configured??editing.snapshot.enrollment==='enrolled')&&<ResourceRow title="Конфигурация на БК" description="Повторно развернуть и проверить встроенный драйвер устройства." actions={<Button disabled={localBusy.has(editing?.id??'')||!enabled||!fresh||!editingCurrent?.online||editingCurrent?.initializable===false||editingCurrent?.preparation_safe===false||['streaming','starting','stopping'].includes(editingCurrent?.snapshot.acquisition??'offline')} onClick={()=>{const target=editing;setEditing(null);void action(target,'prepare');}}>Обновить</Button>}/>}</div></Window>
<Window open={editing!==null} title="Настройки устройства" onClose={()=>setEditing(null)} footer={<WindowFooterActions><Button disabled={localBusy.has(editing?.id??'')} onClick={()=>setEditing(null)}>Отмена</Button><Button loading={localBusy.get(editing?.id??'')==='rename'} disabled={localBusy.has(editing?.id??'')||!name.trim()||!enabled||!fresh} onClick={()=>{if(editing)void action(editing,'rename',{name});}}>Сохранить</Button></WindowFooterActions>}><div className="sensor-content"><TextField label="Название устройства" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={localBusy.has(editing?.id??'')}/>{settingsFacts.map(fact=><TextField key={fact.id} label={fact.label} value={fact.value} readOnly/>)}{editing&&sensorContribution(contributions,editing)?.supportsPreparation!==false&&(editing.configured??editing.snapshot.enrollment==='enrolled')&&<ResourceRow title="Конфигурация на БК" description="Повторно развернуть и проверить встроенный драйвер устройства." actions={<Button disabled={localBusy.has(editing?.id??'')||!enabled||!fresh||!editingCurrent?.online||editingCurrent?.initializable===false||editingCurrent?.preparation_safe===false||['streaming','starting','stopping'].includes(editingCurrent?.snapshot.acquisition??'offline')} onClick={()=>{const target=editing;setEditing(null);void action(target,'prepare');}}>Обновить</Button>}/>}</div></Window>
{adding&&transport.enrollment&&wirelessContributions(contributions).length>0&&<WirelessEnrollmentWindow enabled={enabled} contributions={contributions} transport={transport.enrollment} onClose={()=>setAdding(false)} onChange={()=>{void refresh();}} onComplete={completeEnrollment}/>}
<ToastStack items={error?[{id:'sensor-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</div>;
+1
View File
@@ -24,6 +24,7 @@ export interface SensorUiContribution {
supportsPreparation:boolean;
supportsRenaming?:boolean;
detailLabel?:string;
settingsFacts?:(device:Sensor)=>readonly {id:string;label:string;value:string}[];
rowActions?:(device:Sensor)=>readonly SensorRowAction[];
status?:(device:Sensor,fresh:boolean)=>{label:string;tone:'neutral'|'success'|'warning'|'danger'};
wirelessEnrollment?:{label:string;View:ComponentType<SensorEnrollmentProps>};
+2
View File
@@ -5,7 +5,9 @@ import type {RerunHostFactory} from './rerunHost';
export interface SensorObservationView {id:string;label:string;layers?:{value:string;label:string}[]}
/** Stable host slots let a session update its header without moving its media. */
export interface ObservationHeaderTargets {statusTarget:HTMLElement;actionsTarget:HTMLElement}
export interface CameraPresentation {rotations:Record<string,number>;panoramaYaw:number}
export interface SensorObservationProps {
presentation?:CameraPresentation;onPresentationChange?:(value:CameraPresentation)=>void;
device:Sensor;transport:SensorTransport;enabled:boolean;createRerunHost:RerunHostFactory;
views:({id:string;layer:string;target:HTMLElement}&ObservationHeaderTargets)[];
}
@@ -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.
@@ -40,6 +40,7 @@ export function X4Detail({device,transport,enabled,back,refresh,failure}:SensorD
const viewDevice=available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
return <div className="sensor-content"><div><Button onClick={back}>К устройствам</Button></div>
<SettingsCard title={device.name} description={`${device.model}${device.firmware?' · '+device.firmware:''}`} actions={<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={!enabled||busy} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>}>
<dl className="sensor-facts"><div><dt>Серийный номер</dt><dd>{status.serial||'Не получен'}</dd></div></dl>
{!available&&<p>Нет свежей связи с камерой.</p>}
<div className="sensor-actions"><Button disabled={!available||busy||status.preview!==0} loading={pending==='preview.start'} onClick={()=>void action('preview.start')}>Начать просмотр</Button><Button disabled={!enabled||busy||(!available&&!status.recovery?.preview_wanted)||(available&&status.preview===0&&!status.recovery?.preview_wanted)} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button><Button disabled={!available||busy||status.recording!==0} loading={pending==='verify'} onClick={()=>void action('verify')}>Проверить изображение</Button></div>
{status.alerts?.temperature_high&&<p>Камера сообщает о перегреве.</p>}
@@ -7,8 +7,9 @@ import {useSensorPreview} from '../../../../packages/sensor-ui/src/useSensorPrev
import {useObservationStart} from '../../../../packages/sensor-ui/src/useObservationStart';
import {startX4Observation} from './observationStart';
import {cameraStatus} from './model';
import {X4Panorama} from './X4Panorama';
function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;side:number;label:string;live:boolean}){
function Lens({video,side,label,live,rotation}:{video:RefObject<HTMLVideoElement|null>;side:number;label:string;live:boolean;rotation:number}){
const canvas=useRef<HTMLCanvasElement>(null);const [supported,setSupported]=useState(true);
useEffect(()=>{
const source=video.current,target=canvas.current;if(!source||!target)return;
@@ -17,7 +18,7 @@ function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;si
if(!active)return;
if(source.readyState>=2&&source.videoWidth){
const valid=Math.abs(source.videoWidth/source.videoHeight-2)<.02;setSupported(valid);
if(valid){const size=Math.max(1,Math.round(Math.min(target.clientWidth,target.clientHeight)*Math.min(devicePixelRatio,2)));if(target.width!==size||target.height!==size){target.width=size;target.height=size;}target.getContext('2d')?.drawImage(source,side*source.videoWidth/2,0,source.videoWidth/2,source.videoHeight,0,0,size,size);}
if(valid){const size=Math.max(1,Math.round(Math.min(target.clientWidth,target.clientHeight)*Math.min(devicePixelRatio,2)));if(target.width!==size||target.height!==size){target.width=size;target.height=size;}const context=target.getContext('2d');if(context){context.save();context.clearRect(0,0,size,size);context.translate(size/2,size/2);context.rotate(rotation*Math.PI/180);context.drawImage(source,side*source.videoWidth/2,0,source.videoWidth/2,source.videoHeight,-size/2,-size/2,size,size);context.restore();}}
}
};
const tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
@@ -25,10 +26,10 @@ function Lens({video,side,label,live}:{video:RefObject<HTMLVideoElement|null>;si
const resize=new ResizeObserver(draw);resize.observe(target);
if(typeof source.requestVideoFrameCallback==='function')handle=source.requestVideoFrameCallback(tick);else frame=requestAnimationFrame(fallback);
return()=>{active=false;resize.disconnect();if(handle!==undefined)source.cancelVideoFrameCallback(handle);if(frame!==undefined)cancelAnimationFrame(frame);};
},[video,side]);
return <><canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported}/>{!supported&&<p>Текущий формат изображения не содержит пару объективов.</p>}</>;
},[video,side,rotation]);
return <><canvas ref={canvas} aria-label={label} className="observation-lens" data-live={live&&supported} data-rotation={rotation}/>{!supported&&<p>Текущий формат изображения не содержит пару объективов.</p>}</>;
}
export function X4Observation({device,transport,enabled,views}:SensorObservationProps){
export function X4Observation({device,transport,enabled,views,presentation={rotations:{},panoramaYaw:0},onPresentationChange}:SensorObservationProps){
const video=useRef<HTMLVideoElement>(null);const [generation,setGeneration]=useState(0);
const status=cameraStatus(device);const available=enabled&&device.online&&status.connected;
const activation=useObservationStart(device,available&&device.prepared,status.preview!==0,()=>startX4Observation(device,transport));
@@ -39,9 +40,11 @@ export function X4Observation({device,transport,enabled,views}:SensorObservation
useEffect(()=>{setAttempts(0);},[device.id,device.snapshot.context.session_id]);
const pending=activation.pending||recovery.pending;
const failure=!live&&(activation.error||recovery.error||(sourceStalled&&attempts>=2&&!pending?'Не удалось восстановить изображение. Повторите просмотр.':''))||'';
const shiftPanorama=()=>onPresentationChange?.({...presentation,panoramaYaw:(presentation.panoramaYaw+90)%360});
const rotate=(id:string)=>onPresentationChange?.({...presentation,rotations:{...presentation.rotations,[id]:((presentation.rotations[id]??0)+90)%360}});
return <><video ref={video} autoPlay muted playsInline aria-hidden="true" className="observation-decoder"/>{views.map(view=>createPortal(<div className="observation-source">
<ObservationHeader targets={view} live={live} label={pending?recovery.pending?'Восстановление изображения':'Запуск камеры':state}>{failure&&<IconButton label="Повторить просмотр X4" disabled={pending||!available} onClick={()=>{if(status.preview===0)void activation.retry();else{setAttempts(0);void recovery.retry();}}}><Icon name="refresh"/></IconButton>}{error&&!failure&&<IconButton label="Повторить подключение X4" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
<div className="observation-source__media"><Lens video={video} side={view.id==='left'?0:1} label={`${device.name} ${view.id==='left'?'Left':'Right'} Cam`} live={hasFrame}/></div>
<ObservationHeader targets={view} live={live} label={pending?recovery.pending?'Восстановление изображения':'Запуск камеры':state}>{view.id==='panorama'&&<IconButton label="Сместить направление панорамы вправо на 90°" title={`Направление вправо на 90° · сейчас ${Math.round(presentation.panoramaYaw)}°`} disabled={!onPresentationChange} onClick={shiftPanorama}><Icon name="chevron-right"/></IconButton>}{view.id!=='panorama'&&<IconButton label={`Повернуть на 90° по часовой · ${view.id==='left'?'Left':'Right'} Cam`} title={`По часовой стрелке · сейчас ${presentation.rotations[view.id]??0}°`} disabled={!onPresentationChange} onClick={()=>rotate(view.id)}><Icon name="rotate-clockwise"/></IconButton>}{failure&&<IconButton label="Повторить просмотр X4" disabled={pending||!available} onClick={()=>{if(status.preview===0)void activation.retry();else{setAttempts(0);void recovery.retry();}}}><Icon name="refresh"/></IconButton>}{error&&!failure&&<IconButton label="Повторить подключение X4" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
<div className="observation-source__media"><>{view.id==='panorama'?<X4Panorama video={video} presentation={presentation} optics={device.camera_status?.preview_calibration} live={hasFrame} onChange={onPresentationChange}/>:<Lens video={video} side={view.id==='left'?0:1} label={`${device.name} ${view.id==='left'?'Left':'Right'} Cam`} live={hasFrame} rotation={presentation.rotations[view.id]??0}/>}</></div>
{!hasFrame&&<p className="observation-source__notice">{failure||error||(!available?'Нет свежей связи с камерой.':pending?'Подключение обоих объективов.':sourceStalled&&status.recording!==0?'Камера перестала передавать кадры. Восстановление доступно после завершения записи.':'Ожидание изображения.')}</p>}
</div>,view.target,view.id))}</>;
}
@@ -0,0 +1,78 @@
import {useEffect,useMemo,useRef,useState,type RefObject} from 'react';
import {liveCalibration,lensDirection,type Vec3} from './panoramaCalibration';
import {overlapGains} from './panoramaExposure';
import {panoramaFragment as fragment} from './panoramaShader';
import type {CameraPresentation} from '../../../../packages/sensor-ui/src/observation';
// Flat operator overview from the same live dual-fisheye decoder as both lens views.
const vertex=`attribute vec2 point; varying vec2 uv; void main(){uv=(point+1.0)*0.5;gl_Position=vec4(point,0.,1.);}`;
export function X4Panorama({video,presentation,optics,live,onChange}:{video:RefObject<HTMLVideoElement|null>;presentation:CameraPresentation;optics?:unknown;live:boolean;onChange?:(value:CameraPresentation)=>void}) {
const calibrationKey=JSON.stringify(optics??null);
const calibration=useMemo(()=>liveCalibration(optics),[calibrationKey]);
const calibrationRef=useRef(calibration);calibrationRef.current=calibration;
const canvas=useRef<HTMLCanvasElement>(null),settings=useRef(presentation),redraw=useRef<()=>void>(()=>{});
const drag=useRef<{id:number;x:number;yaw:number}|null>(null);
const [error,setError]=useState('');settings.current=presentation;
useEffect(()=>{redraw.current();},[presentation,calibration]);
useEffect(()=>{
const source=video.current,target=canvas.current;if(!source||!target)return;
const gl=target.getContext('webgl',{alpha:false,antialias:false,depth:false,preserveDrawingBuffer:false});
if(!gl){setError('Панорамный обзор недоступен в этом браузере.');return;}
const shaders:WebGLShader[]=[];let program:WebGLProgram|null=null,buffer:WebGLBuffer|null=null,texture:WebGLTexture|null=null;
let active=true,handle:number|undefined,frame:number|undefined;
const dispose=()=>{for(const shader of shaders)gl.deleteShader(shader);if(program)gl.deleteProgram(program);if(buffer)gl.deleteBuffer(buffer);if(texture)gl.deleteTexture(texture);};
try {
const compile=(type:number,code:string)=>{const shader=gl.createShader(type);if(!shader)throw Error('shader');shaders.push(shader);gl.shaderSource(shader,code);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS))throw Error('shader');return shader;};
program=gl.createProgram();if(!program)throw Error('program');gl.attachShader(program,compile(gl.VERTEX_SHADER,vertex));gl.attachShader(program,compile(gl.FRAGMENT_SHADER,fragment));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw Error('link');gl.useProgram(program);
buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);
const attribute=gl.getAttribLocation(program,'point');gl.enableVertexAttribArray(attribute);gl.vertexAttribPointer(attribute,2,gl.FLOAT,false,0,0);
texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
const rotations=gl.getUniformLocation(program,'rotation'),heading=gl.getUniformLocation(program,'heading'),calibrated=gl.getUniformLocation(program,'calibrated');
const uniforms=[0,1].map(i=>Object.fromEntries(['pose','center','focal','tangential','radial','gain','polynomial','kind','xi'].map(name=>[name,gl.getUniformLocation(program!,name+i)])));
const meter=document.createElement('canvas');meter.width=384;meter.height=192;
const meterContext=meter.getContext('2d',{willReadFrequently:true});
let lastSample=0,lastOptics='',gains:readonly [Vec3,Vec3]=[[1,1,1],[1,1,1]];
const draw=()=>{
if(!active||source.readyState<2||!source.videoWidth)return;
if(Math.abs(source.videoWidth/source.videoHeight-2)>.02){setError('Текущий формат изображения не содержит пару объективов.');return;}
const width=Math.max(2,Math.min(1600,Math.round(Math.min(target.clientWidth,target.clientHeight*2)*Math.min(devicePixelRatio,2)/2)*2));
if(target.width!==width){target.width=width;target.height=width/2;}gl.viewport(0,0,target.width,target.height);
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,gl.RGB,gl.UNSIGNED_BYTE,source);
const current=settings.current;gl.uniform2f(rotations,(current.rotations.left??0)*Math.PI/180,(current.rotations.right??0)*Math.PI/180);gl.uniform1f(heading,current.panoramaYaw*Math.PI/180);
const optical=calibrationRef.current;gl.uniform1f(calibrated,optical?1:0);
if(optical){
const turns=[current.rotations.left??0,current.rotations.right??0];
const key=JSON.stringify([optical,turns]);if(key!==lastOptics){lastOptics=key;lastSample=0;gains=[[1,1,1],[1,1,1]];}
const now=performance.now();
if(meterContext&&now-lastSample>=1000){
try{meterContext.drawImage(source,0,0,meter.width,meter.height);const found=overlapGains(meterContext.getImageData(0,0,meter.width,meter.height).data,meter.width,meter.height,optical,turns);
if(found){const weight=lastSample?1-Math.exp(-(now-lastSample)/1500):1;gains=found.map((v,i)=>v.map((n,c)=>gains[i][c]+(n-gains[i][c])*weight)) as unknown as readonly [Vec3,Vec3];}
}catch{/* Exposure metering cannot interrupt the live projection. */}
lastSample=now;
}
optical.lenses.forEach((lens,i)=>{const u=uniforms[i];
const matrix=([[1,0,0],[0,1,0],[0,0,1]] as Vec3[]).flatMap(ray=>lensDirection(ray,lens,i,turns[i]));
gl.uniformMatrix3fv(u.pose,false,matrix);gl.uniform2f(u.center,...lens.center);gl.uniform2f(u.focal,...lens.focal);gl.uniform2f(u.tangential,...lens.tangential);
gl.uniform3f(u.radial,...lens.radial);gl.uniform3f(u.gain,...gains[i]);gl.uniform4f(u.polynomial,...lens.polynomial);gl.uniform1f(u.kind,lens.kind==='mei'?1:0);gl.uniform1f(u.xi,lens.xi);
});
}
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);setError('');
};
redraw.current=draw;
const tick=()=>{draw();if(active)handle=source.requestVideoFrameCallback(tick);};
const fallback=()=>{draw();if(active)frame=requestAnimationFrame(fallback);};
const resize=new ResizeObserver(draw);resize.observe(target);
if(typeof source.requestVideoFrameCallback==='function')handle=source.requestVideoFrameCallback(tick);else frame=requestAnimationFrame(fallback);
draw();
return()=>{active=false;redraw.current=()=>{};resize.disconnect();if(handle!==undefined)source.cancelVideoFrameCallback(handle);if(frame!==undefined)cancelAnimationFrame(frame);dispose();};
}catch{dispose();setError('Не удалось открыть панорамный обзор.');}
},[video]);
const change=(yaw:number)=>onChange?.({...presentation,panoramaYaw:((yaw%360)+360)%360});
return <><canvas ref={canvas} aria-label="Панорама Insta360 · перетащите для выбора направления" tabIndex={0} data-calibration={calibration?.version??'nominal'} data-live={live&&!error} style={{touchAction:'none'}}
onPointerDown={event=>{if(event.button!==0||!onChange)return;event.currentTarget.setPointerCapture(event.pointerId);drag.current={id:event.pointerId,x:event.clientX,yaw:presentation.panoramaYaw};}}
onPointerMove={event=>{const d=drag.current;if(d&&d.id===event.pointerId)change(d.yaw-(event.clientX-d.x)/Math.max(1,event.currentTarget.clientWidth)*360);}}
onPointerUp={()=>{drag.current=null;}} onPointerCancel={()=>{drag.current=null;}} onLostPointerCapture={()=>{drag.current=null;}}
onKeyDown={event=>{if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();event.stopPropagation();change(presentation.panoramaYaw+(event.key==='ArrowRight'?15:-15));}}}/>
{error&&<p className="observation-source__notice">{error}</p>}</>;
}
+2 -2
View File
@@ -15,7 +15,7 @@ export function cameraRowActions(device:Sensor):readonly SensorRowAction[] {
export interface CameraStatus {
connected:boolean; preview:number|null; recording:number|null; function_mode:number|null;
firmware?:string; battery?:{level:number}; storage?:{free_bytes:number};
firmware?:string; serial?:string; battery?:{level:number}; storage?:{free_bytes:number};
alerts?:{battery_low?:boolean;storage_full?:boolean;temperature_high?:boolean};
recovery?:RecoveryStatus;
}
@@ -29,7 +29,7 @@ export interface CameraFiles {items:string[];offset:number;total:number}
const state=(value:unknown)=>value===0||value===1||value===-1?value:null;
export function cameraStatus(device:Sensor):CameraStatus {
const value=device.camera_status??{};
return {...value,connected:value.connected===true,preview:state(value.preview),recording:state(value.recording),
return {...value,serial:typeof value.serial==='string'&&value.serial.length<=256?value.serial:undefined,connected:value.connected===true,preview:state(value.preview),recording:state(value.recording),
function_mode:typeof value.function_mode==='number'&&Number.isInteger(value.function_mode)?value.function_mode:null} as CameraStatus;
}
export function cameraLabel(device:Sensor,fresh:boolean):{label:string;tone:'neutral'|'success'|'warning'|'danger'} {
@@ -0,0 +1,104 @@
/** Optical calibration layout informed by GyroView (MIT), pinned in THIRD_PARTY_NOTICES.md.
* Factory strings describe sensor pixels, independently of operator display rotations.
* Unknown/malformed versions are rejected instead of silently becoming a calibration.
*/
export type Vec3 = readonly [number,number,number];
export interface LensOptics {
kind:'radial'|'mei'; center:readonly [number,number]; orientation:Vec3;
polynomial:readonly [number,number,number,number];
focal:readonly [number,number]; xi:number; radial:Vec3; tangential:readonly [number,number];
}
export interface PanoramaCalibration {version:1|2|3; width:number;height:number;lenses:readonly [LensOptics,LensOptics]}
const radians=Math.PI/180;
const polynomial=(c:readonly number[],theta:number)=>theta*(c[0]+theta*(c[1]+theta*(c[2]+theta*c[3])));
const bounded=(v:number,limit:number)=>Number.isFinite(v)&&Math.abs(v)<=limit;
export function parseCalibration(value:unknown):PanoramaCalibration|null {
if(typeof value!=='string'||value.length>8192)return null;
const tokens=value.split('_');if(tokens.some(t=>t.trim()===''))return null;
const a=tokens.map(Number);if(a.some(v=>!bounded(v,1e9))||a[0]!==2)return null;
const version=a.length===16?1:a.length===34?2:a.length===40?3:null;if(!version)return null;
const word=a.at(-1)!;if(!Number.isInteger(word)||word<0||word>0xffffffff||(version!==1&&Math.floor(word/65536)!==version))return null;
const stride=version===1?6:version===2?16:19;
const width=version===1?a[13]:a[1+(version===2?13:16)];
const height=version===1?a[14]:a[1+(version===2?14:17)];
if(width<2||width>65536||height<1||height>32768||width<height||width>height*4)return null;
const lenses:LensOptics[]=[];
for(let i=0;i<2;i++){
const b=a.slice(1+i*stride,1+(i+1)*stride);
if(version!==1&&(b[version===2?13:16]!==width||b[version===2?14:17]!==height))return null;
const center:readonly [number,number]=version===3?[b[3],b[4]]:[b[1],b[2]];
if(center[0]<i*width/2||center[0]>(i+1)*width/2||center[1]<0||center[1]>height)return null;
const orientation=b.slice(version===3?5:3,version===3?8:6) as unknown as Vec3;
if(orientation.some(v=>!bounded(v,360)))return null;
const lens:LensOptics={kind:version===3?'mei':'radial',center,orientation,polynomial:[0,0,0,0],focal:[1,1],xi:0,radial:[0,0,0],tangential:[0,0]};
if(version===3){
if(b[0]<0||b[0]>3||b[1]<=0||b[2]<=0||b[1]>width*2||b[2]>height*4||b.slice(11,16).some(v=>!bounded(v,100)))return null;
lens.xi=b[0];lens.focal=[b[1],b[2]];lens.radial=[b[11],b[12],b[13]];lens.tangential=[b[14],b[15]];
}else{
if(b[0]<=0||b[0]>height)return null;
// The legacy angular scale is an open-source convention, not a vendor guarantee.
if(version===1)lens.polynomial=[b[0]/(96*radians),0,0,0];
else {
const c=b.slice(9,13),edge=polynomial(c,100*radians);if(edge<=0)return null;
lens.polynomial=c.map(v=>v*b[0]/edge) as unknown as LensOptics['polynomial'];
let previous=0;for(let t=1;t<=100;t++){const r=polynomial(lens.polynomial,t*radians);if(!Number.isFinite(r)||r<=previous)return null;previous=r;}
}
}
lenses.push(lens);
}
return {version,width,height,lenses:lenses as unknown as PanoramaCalibration['lenses']};
}
/** Existing operator left/right rotations own the mounting; factory residuals refine it.
* Input rays use the viewer's x-forward/y-right/z-up convention. Lens 0 is the left half.
*/
export function lensDirection(ray:Vec3,lens:LensOptics,index:number,rotation:number):Vec3 {
let [x,y,z]=[-ray[1],-ray[2],-ray[0]];
const [yaw,pitch,roll]=lens.orientation.map(v=>v*radians);
[x,z]=[Math.cos(yaw)*x+Math.sin(yaw)*z,-Math.sin(yaw)*x+Math.cos(yaw)*z];
[y,z]=[Math.cos(pitch)*y-Math.sin(pitch)*z,Math.sin(pitch)*y+Math.cos(pitch)*z];
if(index===1){y=-y;z=-z;}
const residual=roll-Math.round(roll/(Math.PI/2))*(Math.PI/2);
const angle=(index===1?Math.PI:0)-rotation*radians-residual;
return [Math.cos(angle)*x-Math.sin(angle)*y,Math.sin(angle)*x+Math.cos(angle)*y,z];
}
export function projectLens(calibration:PanoramaCalibration,index:0|1,ray:Vec3,rotation:number):readonly [number,number]|null {
const lens=calibration.lenses[index],[x,y,z]=lensDirection(ray,lens,index,rotation),theta=Math.atan2(Math.hypot(x,y),z);
if(theta>100*radians)return null;
let px:number,py:number;
if(lens.kind==='radial'){
const r=polynomial(lens.polynomial,theta),norm=Math.max(Math.hypot(x,y),1e-9);px=lens.center[0]+r*x/norm;py=lens.center[1]+r*y/norm;
}else{
const denominator=z+lens.xi;if(denominator<=1e-6)return null;
const u=x/denominator,v=y/denominator,r2=u*u+v*v,[k1,k2,k3]=lens.radial,[p1,p2]=lens.tangential;
const scale=1+r2*(k1+r2*(k2+r2*k3));
px=lens.center[0]+lens.focal[0]*(scale*u+2*p1*u*v+p2*(r2+2*u*u));
py=lens.center[1]+lens.focal[1]*(scale*v+p1*(r2+2*v*v)+2*p2*u*v);
}
if(!Number.isFinite(px)||!Number.isFinite(py)||px<index*calibration.width/2||px>(index+1)*calibration.width/2||py<0||py>calibration.height)return null;
return [px/calibration.width,py/calibration.height];
}
/** The live X4 packs a centred square crop from each rectangular sensor. SDK offsets
* shift that crop relative to the centre. Keep this mapping separate from lens optics.
*/
export function liveCalibration(value:unknown):PanoramaCalibration|null {
if(!value||typeof value!=='object')return null;
const data=value as {offsets?:unknown;crop?:Record<string,unknown>};
if(!Array.isArray(data.offsets)||data.offsets.length>4)return null;
const candidates=data.offsets.map(parseCalibration).filter((v):v is PanoramaCalibration=>v!==null);
// Prefer the explicit unified camera model, avoiding the legacy radius-angle guess.
const c=candidates.find(v=>v.version===3)??candidates.find(v=>v.version===2)??candidates[0];if(!c)return null;
const crop=data.crop;if(!crop)return null;
const [sw,sh,w,h,x,y]=['source_width','source_height','width','height','x','y'].map(k=>crop[k]);
if([sw,sh,w,h,x,y].some(v=>typeof v!=='number'||!Number.isInteger(v)||!bounded(v,65536)))return null;
const sourceWidth=sw as number,sourceHeight=sh as number,width=w as number,height=h as number;
if(sourceWidth!==c.width/2||sourceHeight!==c.height||width<=0||height<=0||width!==height||width>sourceWidth||height>sourceHeight)return null;
const ox=(sourceWidth-width)/2+(x as number),oy=(sourceHeight-height)/2+(y as number);
if(ox<0||oy<0||ox+width>sourceWidth||oy+height>sourceHeight)return null;
return {...c,width:2,height:1,lenses:c.lenses.map((lens,i)=>({...lens,
center:[i+(lens.center[0]-i*sourceWidth-ox)/width,(lens.center[1]-oy)/height],
focal:[lens.focal[0]/width,lens.focal[1]/height],
polynomial:lens.polynomial.map(v=>v/width),
})) as unknown as PanoramaCalibration['lenses']};
}
@@ -0,0 +1,20 @@
import {projectLens,type PanoramaCalibration,type Vec3} from './panoramaCalibration';
const median=(values:number[])=>{values.sort((a,b)=>a-b);return values[Math.floor(values.length/2)];};
/** Robust same-direction overlap samples, never whole-lens averages of different scenery.
* Bounded 384-ray analysis once per second, in the decoded display signal. It avoids clipping
* and limits correction to 33%; nearby parallax must not drive unlimited colour changes.
*/
export function overlapGains(pixels:Uint8ClampedArray,width:number,height:number,calibration:PanoramaCalibration,rotations:readonly number[]):readonly [Vec3,Vec3]|null {
const ratios:number[][]=[[],[],[]];
for(const side of [-1,1])for(let lat=-72;lat<=72;lat+=3)for(const delta of [-2,0,2]){
const latitude=lat*Math.PI/180,longitude=(side*90+delta)*Math.PI/180;
const ray:Vec3=[Math.cos(latitude)*Math.cos(longitude),Math.cos(latitude)*Math.sin(longitude),Math.sin(latitude)];
const a=projectLens(calibration,0,ray,rotations[0]),b=projectLens(calibration,1,ray,rotations[1]);if(!a||!b)continue;
const sample=(uv:readonly number[])=>4*(Math.min(height-1,Math.floor(uv[1]*height))*width+Math.min(width-1,Math.floor(uv[0]*width)));
const ai=sample(a),bi=sample(b);
for(let channel=0;channel<3;channel++){const av=pixels[ai+channel],bv=pixels[bi+channel];if(av>18&&bv>18&&av<235&&bv<235)ratios[channel].push(Math.log(bv/av));}
}
if(ratios.some(v=>v.length<32))return null;
const gain=ratios.map(values=>{const middle=median(values);const inliers=values.filter(v=>Math.abs(v-middle)<.25);return inliers.length<24?1:Math.exp(Math.max(-Math.log(4/3),Math.min(Math.log(4/3),median(inliers)/2)));}) as unknown as Vec3;
return [gain,gain.map(v=>1/v) as unknown as Vec3];
}
@@ -0,0 +1,38 @@
// GPU projection from the camera's own optical parameters; one existing video texture.
const lens=(i:number)=>`
uniform mat3 pose${i}; uniform vec2 center${i},focal${i},tangential${i};
uniform vec3 radial${i},gain${i}; uniform vec4 polynomial${i}; uniform float kind${i},xi${i};
vec4 lens${i}(vec3 ray){
vec3 d=pose${i}*ray;float theta=atan(length(d.xy),d.z);vec2 pixel;
if(kind${i}<.5){
vec4 c=polynomial${i};float r=theta*(c.x+theta*(c.y+theta*(c.z+theta*c.w)));
pixel=center${i}+r*d.xy/max(length(d.xy),.000001);
}else{
vec2 p=d.xy/max(d.z+xi${i},.000001);float r2=dot(p,p);vec3 k=radial${i};vec2 t=tangential${i};
float scale=1.+r2*(k.x+r2*(k.y+r2*k.z));
vec2 distorted=scale*p+vec2(2.*t.x*p.x*p.y+t.y*(r2+2.*p.x*p.x),t.x*(r2+2.*p.y*p.y)+2.*t.y*p.x*p.y);
pixel=center${i}+focal${i}*distorted;
}
vec3 color=texture2D(image,vec2(pixel.x*.5,pixel.y)).rgb;
float valid=step(${i}.,pixel.x)*step(pixel.x,${i+1}.)*step(0.,pixel.y)*step(pixel.y,1.);
float weight=(1.-smoothstep(radians(87.),radians(93.),theta))*valid;
return vec4(color*gain${i},weight);
}`;
export const panoramaFragment=`precision highp float;
varying vec2 uv; uniform sampler2D image; uniform vec2 rotation; uniform float heading,calibrated;
const float PI=3.141592653589793;
${lens(0)}${lens(1)}
void main(){
float longitude=(uv.x-.5)*2.*PI+heading,latitude=(uv.y-.5)*PI;
vec3 ray=vec3(cos(latitude)*cos(longitude),cos(latitude)*sin(longitude),sin(latitude));
if(calibrated>.5){
vec4 a=lens0(ray),b=lens1(ray);float total=a.a+b.a;
if(total>.00001){gl_FragColor=vec4((a.rgb*a.a+b.rgb*b.a)/total,1.);return;}
}
// Compatibility view for old drivers or unrecognised calibration, without fake blending.
bool front=ray.x>=0.;float transverse=length(ray.yz),theta=atan(transverse,abs(ray.x));
vec2 p=vec2(front?ray.y:-ray.y,-ray.z)*theta/max(transverse,.000001)*(.495/(PI*.5));
float a=front?rotation.y:rotation.x;
p=vec2(cos(a)*p.x+sin(a)*p.y,-sin(a)*p.x+cos(a)*p.y);
gl_FragColor=texture2D(image,vec2((front?.5:0.)+(p.x+.5)*.5,p.y+.5));
}`;
+3 -2
View File
@@ -1,11 +1,12 @@
import type {SensorUiContribution} from '../../../../packages/sensor-ui/src/extensions';
import {X4Detail} from './X4Detail';
import {cameraLabel,cameraRowActions} from './model';
import {cameraLabel,cameraRowActions,cameraStatus} from './model';
import {X4Observation} from './X4Observation';
export const insta360X4SensorUi:SensorUiContribution={
kind:'insta360.x4',Detail:X4Detail,icon:'camera',retainOffline:true,
supportsPreparation:true,supportsRenaming:true,status:cameraLabel,
rowActions:cameraRowActions,
observation:{Session:X4Observation,views:device=>[{id:'left',label:`${device.name} Left Cam`},{id:'right',label:`${device.name} Right Cam`}]},
settingsFacts:device=>[{id:'serial',label:'Серийный номер',value:cameraStatus(device).serial||'Не получен'}],
observation:{Session:X4Observation,views:device=>[{id:'left',label:`${device.name} Left Cam`},{id:'right',label:`${device.name} Right Cam`},{id:'panorama',label:`${device.name} · панорама`}]},
};
+31 -3
View File
@@ -24,8 +24,8 @@ constexpr size_t MAX_PACKET = 4 * 1024 * 1024;
constexpr size_t MAX_QUEUE = 8 * 1024 * 1024;
constexpr size_t MAX_RESULT = 60 * 1024;
std::string quote(const std::string& value) {
if (value.size() > 1024) throw std::runtime_error("oversized SDK string");
std::string quote(const std::string& value, size_t limit = 1024) {
if (value.size() > limit) throw std::runtime_error("oversized SDK string");
std::ostringstream out;
out << '"';
for (unsigned char c : value) {
@@ -111,7 +111,7 @@ struct mc_x4 {
std::shared_ptr<Camera> camera;
std::shared_ptr<Frames> frames = std::make_shared<Frames>();
std::shared_ptr<Notifications> notifications = std::make_shared<Notifications>();
std::string firmware, result;
std::string firmware, serial, calibration = "null", result;
bool opened = false;
int preview = 0;
// Only the isolated worker calls control methods; callbacks use separate
@@ -145,6 +145,8 @@ struct mc_x4 {
}
}
std::string result = "{\"firmware\":" + quote(firmware) +
",\"serial\":" + quote(serial) +
",\"preview_calibration\":" + calibration +
",\"connected\":" + (connected ? "true" : "false") +
",\"preview\":" + std::to_string(preview) +
",\"recording\":" + std::to_string(notifications->recording) +
@@ -165,6 +167,30 @@ struct mc_x4 {
return complete(result);
}
void read_preview_calibration() {
// Read-only metadata from this session's camera. A missing/unknown
// calibration must not take down camera control or the raw lens feed.
calibration = "null";
try {
auto param = camera->GetPreviewParam();
const auto count = param.GetCalibrationCount();
if (!count || count > 4) return;
std::ostringstream out;
out << "{\"offsets\":[";
for (size_t i = 0; i < count; ++i) {
if (i) out << ',';
out << quote(param.GetCalibration(i), 8192);
}
out << "],\"crop\":{\"source_width\":" << param.GetCropSrcWidth()
<< ",\"source_height\":" << param.GetCropSrcHeight()
<< ",\"width\":" << param.GetCropDstWidth()
<< ",\"height\":" << param.GetCropDstHeight()
<< ",\"x\":" << param.GetCropOffsetX()
<< ",\"y\":" << param.GetCropOffsetY() << "}}";
calibration = out.str();
} catch (...) { calibration = "null"; }
}
std::string settings(CameraFunctionMode mode) {
if (!mode_supported(mode)) return INVALID;
if (!camera->SyncPhotographyOptions(mode)) return UNKNOWN;
@@ -380,11 +406,13 @@ mc_x4* mc_x4_open(const char* serial, const char* log_directory) {
const auto& device = handle->descriptors.front();
if (device.camera_type != CameraType::Insta360X4 || device.info.connection_type != ConnectionType::USB || device.serial_number != serial) return nullptr;
handle->firmware = device.fw_version;
handle->serial = device.serial_number;
handle->camera = std::make_shared<Camera>(device.info);
handle->camera->SetServicePort(9099); // private network namespace per instance
handle->camera->SetTimeout(10000);
handle->opened = handle->camera->Open();
if (!handle->opened) return nullptr;
handle->read_preview_calibration();
auto n = handle->notifications;
handle->camera->SetCaptureStateNotification([n](bool active) {
std::lock_guard<std::mutex> lock(n->mutex);
@@ -93,6 +93,18 @@ def test_discovery_never_selects_first_of_multiple_cameras(library):
assert library.test_count(0) == 0 and library.test_count(2) == 2
def test_details_include_session_identity_and_optics_without_starting_preview(camera):
api, _ = camera
result = call(camera, 1)["result"]
assert result["serial"] == "SYNTHETIC-X4"
assert len(result["preview_calibration"]["offsets"]) == 1
assert result["preview_calibration"]["crop"] == {
"source_width": 1920, "source_height": 960,
"width": 1920, "height": 960, "x": 0, "y": 0,
}
assert api.test_count(3) == 0 and api.test_count(6) == 0
def test_preview_stop_and_close_do_not_stop_recording(camera):
api, handle = camera
assert call(camera, 6)["state"] == "complete"
@@ -179,6 +191,20 @@ def test_early_camera_stop_notification_wins_over_start_acknowledgement(camera):
assert api.test_count(4) == 1
def test_unavailable_calibration_preserves_camera_control(library):
for mode in (1, 2):
library.test_calibration(mode)
handle = library.mc_x4_open(b"SYNTHETIC-X4", b"/unused")
assert handle
try:
result = call((library, handle), 1)["result"]
assert result["serial"] == "SYNTHETIC-X4"
assert result["preview_calibration"] is None
assert library.test_count(3) == 0 and library.test_count(6) == 0
finally:
library.mc_x4_close(handle)
class TestNativeBridge(unittest.TestCase):
@classmethod
def setUpClass(cls):
+18 -2
View File
@@ -10,7 +10,7 @@ int discovered = 1, opens = 0, closes = 0, freed = 0, writes = 0;
int record_starts = 0, record_stops = 0, previews = 0, preview_stops = 0;
bool recording = false, start_ack = true, preview_ack = true, connected = true;
bool stop_before_ack = false;
int function_mode = 7;
int function_mode = 7, calibration_mode = 0;
std::shared_ptr<ins_camera::StreamDelegate> delegate;
ins_camera::CaptureStateCallBack capture_callback;
std::shared_ptr<ins_camera::CaptureSettings> capture;
@@ -19,6 +19,21 @@ std::shared_ptr<ins_camera::ExposureSettings> exposure;
namespace ins_camera {
class CameraImpl {};
struct PreviewParam::Impl {};
PreviewParam::PreviewParam() = default;
PreviewParam::~PreviewParam() = default;
PreviewParam::PreviewParam(PreviewParam&&) noexcept = default;
PreviewParam& PreviewParam::operator=(PreviewParam&&) noexcept = default;
size_t PreviewParam::GetCalibrationCount() const { if (calibration_mode == 1) throw std::runtime_error("unavailable"); return calibration_mode == 2 ? 5 : 1; }
std::string PreviewParam::GetCalibration(size_t) const { return "2_480_480_480_0_0_0_480_1440_480_0_0_0_1920_960_0"; }
uint32_t PreviewParam::GetCropSrcWidth() const { return 1920; }
uint32_t PreviewParam::GetCropSrcHeight() const { return 960; }
uint32_t PreviewParam::GetCropDstWidth() const { return 1920; }
uint32_t PreviewParam::GetCropDstHeight() const { return 960; }
int32_t PreviewParam::GetCropOffsetX() const { return 0; }
int32_t PreviewParam::GetCropOffsetY() const { return 0; }
PreviewParam Camera::GetPreviewParam() const { return PreviewParam(); }
class ExposureSettingsPrivate {
public:
int iso = 100, ev = 0;
@@ -109,13 +124,14 @@ void ExposureSettings::SetExposureMode(PhotographyOptions_ExposureMode value) {
extern "C" {
void test_reset() {
discovered = 1; opens = closes = freed = writes = record_starts = record_stops = previews = preview_stops = 0;
recording = stop_before_ack = false; connected = start_ack = preview_ack = true; function_mode = 7;
recording = stop_before_ack = false; connected = start_ack = preview_ack = true; function_mode = 7; calibration_mode = 0;
delegate.reset(); capture_callback = nullptr;
capture = std::make_shared<ins_camera::CaptureSettings>(); exposure = std::make_shared<ins_camera::ExposureSettings>();
}
int test_count(int which) {
switch (which) { case 0: return opens; case 1: return closes; case 2: return freed; case 3: return writes; case 4: return record_starts; case 5: return record_stops; case 6: return previews; case 7: return preview_stops; default: return -1; }
}
void test_calibration(int mode) { calibration_mode = mode; }
void test_discovered(int count) { discovered = count; }
void test_ack(int type, int value) { if (type == 0) start_ack = value; else if (type == 1) preview_ack = value; else stop_before_ack = value; }
void test_connected(int value) { connected = value; }
+1 -1
View File
@@ -16,7 +16,7 @@ sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from debian import package # noqa: E402
from fetch_sdk import verify # noqa: E402
VERSION = "0.1.3-9"
VERSION = "0.1.3-10"
WHEELS = {
"aiohappyeyeballs",
"aiohttp",
@@ -0,0 +1,50 @@
"""Validation and read-only migration of the former operator-local preferences."""
import hashlib
import json
from pathlib import Path
SCHEMA = "missioncore.observation/v1"
class RevisionConflict(ValueError):
pass
def path(root: Path, vehicle: str) -> Path:
return root / "observation" / hashlib.sha256(vehicle.encode()).hexdigest() / "method.json"
def validate(document: dict) -> dict:
if not isinstance(document, dict) or set(document) != {"layouts", "cameras"}:
raise ValueError("Invalid observation configuration")
if len(json.dumps(document, allow_nan=False).encode()) > 500000:
raise ValueError("Observation configuration is too large")
layouts, cameras = document["layouts"], document["cameras"]
if not isinstance(layouts, dict) or layouts.get("version") != 1:
raise ValueError("Invalid layouts")
if not isinstance(cameras, dict) or len(cameras) > 128:
raise ValueError("Invalid camera settings")
for device, camera in cameras.items():
if not isinstance(device, str) or not 0 < len(device) <= 512 or not isinstance(camera, dict):
raise ValueError("Invalid camera identity")
if set(camera) != {"rotations", "panoramaYaw"} or not isinstance(camera["rotations"], dict):
raise ValueError("Invalid camera presentation")
if set(camera["rotations"]) - {"left", "right"}:
raise ValueError("Unknown lens")
if any(type(v) is not int or v not in (0, 90, 180, 270) for v in camera["rotations"].values()):
raise ValueError("Invalid rotation")
yaw = camera["panoramaYaw"]
if type(yaw) not in (int, float) or not 0 <= yaw < 360:
raise ValueError("Invalid panorama direction")
return document
def read(root: Path, vehicle: str) -> dict:
target = path(root, vehicle)
if not target.exists():
return {"schema": SCHEMA, "revision": 0, "document": None}
if target.is_symlink() or target.stat().st_size > 1100000:
raise ValueError("Invalid observation file")
value = json.loads(target.read_bytes())
if (not isinstance(value, dict) or set(value) != {"schema", "revision", "document"}
or value["schema"] != SCHEMA or type(value["revision"]) is not int
or not 1 <= value["revision"] < 2**53-1):
raise ValueError("Invalid observation file")
validate(value["document"])
return value
+4
View File
@@ -46,6 +46,8 @@ class FleetRegistry:
self.monitor = MonitorReceiver(root)
from .rover_control import RoverControl
self.rover_control = RoverControl()
from .rover_configuration import RoverConfigurations
self.rover_configurations = RoverConfigurations(root)
self.trust = CoreTrust(root)
path = root / "fleet.sqlite3"
if path.is_symlink():
@@ -489,6 +491,7 @@ class FleetRegistry:
return 400, {"error": "Invalid Node inventory"}
sensor_state = sensors.validate_inventory(value, node_id)
sensor_response = sensors.heartbeat(row, value)
configuration_response = self.rover_configurations.heartbeat(node_id, value)
archive_ack = None
archive_started = time.monotonic()
try:
@@ -544,6 +547,7 @@ class FleetRegistry:
"monitor_ack": monitor_ack,
"ok": True,
"client_pem": row["binding"]["client_pem"],
**configuration_response,
**sensor_response,
**enrollment_response,
}
+117
View File
@@ -0,0 +1,117 @@
"""Confirmed onboard configuration mirror and bounded paired-channel requests.
Only an authenticated Node heartbeat can write a confirmed configuration. A
browser request is a transient proposal; its HTTP success requires onboard ACK.
"""
from __future__ import annotations
import copy
import hashlib
import json
import math
import secrets
import threading
import time
from pathlib import Path
from .observation_configuration import validate, RevisionConflict
from .trust import atomic_private
SCHEMA = "missioncore.rover-configuration/v1"
class Unavailable(RuntimeError):
pass
class RoverConfigurations:
def __init__(self, root: Path):
self.root = root / "rover-configurations"
self.condition = threading.Condition()
self.live: dict[str, dict] = {}
self.pending: dict[str, dict] = {}
def path(self, node: str) -> Path:
return self.root / hashlib.sha256(node.encode()).hexdigest() / "Rover Config.json"
def validate(self, node: str, value: dict) -> dict:
if (not isinstance(value, dict) or set(value)-{"schema", "node_id", "name", "revision", "observation", "last_change"}
or value.get("schema") != SCHEMA or value.get("node_id") != node
or type(value.get("revision")) is not int or not 0 <= value["revision"] < 2**53-1
or not isinstance(value.get("name"), str) or len(value["name"]) > 256
or "observation" not in value
or ("last_change" in value and (not isinstance(value["last_change"], str) or len(value["last_change"]) != 32))):
raise ValueError("Invalid onboard configuration")
if value["observation"] is not None:
validate(value["observation"])
return value
def _mirror(self, node: str) -> dict | None:
path = self.path(node)
if not path.exists():
return None
if path.is_symlink() or path.stat().st_size > 524288:
raise ValueError("Invalid configuration mirror")
return self.validate(node, json.loads(path.read_bytes()))
def view(self, node: str) -> dict:
with self.condition:
live = self.live.get(node, {})
writable = live.get("ready", False) and time.monotonic()-live.get("seen", 0) <= 15
value = live.get("configuration") or self._mirror(node)
return {"schema": SCHEMA, "revision": value["revision"] if value else 0,
"document": value["observation"] if value else None,
"source": "onboard" if writable else "mirror", "writable": bool(writable),
"available": value is not None}
def heartbeat(self, node: str, payload: dict) -> dict:
with self.condition:
offered = payload.get("rover_configuration")
value = None
if isinstance(offered, dict) and offered.get("state") == "ready":
try:
value = self.validate(node, offered["configuration"])
target = self.path(node)
if self._mirror(node) != value:
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
atomic_private(target, (json.dumps(value, ensure_ascii=False, indent=2)+"\n").encode())
except (KeyError, ValueError, TypeError, OSError):
value = None
self.live[node] = {"ready": value is not None, "configuration": copy.deepcopy(value), "seen": time.monotonic()}
pending = self.pending.get(node)
if pending is None:
return {}
command = pending["command"]
if value is not None:
result = offered.get("result")
# last_change survives Node restart and lost response packets.
if (value.get("last_change") == command["id"]
and value["revision"] == command["expected_revision"]+1
and value["observation"] == command["observation"]):
pending["result"] = self.view(node)
elif isinstance(result, dict) and result.get("id") == command["id"]:
pending["error"] = "conflict" if result.get("state") == "conflict" else "unavailable"
if "result" in pending or "error" in pending:
self.condition.notify_all()
return {}
if value is None or time.time() >= command["expires_at"]:
return {}
return {"rover_configuration_change": copy.deepcopy(command)}
def update(self, node: str, name: str, document: dict, revision: int, *, timeout: float = 16) -> dict:
validate(document)
with self.condition:
before = self.view(node)
if not before["writable"]:
raise Unavailable("Борт не подтвердил готовность сохранять конфигурацию. Изменения пока не сохранены.")
if before["revision"] != revision or node in self.pending:
raise RevisionConflict("Конфигурация уже изменена или сохраняется в другом окне. Загрузите настройки с борта.")
request = {"command": {"id": secrets.token_hex(16), "name": name,
"expected_revision": revision, "observation": copy.deepcopy(document),
"expires_at": math.ceil(time.time()+timeout)}}
self.pending[node] = request
try:
self.condition.wait_for(lambda: "result" in request or "error" in request, timeout)
if "result" in request:
return request["result"]
if request.get("error") == "conflict":
raise RevisionConflict("Конфигурация на борту изменилась. Загрузите её перед повторным сохранением.")
raise Unavailable("Подтверждение записи на борт не получено. Загрузите настройки, чтобы проверить результат.")
finally:
self.pending.pop(node, None)
+52
View File
@@ -99,6 +99,58 @@ def board_layout_patch(vehicle_id: str, body: BoardLayoutChange, response: Respo
raise HTTPException(500, "Не удалось сохранить раскладку аппарата.") from None
class ObservationConfigurationChange(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=0, lt=2**53-1, strict=True)
document: dict
@router.get("/{vehicle_id}/observation-configuration")
def observation_configuration_read(vehicle_id: str, response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
row = fleet.find(vehicle_id)
value = fleet.rover_configurations.view(row["node_id"])
# A one-time draft may migrate only after reading the board's empty
# configuration. It becomes durable solely through the normal PUT/ACK.
if value["available"] and value["document"] is None:
from k1link.fleet.observation_configuration import read
value["draft"] = read(fleet.root, vehicle_id)["document"]
return value
except PairingError as error:
raise HTTPException(404, str(error)) from None
except (OSError, ValueError):
raise HTTPException(500, "Не удалось прочитать настройки центра наблюдения.") from None
@router.put("/{vehicle_id}/observation-configuration")
def observation_configuration_write(vehicle_id: str, body: ObservationConfigurationChange,
response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
from k1link.fleet.observation_configuration import RevisionConflict
from k1link.fleet.rover_configuration import Unavailable
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
row = fleet.find(vehicle_id)
if row["enrollment"] != "paired":
raise Unavailable("Борт не подключён.")
# Never hold the fleet lock while waiting for its authenticated heartbeat.
return fleet.rover_configurations.update(row["node_id"], row["name"], body.document, body.expected_revision)
except PairingError as error:
raise HTTPException(404, str(error)) from None
except RevisionConflict as error:
raise HTTPException(409, str(error)) from None
except Unavailable as error:
raise HTTPException(503, str(error)) from None
except ValueError:
raise HTTPException(422, "Недопустимая конфигурация наблюдения.") from None
except OSError:
raise HTTPException(500, "Не удалось сохранить настройки центра наблюдения.") from None
@router.get("/{vehicle_id}/monitor")
def board_monitor(vehicle_id: str, response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)],
@@ -0,0 +1,71 @@
import copy
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
from k1link.fleet import observation_configuration as observation
from k1link.fleet.rover_configuration import RoverConfigurations, SCHEMA, Unavailable
DOCUMENT = {"layouts": {"version": 1, "selected": "auto", "layout": {"version": 1, "hidden": ["map"]}, "presets": []}, "cameras": {"camera-a": {"rotations": {"left": 90, "right": 270}, "panoramaYaw": 45}}}
def snapshot(revision=0, document=None, change=None):
value={"schema":SCHEMA,"node_id":"node-a","name":"Rover 006","revision":revision,"observation":document}
if change:value["last_change"]=change
return {"rover_configuration":{"state":"ready","configuration":value}}
def dispatch(store):
for _ in range(100):
reply=store.heartbeat("node-a",snapshot())
if reply:return reply["rover_configuration_change"]
time.sleep(.005)
raise AssertionError("No pending request")
def test_browser_proposal_is_not_saved_before_onboard_receipt(tmp_path):
store=RoverConfigurations(tmp_path)
with pytest.raises(Unavailable):store.update("node-a","Rover 006",DOCUMENT,0)
assert not store.path("node-a").exists()
store.heartbeat("node-a",snapshot())
with ThreadPoolExecutor(max_workers=1) as pool:
result=pool.submit(store.update,"node-a","Rover 006",DOCUMENT,0)
change=dispatch(store)
assert not result.done()
assert json.loads(store.path("node-a").read_text())["observation"] is None
store.heartbeat("node-a",snapshot(1,DOCUMENT,change["id"]))
assert result.result(timeout=1)["document"]==DOCUMENT
assert store.path("node-a").stat().st_mode&0o777==0o600
assert RoverConfigurations(tmp_path).view("node-a")["document"]==DOCUMENT
assert not RoverConfigurations(tmp_path).view("node-a")["writable"]
assert not store.view("node-b")["available"]
def test_conflicts_timeout_and_late_onboard_commit_reconcile(tmp_path):
store=RoverConfigurations(tmp_path);store.heartbeat("node-a",snapshot())
with ThreadPoolExecutor(max_workers=1) as pool:
result=pool.submit(store.update,"node-a","Rover 006",DOCUMENT,0,timeout=.15)
change=dispatch(store)
with pytest.raises(observation.RevisionConflict):store.update("node-a","Rover 006",DOCUMENT,0)
with pytest.raises(Unavailable):result.result(timeout=1)
assert store.view("node-a")["document"] is None
store.heartbeat("node-a",snapshot(1,DOCUMENT,change["id"]))
assert store.view("node-a")["document"]==DOCUMENT
with pytest.raises(observation.RevisionConflict):store.update("node-a","Rover 006",DOCUMENT,0)
def test_wrong_node_or_corrupt_mirror_cannot_confirm_save(tmp_path):
store=RoverConfigurations(tmp_path);store.heartbeat("node-a",snapshot())
store.heartbeat("node-b",snapshot())
assert not store.path("node-b").exists()
store.path("node-a").write_text("{broken")
store.heartbeat("node-a",snapshot(1,DOCUMENT))
assert store.path("node-a").read_text()=="{broken"
assert not store.live["node-a"]["ready"]
@pytest.mark.parametrize("rotation",[45,True,"90",-90,360])
def test_invalid_rotations_rejected(rotation):
invalid=copy.deepcopy(DOCUMENT);invalid["cameras"]["camera-a"]["rotations"]["left"]=rotation
with pytest.raises(ValueError):observation.validate(invalid)
def test_unsupported_node_cannot_accept_writes_and_mirror_survives(tmp_path):
store=RoverConfigurations(tmp_path);store.heartbeat("node-a",snapshot(1,DOCUMENT))
store.heartbeat("node-a",{})
assert store.view("node-a")["document"]==DOCUMENT
with pytest.raises(Unavailable):store.update("node-a","Rover 006",DOCUMENT,1)