До публикации{status.presented&&device.frames?.mqtt_to_publish_ms!=null?device.frames.mqtt_to_publish_ms.toFixed(1):'—'} мс
>}
- timeline={!focusedAny&&scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
+ timeline={!focusedAny&&scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
media={{}} onClose={()=>{setCameraMaximized(false);setVisible(current=>{const next=new Set(current);next.delete('camera');return next;});}}
status={{status.cameraPresented?'Эфир':'Ожидание'}}
footer={Бортовой компьютерЭфир без буфера}>
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.css b/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.css
new file mode 100644
index 00000000..05606349
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.css
@@ -0,0 +1,7 @@
+.k1-management-mode {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--nodedc-space-3);
+}
+.k1-management-mode > :first-child { flex: 1 1 18rem; min-width: 0; }
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.tsx b/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.tsx
new file mode 100644
index 00000000..b295e655
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1ManagementControls.tsx
@@ -0,0 +1,53 @@
+import {useEffect,useState} from 'react';
+import {ActivityIndicator,Button,Description,Checker,ConfirmationModal,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
+import type {K1Management,ManagementOperation,K1Project} from './useK1Management';
+import './K1ManagementControls.css';
+
+type Confirmation={operation:ManagementOperation;title:string;description:string;projects?:K1Project[];revision?:string};
+export function K1ManagementControls({management:m,storage=false}:{management:K1Management;storage?:boolean}) {
+ const [mode,setMode]=useState<'data'|'storage'>('data'),[selected,setSelected]=useState([]);
+ const [confirmation,setConfirmation]=useState(null);
+ const projects=m.catalog?.projects??[];
+ useEffect(()=>{if(m.info?.usb_mode)setMode(m.info.usb_mode);},[m.info?.usb_mode]);
+ useEffect(()=>{setSelected([]);},[m.catalog]);
+ useEffect(()=>{if(storage&&m.canManage&&!m.catalog)void m.run('projects');},[storage,m.info]);
+ const label=m.info?.storage_type==='microSD'?'microSD':m.info?.storage_type==='external-usb'?'Внешний USB-накопитель':'Хранилище K1';
+ function askDelete(items:K1Project[]) {
+ setConfirmation({operation:'delete-projects',title:`Удалить проекты: ${items.length}?`,
+ description:`Записи будут удалены с K1 без возможности отмены: ${items.map(p=>p.name).join(', ')}.`,projects:items,revision:m.catalog?.catalog_revision});
+ }
+ return
+
+
+
+ setConfirmation({operation:mode==='storage'?'usb-storage':'usb-data',title:'Изменить режим USB?',description:mode==='storage'?'В режиме USB-накопителя сканирование недоступно. Для новой съёмки верните канал управления.':'K1 вернётся в режим канала управления по USB Ethernet.'})}>Инициализировать режим
+
+ {!m.canSwitchToStorage&&Режим USB-накопителя отключает канал управления по USB. Для переключения и возврата подключите K1 через Bridge. Список проектов доступен без смены режима.}
+ void m.run('info')}>Обновить состояние
+
+ {storage?
+
+ setSelected(checked?projects.map(p=>p.id):[])}/>
+ void m.run('projects')}>Обновить список
+ askDelete(projects.filter(p=>selected.includes(p.id)))}>Удалить выбранное
+
)}
+ {m.catalog&&!projects.length&&На K1 нет проектов.}
+ {!m.catalog&&!m.busy&&Обновите список проектов.}
+ setConfirmation({operation:'format-storage',title:'Очистить диск K1?',description:'Все данные основного хранилища K1 будут удалены форматированием. Это действие нельзя отменить.'})}>Очистить диск
+ :
+
+ setConfirmation({operation:'reboot',title:'Перезагрузить K1?',description:'Связь со сканером временно прервётся. Бортовой компьютер останется включённым.'})}>Перезагрузить устройство
+ setConfirmation({operation:'power-off',title:'Выключить K1?',description:'Для следующего включения потребуется кнопка питания на сканере. Бортовой компьютер останется включённым.'})}>Выключить устройство
+
+ }
+ {!m.ready&&Обслуживание доступно при подтверждённом подключении и после завершения съёмки K1.}
+ {m.busy&& Ожидаем ответ K1…}
+ {m.message&&{m.message}}
+ setConfirmation(null)}
+ onConfirm={async()=>{if(!confirmation)return;const request=confirmation;const result=await m.run(request.operation,request.projects?.map(p=>p.id),request.revision);setConfirmation(null);if(result?.status==='succeeded'&&storage)void m.run('projects');}}/>
+
;
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1Observation.tsx b/plugins/xgrids-k1/frontend/src/sensors/K1Observation.tsx
index 1885fa35..640c58c2 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/K1Observation.tsx
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1Observation.tsx
@@ -1,23 +1,80 @@
+import {SpatialScene,EmptySpatialStage,heightSlice,ObservationTimeline,useLiveRerunPlayback} from '@mission-core/sensor-sdk';
+import {useK1SceneSettings} from './useK1SceneSettings';
+import {useK1CameraPreview} from './useK1CameraPreview';
+import './livePreview.css';
import {observationRerun} from './observationRerun';
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
-import {Icon,IconButton} from '@nodedc/ui-react';
+import {Button,Description,Icon,IconButton,ToastStack,RangeControl} from '@nodedc/ui-react';
import {ObservationHeader,type SensorObservationProps} from '@mission-core/sensor-sdk';
import {useK1Preview,pendingPreview,type PreviewStatus} from './useK1Preview';
+import {K1ObservationAction} from './K1ObservationAction';
+import {perform} from './runtime';
+import {k1ConnectionNotice,k1ManualState} from './presentation';
-function ActiveK1Observation({device,transport,enabled,views,createRerunHost}:SensorObservationProps){
- const spatial=useRef(null),plan=useRef(null),video=useRef(null);
- const [status,setStatus]=useState(pendingPreview),[generation,setGeneration]=useState(0);const attempts=useRef(0);
+type ActiveProps=SensorObservationProps&{stop:()=>void;pending:boolean};
+function PointPane({view,...props}:ActiveProps&{view:SensorObservationProps['views'][number]}){
+ const {device,transport,createRerunHost}=props;
+ const spatial=useRef(null),viewport=useRef(null),video=useRef(null);
+ const [status,setStatus]=useState(pendingPreview),[generation,setGeneration]=useState(0);
+ const scene=useK1SceneSettings(device,transport,()=>{}, {view:view.id,settings:props.sceneProfiles?.[view.id],save:value=>props.onSceneChange?.(view.id,value)});
+ const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
+ const onBounds=useCallback((next:{min:number;max:number})=>setBounds(old=>old&&Math.abs(old.min-next.min)<.01&&Math.abs(old.max-next.max)<.01?old:next),[]);
+ const floor=scene.draft.heightFloor??null,ceiling=scene.draft.heightCeiling??null;
+ const range=bounds?{min:Math.min(0,bounds.min,floor??Infinity),max:Math.max(80,bounds.max,ceiling??-Infinity)}:null;
+ const current=useRef({device,transport,settings:scene.draft,view:view.id,onBounds});current.current={device,transport,settings:scene.draft,view:view.id,onBounds};
+ const host=useMemo(()=>observationRerun(createRerunHost,()=>current.current),[createRerunHost]);
const report=useCallback((value:PreviewStatus)=>setStatus(value),[]);
- const host=useMemo(()=>observationRerun(createRerunHost,plan),[createRerunHost]);
- useK1Preview(device,transport,host,spatial,video,report,generation,enabled);
- useEffect(()=>{if(!status.retry)return;const timer=setTimeout(()=>setGeneration(v=>v+1),Math.min(30000,2000*2**Math.min(attempts.current++,4)));return()=>clearTimeout(timer);},[status.retry]);
- return <>{views.map(view=>{const points=view.id!=='camera',live=points?status.presented:status.cameraPresented;return createPortal(
{manual.connected?(manual.active?'Состояние сканирования доступно в управлении K1.':'Активируйте устройство кнопкой Play в шапке вьюпорта.'):k1ConnectionNotice(props.device,props.fresh!==false)}
+ {!manual.connected&&!manual.active&&props.reconnect&&Подключить K1}
+
+
,view.target,view.id))}>;
+ return <>{toast}void stop()} pending={pending}/>>;
}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1ObservationAction.tsx b/plugins/xgrids-k1/frontend/src/sensors/K1ObservationAction.tsx
new file mode 100644
index 00000000..fe266608
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1ObservationAction.tsx
@@ -0,0 +1,15 @@
+import {Icon,IconButton} from '@nodedc/ui-react';
+import type {Sensor} from './runtime';
+import {k1ManualState} from './presentation';
+
+/** Play opens the named-session workflow; Stop acts on the current acquisition. */
+export function K1ObservationAction({device,fresh,configure,stop,pending=false}:{
+ device:Sensor;fresh:boolean;configure?:()=>void;stop?:()=>void;pending?:boolean;
+}){
+ const manual=k1ManualState(device,fresh);
+ if(!manual.connected&&!manual.active)return null;
+ if(manual.showStop)return ;
+ if(!configure)return null;
+ return ;
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1SceneWindows.tsx b/plugins/xgrids-k1/frontend/src/sensors/K1SceneWindows.tsx
index 28fec67f..37a9e8d5 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/K1SceneWindows.tsx
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1SceneWindows.tsx
@@ -10,7 +10,13 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
connected: boolean;
}) {
const title = tool === 'source' ? 'Визуальный движок' : tool === 'layers' ? 'Слои сцены' : 'Отображение';
- return { scene.flush(); close(); }}>
+ return { scene.flush(); close(); }}>
+
+ ;
+}
+
+export function K1SceneControls({tool,scene,connected}:{tool:SceneTool|null;scene:K1SceneState;connected:boolean}) {
+ return <>
{tool === 'display' && }
{tool === 'layers' && }
{tool === 'source' &&
@@ -19,5 +25,5 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
Живой просмотр
Потоки открываются автоматически после запуска устройства. Запись сохраняется на бортовом компьютере.
}]}/>}
- ;
+ >;
}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/K1SettingsWindow.tsx b/plugins/xgrids-k1/frontend/src/sensors/K1SettingsWindow.tsx
new file mode 100644
index 00000000..cd0337f9
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/K1SettingsWindow.tsx
@@ -0,0 +1,33 @@
+import {useEffect,useState} from 'react';
+import {FeatureSettingsWindow} from '@nodedc/ui-react';
+import type {SensorDetailProps} from '@mission-core/sensor-sdk';
+import {K1Detail} from './K1Detail';
+import {K1SceneControls,type SceneTool} from './K1SceneWindows';
+import {useK1SceneSettings} from './useK1SceneSettings';
+import {useK1Management} from './useK1Management';
+import {K1ManagementControls} from './K1ManagementControls';
+import {k1ManualState} from './presentation';
+
+/** One gear surface; the existing scene owner and persistent viewport profile stay authoritative. */
+export function K1SettingsWindow(props:SensorDetailProps) {
+ const [section,setSection]=useState<'connection'|'storage'|SceneTool>('connection');
+ const management=useK1Management(props);
+ const scene=useK1SceneSettings(props.device,props.transport,props.failure,props.sceneProfile);
+ const close=()=>{scene.flush();props.back();};
+ const connected=k1ManualState(props.device,props.enabled).connected;
+ useEffect(()=>{if(!connected&&(section==='layers'||section==='display'))setSection('connection');},[connected,section]);
+ return {scene.flush();setSection(value);}} onClose={close}>
+
+ {section==='connection'&&}
+ {section==='storage'&&}
+ {(section==='layers'||section==='display')&&}
+ ;
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/enrollment.ts b/plugins/xgrids-k1/frontend/src/sensors/enrollment.ts
index 687c398e..b1d35e7d 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/enrollment.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/enrollment.ts
@@ -31,6 +31,7 @@ export function enrollmentCommand(state:EnrollmentState,action:EnrollmentCommand
export function enrollmentAllowed(state:EnrollmentState|null,action:EnrollmentCommand['action']):boolean {
if(!state?.available||state.fresh===false)return false;
+ if(action==='reset')return state.can_reset===true&&state.supported_actions?.includes('reset')===true;
if(!state.allowed_actions)return true; // Older driver, server admission still applies.
if(action==='networks')return true;
const permissions=action==='scan'?['scan-ble']:action==='connect'?['provision-fresh-device']:
@@ -76,13 +77,18 @@ export async function enroll(transport:EnrollmentTransport,initial:EnrollmentSta
await pause();assertActive();
try{operation=await transport.operation(command.operation_id);}catch{operation=null;}
}
- if(action==='scan'||action==='networks'){
+ if(action==='reset'&&(operation.state!=='complete'||!operation.result||state.command_result?.operation_id!==command.operation_id||state.command_result.status!=='succeeded'||state.mode_revision!==(initial.mode_revision??-1)+1))throw new Error('Сброс подключения пока не подтверждён. Обновите состояние K1.');
+ if(action==='scan'||action==='networks'||action==='reset'){
if(action==='scan'&&(operation.state!=='complete'||!operation.result||
(state.command_result?.operation_id===command.operation_id&&state.command_result.status!=='succeeded')))
throw new Error(scanFailure);
if(operation.state!=='complete'||!operation.result)throw new Error(operation.error||unknownResult);
return state;
}
+ // A terminal delivery without a driver result has no correlated bootstrap result.
+ // Unknown still means unconfirmed: release the UI without replaying a command
+ // or inferring success from a later unrelated connected snapshot.
+ if(!operation.result)throw new Error(operation.error||unknownResult);
// A network ACK can precede its owned DeviceInfo bootstrap. Keep observing
// the same attempt; no second POST, verify command or target selection occurs.
while(true){
@@ -156,6 +162,23 @@ export function enrollmentProofCurrent(proof:EnrollmentProof|null,state:Enrollme
return !!current&&Object.entries(proof).every(([key,value])=>current[key as keyof EnrollmentProof]===value);
}
+/** Existing proof only: no response never proves that the scanner is powered off. */
+export function enrollmentRecoveryNotice(state:EnrollmentState):string {
+ if(!state.available||state.fresh===false)return 'Нет свежих сведений с БК. Восстанавливаем связь.';
+ const verification=state.verification;
+ if(verification?.status==='accepted'||verification?.status==='running')return 'Проверяем связь и состояние K1.';
+ if(verification?.status==='failed'){
+ const code=verification.error_code;
+ if(code==='connection-verify-route-mismatch')return 'БК не видит K1 в общей сети. Проверьте подключение устройств к одной сети.';
+ if(code==='connection-verify-mqtt-unreachable')return 'K1 не отвечает в общей сети. Проверьте питание и подключение K1 к сети, затем повторите проверку.';
+ if(['connection-verify-device-not-rediscovered','connection-verify-device-not-connectable','connection-verify-status-read-timeout','connection-verify-exact-uuid-scan-timeout','connection-verify-address-unavailable'].includes(code??''))return 'K1 недоступен. Проверьте питание, дождитесь загрузки сканера и проверьте подключение к сети. Затем повторите проверку.';
+ return 'Не удалось подтвердить состояние K1. Проверьте подключение и повторите проверку.';
+ }
+ if(state.connected)return state.acquisition_recovery?.state==='ceased'?'K1 подключён. Предыдущая съёмка завершена.':'Связь с K1 подтверждена.';
+ if(['active','prepared'].includes(state.acquisition_recovery?.state??''))return 'Связь с предыдущей съёмкой не подтверждена. Проверьте состояние K1.';
+ return 'Проверьте связь с K1 в ранее настроенной общей сети.';
+}
+
export function bridgeFormValid(ssid:string,password:string):boolean{
const bytes=new TextEncoder();return bytes.encode(ssid).length>0&&bytes.encode(ssid).length<=32&&bytes.encode(password).length>0&&bytes.encode(password).length<=64;
}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/livePreview.css b/plugins/xgrids-k1/frontend/src/sensors/livePreview.css
index e30fddd4..28d7fd2a 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/livePreview.css
+++ b/plugins/xgrids-k1/frontend/src/sensors/livePreview.css
@@ -4,3 +4,8 @@
.k1-preview.sensor-viewer-expanded .spatial-workspace {height:calc(100vh - 150px)}
.k1-camera-content {position:relative;height:100%;min-height:0}
.k1-camera-notice {position:absolute;inset:0}
+
+.k1-observation-scene .spatial-workspace {height:100%;min-height:0;width:100%}
+.k1-observation-scene .spatial-viewport-shell {min-height:0}
+
+.k1-observation-scene .scene-information { top: calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); }
diff --git a/plugins/xgrids-k1/frontend/src/sensors/localCameraPreview.ts b/plugins/xgrids-k1/frontend/src/sensors/localCameraPreview.ts
new file mode 100644
index 00000000..617df239
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/localCameraPreview.ts
@@ -0,0 +1,20 @@
+import type {Sensor,SensorTransport} from './runtime';
+import {localPreview} from './localPreview';
+import {previewCamera} from './previewCamera';
+import {previewFrames} from './previewFrames';
+/** Existing onboard MSE carrier, independent of cloud view admission. */
+export function localCameraPreview(device:Sensor,transport:SensorTransport,video:HTMLVideoElement,report:(state:{camera:string;cameraPresented:boolean})=>void){
+ let active=true,decoded=false,last=-1,progress=0;
+ const failed=()=>{if(active)report({camera:'Камера: изображение недоступно',cameraPresented:false});};
+ const ready=()=>{decoded=true;progress=performance.now();};
+ let decoder=previewCamera(video,ready,failed);
+ const connection=localPreview(device,transport,{media:'camera',acquisition_id:device.control?.acquisition_id,view_id:crypto.randomUUID(),after:0},failed);
+ const frames=previewFrames(payload=>decoder.push(payload));
+ connection.camera.onmessage=event=>{try{
+ if(typeof event.data==='string'){const metadata=JSON.parse(event.data);if(metadata.type!=='camera-ready'||typeof metadata.mime!=='string')throw Error('Invalid camera metadata');decoder.close();decoder=previewCamera(video,ready,failed);decoded=false;decoder.open(metadata.mime);}
+ else frames.push(event.data);
+ }catch{failed();}};
+ const timer=setInterval(()=>{if(decoded&&video.currentTime!==last){last=video.currentTime;progress=performance.now();}const fresh=decoded&&performance.now()-progress<2000;report({camera:fresh?'Камера: изображение поступает':'Камера: ожидаем изображение',cameraPresented:fresh});},500);
+ void connection.start().catch(failed);
+ return()=>{active=false;clearInterval(timer);connection.close();frames.close();decoder.close();};
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/observationRerun.ts b/plugins/xgrids-k1/frontend/src/sensors/observationRerun.ts
index 0b5b997e..f98ef4d5 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/observationRerun.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/observationRerun.ts
@@ -1,24 +1,41 @@
-import type {RefObject} from 'react';
-import type {RerunHostFactory,LiveRerunViewer} from '@mission-core/sensor-sdk';
+import type {RerunHostFactory,SceneSettings} from '@mission-core/sensor-sdk';
+import {perform,type Sensor,type SensorTransport} from './runtime';
+import {k1ScenePatch} from './useK1SceneSettings';
-/** One incoming RRD stream, two independently navigable native views. */
-export function observationRerun(factory:RerunHostFactory,plan:RefObject):RerunHostFactory {
+/** Canonical blueprint service; no alternate grid, camera or accumulation defaults. */
+export function observationRerun(factory:RerunHostFactory,current:()=>{device:Sensor;transport:SensorTransport;settings:SceneSettings;view:string;onBounds?:(bounds:{min:number;max:number})=>void}):RerunHostFactory {
return element=>{
- const spatial=factory(element),overhead=factory(plan.current!);let disposed=false;
- const controller=new AbortController();
- const load=async(url:URL)=>{const response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error('Не удалось загрузить вид облака точек.');return new Uint8Array(await response.arrayBuffer());};
- const ready=Promise.all([spatial.ready,overhead.ready,load(new URL('./observation-3d.rbl',import.meta.url)),load(new URL('./observation-plan.rbl',import.meta.url))]).then(([a,b,perspective,top])=>{
- let primaryBlueprint:ReturnType|null=null,secondaryBlueprint:ReturnType|null=null,recording:string|null=null;
- const viewer:LiveRerunViewer={
- ...a.viewer,
- start:async(source,mount,options)=>{await a.viewer.start(source,mount,options);if(disposed)return;await b.viewer.start(source,b.mount,options);primaryBlueprint=a.viewer.open_channel('observation-perspective');secondaryBlueprint=b.viewer.open_channel('observation-plan');},
- open_channel:name=>{const first=a.viewer.open_channel(name),second=b.viewer.open_channel(name);return {get ready(){return first.ready&&second.ready;},send_rrd:bytes=>{second.send_rrd(bytes.slice());first.send_rrd(bytes);},close:()=>{first.close();second.close();}};},
- get_active_recording_id:()=>{const id=a.viewer.get_active_recording_id();if(id&&id!==recording&&primaryBlueprint?.ready&&secondaryBlueprint?.ready&&b.viewer.get_active_recording_id()===id){primaryBlueprint.send_rrd(perspective.slice());secondaryBlueprint.send_rrd(top.slice());recording=id;}return id;},
- override_panel_state:(panel,state)=>{a.viewer.override_panel_state(panel,state);b.viewer.override_panel_state(panel,state);},
- set_active_timeline:(id,timeline)=>{a.viewer.set_active_timeline(id,timeline);b.viewer.set_active_timeline(id,timeline);},
+ const host=factory(element),owner=crypto.randomUUID().replaceAll('-','');
+ const timing:{requests:number;started_ms?:number;completed_ms?:number;error?:boolean}={requests:0};
+ const began=performance.now();
+ const report=()=>{element.dataset.k1Profile=JSON.stringify(timing);};
+ let disposed=false,recording:string|null=null,applied='',busy=false,retryAt=0;
+ const ready=host.ready.then(({viewer,mount})=>{
+ let blueprint:ReturnType|null=null;
+ let sliceKey='',sliceAt=0,boundsAt=0;
+ const refresh=()=>{
+ const id=viewer.get_active_recording_id(),state=current(),settings=k1ScenePatch(state.settings),follow=state.settings.followTrajectory??false;
+ const key=JSON.stringify([id,settings,state.view,follow]);
+ const nextSlice=JSON.stringify([id,state.settings.heightFloor,state.settings.heightCeiling]);
+ // A blueprint can introduce a new native view within the same recording.
+ // Reapply bounded local presentation so that view inherits the slice too.
+ if(id&&(nextSlice!==sliceKey||performance.now()-sliceAt>500)&&viewer.set_height_slice?.(state.settings.heightFloor??null,state.settings.heightCeiling??null)){sliceKey=nextSlice;sliceAt=performance.now();}
+ if(id&&performance.now()-boundsAt>500){boundsAt=performance.now();const bounds=viewer.get_height_bounds?.();if(bounds)state.onBounds?.(bounds);}
+ if(id!==recording)applied='';
+ if(!id||!blueprint?.ready||busy||key===applied||disposed||Date.now()(state.transport,state.device,'details',{preview_blueprint:{recording_id:id,owner,view:state.view==='plan'?'plan':'3d',settings,follow_trajectory:follow,host_playback:true,...(eye?{eye}:{})}})
+ .then(result=>{if(disposed||recording!==id)return;const bytes=Uint8Array.from(atob(result.rrd),c=>c.charCodeAt(0));blueprint!.send_rrd(bytes);applied=key;timing.completed_ms=Math.round(performance.now()-began);timing.error=false;report();})
+ .catch(error=>{timing.error=true;report();console.error('K1 spatial profile could not be applied',error);retryAt=Date.now()+3000;}).finally(()=>{busy=false;});
+ return applied?id:null;
};
- return {viewer,mount:a.mount};
+ return {mount,viewer:{...viewer,
+ get ready(){return viewer.ready;},
+ start:async(...args:Parameters)=>{await viewer.start(...args);if(!disposed)blueprint=viewer.open_channel('canonical-spatial-profile:'+owner);},
+ get_active_recording_id:refresh,
+ }};
});
- return {ready,dispose:()=>{disposed=true;controller.abort();spatial.dispose();overhead.dispose();}};
+ return {ready,dispose:()=>{disposed=true;delete element.dataset.k1Profile;host.dispose();if(recording){const state=current();void perform(state.transport,state.device,'details',{preview_blueprint:{recording_id:recording,owner,release:true}}).catch(()=>{});}}};
};
}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/plugin.ts b/plugins/xgrids-k1/frontend/src/sensors/plugin.ts
index 95a378b0..101ebf70 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/plugin.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/plugin.ts
@@ -1,12 +1,12 @@
import type {SensorUiContribution} from '@mission-core/sensor-sdk';
-import {K1Detail} from './K1Detail';
+import {K1SettingsWindow} from './K1SettingsWindow';
import {DeviceEnrollmentWindow} from './DeviceEnrollmentWindow';
import {k1Status} from './presentation';
import {K1Observation} from './K1Observation';
export const xgridsK1SensorUi:SensorUiContribution={
- kind:'k1', Detail:K1Detail, icon:'network', retainOffline:true, supportsPreparation:false,
- supportsRenaming:false,status:k1Status,
+ kind:'k1', Detail:K1SettingsWindow, detailPresentation:'modal', icon:'network', retainOffline:true, supportsPreparation:false,
+ supportsRenaming:false,settingsInDetail:true,status:k1Status,
wirelessEnrollment:{label:'XGRIDS LixelKity K1',View:DeviceEnrollmentWindow},
- observation:{Session:K1Observation,catalog:{label:'XGRIDS LixelKity K1',views:[{id:'points',label:'XGRIDS K1 · Облако точек · 3D'},{id:'plan',label:'XGRIDS K1 · Облако точек · Сверху'},{id:'camera',label:'XGRIDS K1 · Камера'}]},views:device=>[{id:'points',label:`${device.name} Point Cloud · 3D`},{id:'plan',label:`${device.name} Point Cloud · Сверху`},{id:'camera',label:`${device.name} Cam Right`}]},
+ observation:{Session:K1Observation,catalog:{label:'XGRIDS LixelKity K1',views:[{id:'points',scene:true,label:'XGRIDS K1 · Облако точек'},{id:'camera',label:'XGRIDS K1 · Камера'}]},views:device=>[{id:'points',scene:true,label:`${device.name} Point Cloud`},{id:'camera',label:`${device.name} Cam Right`}]},
};
diff --git a/plugins/xgrids-k1/frontend/src/sensors/presentation.ts b/plugins/xgrids-k1/frontend/src/sensors/presentation.ts
index 8823aa00..18b9ec11 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/presentation.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/presentation.ts
@@ -9,6 +9,9 @@ export function k1Status(device:Sensor,fresh:boolean):{label:string;tone:'neutra
export function k1ConnectionNotice(device:Sensor,fresh:boolean):string {
if(!fresh)return 'Нет свежих сведений с БК. Ожидаем восстановления связи.';
+ if(device.connection_mode==='usb')return device.control?.reason_code==='application_authority_unavailable'
+ ?'K1 подключён по USB. Служба на БК не смогла авторизовать подключение. Проверьте установленную интеграцию K1.'
+ :'Нет подтверждённой связи с K1 по USB. Проверьте питание сканера и USB-кабель. Состояние съёмки уточняется после восстановления связи.';
if(device.control?.reason_code==='application_authority_unavailable')
return 'Wi-Fi настроен. Служба K1 на БК не смогла авторизовать подключение. Обновите интеграцию K1 на БК и проверьте состояние устройства.';
return device.control?.network_applied
@@ -22,3 +25,14 @@ export function k1ManualState(device:Sensor,fresh:boolean) {
return {active,connected,canStart:connected&&!active&&device.control?.can_start===true,
showStop:active||device.control?.can_stop===true};
}
+
+export function k1StorageStatus(device:Sensor,fresh:boolean,now=Date.now()):{label:string;tone:'neutral'|'warning'} {
+ // Fleet inventory has an existing 20-second heartbeat freshness window.
+ // The driver separately requires a source report no older than five seconds.
+ const value=device.storage_status,age=value?now-Date.parse(value.observed_at):NaN;
+ if(!fresh||!device.online||!device.verified||!value||!Number.isFinite(age)||age<0||age>=20000||
+ !Number.isFinite(value.used_percent)||value.used_percent<0||value.used_percent>100)
+ return {label:'Хранилище K1: нет свежих данных',tone:'neutral'};
+ const percent=(Math.round(value.used_percent*10)/10).toLocaleString('ru-RU');
+ return {label:`Хранилище K1: занято ${percent} %${value.used_percent>=95?' · мало свободного места':''}`,tone:value.used_percent>=95?'warning':'neutral'};
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/previewFreshness.ts b/plugins/xgrids-k1/frontend/src/sensors/previewFreshness.ts
index f7898d7d..88502d85 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/previewFreshness.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/previewFreshness.ts
@@ -1,4 +1,7 @@
/** Source-age gate, independent of wall-clock skew between operator and board. */
+// The optional cloud preview admits 2–3 s delivery and a sampled frame interval.
+// Keep a finite source-age limit; repeated metadata must never extend it.
+const CLOUD_PREVIEW_FRESH_MS = 5_000;
export function previewFreshness(now: () => number = () => performance.now()) {
let sequence = 0, expires = 0, points = 0;
return {
@@ -17,7 +20,7 @@ export function previewFreshness(now: () => number = () => performance.now()) {
return;
sequence = frame.sequence!;
points = frame.points!;
- expires = frame.age_ms === null ? 0 : now() + Math.max(0, 2000 - frame.age_ms!);
+ expires = frame.age_ms === null ? 0 : now() + Math.max(0, CLOUD_PREVIEW_FRESH_MS - frame.age_ms!);
},
get fresh() { return sequence > 0 && now() < expires; },
get points() { return points; },
diff --git a/plugins/xgrids-k1/frontend/src/sensors/previewSignalling.ts b/plugins/xgrids-k1/frontend/src/sensors/previewSignalling.ts
new file mode 100644
index 00000000..149cf0cb
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/previewSignalling.ts
@@ -0,0 +1,9 @@
+export function privateCandidate(sdp: string): string {
+ return sdp.split('\r\n').filter(line => {
+ if (!line.startsWith('a=candidate:'))
+ return true;
+ const fields = line.split(' '), ip = fields[4] ?? '', parts = ip.split('.').map(Number);
+ return fields[7] === 'host' && (ip.endsWith('.local') || (parts.length === 4 && parts.every(v => Number.isInteger(v) && v >= 0 && v <= 255) &&
+ (parts[0] === 10 || parts[0] === 127 || (parts[0] === 192 && parts[1] === 168) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127))));
+ }).join('\r\n');
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/useK1CameraPreview.ts b/plugins/xgrids-k1/frontend/src/sensors/useK1CameraPreview.ts
new file mode 100644
index 00000000..1a176458
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/useK1CameraPreview.ts
@@ -0,0 +1,49 @@
+import {useEffect,useState,type RefObject} from 'react';
+import {perform,type Sensor,type SensorTransport} from './runtime';
+import {localCameraPreview} from './localCameraPreview';
+import {privateCandidate} from './previewSignalling';
+export function useK1CameraPreview(device:Sensor,transport:SensorTransport,video:RefObject,enabled:boolean,generation=0){
+ const [state,setState]=useState({camera:'Камера: ожидаем изображение',cameraPresented:false});
+ useEffect(()=>{
+ const element=video.current;
+ setState({camera:'Камера: ожидаем изображение',cameraPresented:false});
+ if(!enabled||!element)return;
+ if(transport.localPreview)return localCameraPreview(device,transport,element,setState);
+ let active=true,peer:string|undefined,timer:ReturnType|undefined,ice:ReturnType|undefined;
+ let pc:RTCPeerConnection;
+ try{pc=new RTCPeerConnection({iceServers:[]});}catch{setState({camera:'Камера: просмотр недоступен',cameraPresented:false});return;}
+ const channel=pc.createDataChannel('sensor');
+ pc.addTransceiver('video',{direction:'recvonly'});
+ pc.ontrack=event=>{if(active){element.srcObject=new MediaStream([event.track]);void element.play().catch(()=>{});}};
+ const fail=()=>{if(active)setState({camera:'Камера: восстанавливаем связь',cameraPresented:false});};
+ let last=-1,progress=0,keepalive=0,retry=0,statsAt=0,statsBusy=false;
+ const connect=async()=>{
+ await pc.setLocalDescription(await pc.createOffer());
+ if(pc.iceGatheringState!=='complete')await new Promise((resolve,reject)=>{
+ ice=setTimeout(()=>reject(Error('ICE timeout')),8000);
+ pc.onicegatheringstatechange=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(ice);resolve();}};
+ });
+ if(!active)return;
+ const answer=await perform<{peer_id:string;sdp:string;type:'answer'}>(transport,device,'offer',{media:'camera',sdp:privateCandidate(pc.localDescription!.sdp),acquisition_id:device.control?.acquisition_id});
+ peer=answer.peer_id;
+ if(!active){void perform(transport,device,'close-peer',{peer_id:peer}).catch(()=>{});return;}
+ await pc.setRemoteDescription(answer);
+ };
+ pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState))fail();};
+ timer=setInterval(()=>{
+ const now=performance.now();
+ if(element.readyState>=2&&element.currentTime!==last){last=element.currentTime;progress=now;}
+ const fresh=progress>0&&now-progress<2000;
+ setState(previous=>previous.cameraPresented===fresh?previous:{camera:fresh?'Камера: изображение поступает':'Камера: нет свежих кадров',cameraPresented:fresh});
+ if(channel.readyState==='open'&&now-keepalive>5000){channel.send('keepalive');keepalive=now;}
+ if(pc.connectionState==='failed'&&retry++===0)fail();
+ if(!statsBusy&&now-statsAt>=2000){statsAt=now;statsBusy=true;void pc.getStats().then(stats=>{
+ if(!active)return;
+ stats.forEach(row=>{if(row.type==='inbound-rtp'&&row.kind==='video')element.dataset.k1Preview=JSON.stringify({timestamp:row.timestamp,bytes:row.bytesReceived,frames:row.framesDecoded,dropped:row.framesDropped,fps:row.framesPerSecond,decode_seconds:row.totalDecodeTime,jitter_buffer_seconds:row.jitterBufferDelay,jitter_buffer_frames:row.jitterBufferEmittedCount,current_time:element.currentTime});});
+ }).catch(()=>{}).finally(()=>{statsBusy=false;});}
+ },500);
+ void connect().catch(fail);
+ return()=>{active=false;delete element.dataset.k1Preview;clearTimeout(ice);clearInterval(timer);pc.ontrack=null;pc.onconnectionstatechange=null;pc.onicegatheringstatechange=null;pc.close();element.pause();element.srcObject=null;if(peer)void perform(transport,device,'close-peer',{peer_id:peer}).catch(()=>{});};
+ },[device.snapshot.context.session_id,device.control?.acquisition_id,transport,video,enabled,generation]);
+ return state;
+}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/useK1Management.ts b/plugins/xgrids-k1/frontend/src/sensors/useK1Management.ts
new file mode 100644
index 00000000..5c437700
--- /dev/null
+++ b/plugins/xgrids-k1/frontend/src/sensors/useK1Management.ts
@@ -0,0 +1,52 @@
+import {useEffect,useRef,useState} from 'react';
+import type {SensorDetailProps} from '@mission-core/sensor-sdk';
+import {perform} from './runtime';
+import {k1ManualState} from './presentation';
+
+export type ManagementOperation='info'|'projects'|'delete-projects'|'format-storage'|'usb-storage'|'usb-data'|'power-off'|'reboot';
+export interface K1Project {id:string;name:string}
+export interface ManagementResult {status:'succeeded'|'rejected'|'blocked'|'unknown';message?:string;result_code?:number;usb_mode?:'data'|'storage';storage_type?:string;projects?:K1Project[];catalog_revision?:string}
+export function useK1Management(props:SensorDetailProps) {
+ const {device,enabled}=props,manual=k1ManualState(device,enabled);
+ const ready=manual.connected&&!manual.active&&['connection-ready','completed'].includes(device.control?.phase??'');
+ const identity=`${device.id}:${device.snapshot.context.session_id}:${device.control?.generation}`;
+ const [info,setInfo]=useState(null),[catalog,setCatalog]=useState(null);
+ const [busy,setBusy]=useState(null),[message,setMessage]=useState('');
+ const running=useRef(false),pendingInfo=useRef(false),latest=useRef(props),identityRef=useRef(identity);
+ latest.current=props;identityRef.current=identity;
+ async function run(operation:ManagementOperation,ids:string[]=[],catalogRevision?:string) {
+ if(running.current)return;
+ const current=latest.current,currentManual=k1ManualState(current.device,current.enabled);
+ if(!currentManual.connected||currentManual.active||!['connection-ready','completed'].includes(current.device.control?.phase??''))return;
+ running.current=true;setBusy(operation);setMessage('');
+ const owner=identityRef.current;
+ try {
+ const result=await perform(current.transport,current.device,'management',{
+ operation,operator_confirmed:!['info','projects'].includes(operation),project_ids:ids,
+ catalog_revision:catalogRevision??null,
+ control_generation:current.device.control?.generation,control_revision:current.device.control?.revision,
+ });
+ if(owner!==identityRef.current)return;
+ if(result.status!=='succeeded') {
+ setMessage(result.message??(result.status==='rejected'?`K1 отклонил операцию (код ${result.result_code}).`:'K1 не подтвердил результат операции.'));
+ if(result.status==='unknown')setInfo(null);
+ return result;
+ }
+ if(result.usb_mode)setInfo(result);
+ if(operation==='projects')setCatalog(result);
+ if(['delete-projects','format-storage'].includes(operation))setCatalog(null);
+ if(operation==='power-off'||operation==='reboot')setInfo(null);
+ if(!['info','projects'].includes(operation))setMessage(operation==='power-off'?'K1 подтвердил команду выключения.':operation==='reboot'?'K1 подтвердил команду перезагрузки.':'Операция завершена.');
+ return result;
+ } catch {
+ if(owner===identityRef.current){setInfo(null);setMessage('Не получен результат с борта. Проверьте связь и обновите состояние K1.');}
+ } finally {
+ running.current=false;setBusy(null);void latest.current.refresh().catch(()=>{});
+ if(pendingInfo.current){pendingInfo.current=false;void run('info');}
+ }
+ }
+ useEffect(()=>{setInfo(null);setCatalog(null);setMessage('');if(ready){if(running.current)pendingInfo.current=true;else void run('info');}},[identity,ready]);
+ return {ready,info,catalog,busy,message,run,canManage:ready&&!busy&&!!info,
+ canSwitchToStorage:props.device.connection_mode==='bridge'};
+}
+export type K1Management=ReturnType;
diff --git a/plugins/xgrids-k1/frontend/src/sensors/useK1Preview.ts b/plugins/xgrids-k1/frontend/src/sensors/useK1Preview.ts
index a1928114..4d12e3fd 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/useK1Preview.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/useK1Preview.ts
@@ -1,8 +1,10 @@
-import { useEffect, useState, type RefObject } from 'react';
-import type { RerunHostFactory, LiveRerunViewer } from '@mission-core/sensor-sdk';
+import {privateCandidate} from './previewSignalling';
+import {useK1CameraPreview} from './useK1CameraPreview';
+import { useEffect, useRef, useState, type RefObject } from 'react';
+import type { RerunHostFactory, LiveRerunViewer, SceneSettings } from '@mission-core/sensor-sdk';
import { perform, type Sensor, type SensorTransport } from './runtime';
import { MEDIA_PROTOCOL, previewFrames, previewRecording } from './previewFrames';
-import { previewCamera } from './previewCamera';
+import {k1ScenePatch} from './useK1SceneSettings';
import { previewFreshness } from './previewFreshness';
import {localPreview, type PreviewChannel} from './localPreview';
export type PreviewStatus = {
@@ -15,33 +17,37 @@ export type PreviewStatus = {
points: number;
};
export const pendingPreview: PreviewStatus = { lidar: 'Лидар: ожидаем данные', camera: 'Камера: ожидаем изображение', retry: false, presented: false, hasScene: false, cameraPresented: false, points: 0 };
-function privateCandidate(sdp: string): string {
- return sdp.split('\r\n').filter(line => {
- if (!line.startsWith('a=candidate:'))
- return true;
- const fields = line.split(' '), ip = fields[4] ?? '', parts = ip.split('.').map(Number);
- return fields[7] === 'host' && (ip.endsWith('.local') || (parts.length === 4 && parts.every(v => Number.isInteger(v) && v >= 0 && v <= 255) &&
- (parts[0] === 10 || parts[0] === 127 || (parts[0] === 192 && parts[1] === 168) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127))));
- }).join('\r\n');
-}
-export function useK1Preview(device: Sensor, transport: SensorTransport, createRerunHost: RerunHostFactory, spatial: RefObject, video: RefObject, onStatus: (value: PreviewStatus) => void, generation = 0, enabled = true) {
+export function useK1Preview(device: Sensor, transport: SensorTransport, createRerunHost: RerunHostFactory, spatial: RefObject, video: RefObject, onStatus: (value: PreviewStatus) => void, generation = 0, enabled = true, settings?:SceneSettings) {
+ const cameraStatus=useK1CameraPreview(device,transport,video,enabled,generation);
+ const cameraStatusRef=useRef(cameraStatus);cameraStatusRef.current=cameraStatus;
+ const statusRef=useRef(pendingPreview);
+ const publish=(value:PreviewStatus)=>{statusRef.current=value;onStatus({...value,...cameraStatusRef.current});};
+ useEffect(()=>{onStatus({...statusRef.current,...cameraStatus});},[cameraStatus,onStatus]);
+ const localSettingsKey=transport.localPreview&&settings?JSON.stringify(k1ScenePatch(settings)):'';
+ const settingsRef=useRef(settings);settingsRef.current=settings;
+ const startup = useRef<{at:number;stages:Record}>({at:performance.now(),stages:{}});
+ const stamp = (name:string) => { startup.current.stages[name] ??= Math.round(performance.now()-startup.current.at); };
const [native, setNative] = useState(null);
// The runtime and native channel belong to this acquisition view, not its peers.
useEffect(() => {
let active = true;
+ startup.current={at:performance.now(),stages:{}};
const host = createRerunHost(spatial.current!);
void host.ready.then(async ({ viewer, mount }) => {
if (!active)
return;
+ stamp('realm_ready_ms');
await viewer.start(null, mount, { width: '100%', height: '100%', theme: 'dark', hide_welcome_screen: true, enable_history: false, allow_fullscreen: false,
panel_state_overrides: { top: 'Hidden', blueprint: 'Hidden', selection: 'Hidden', time: 'Hidden' } });
if (!active)
return;
for (const panel of ['top', 'blueprint', 'selection', 'time'] as const)
viewer.override_panel_state(panel, 'hidden');
+ stamp('viewer_ready_ms');
setNative(viewer);
- }).catch(() => { if (active)
- onStatus({ ...pendingPreview, lidar: 'Визуализатор не загрузился. Обновите страницу.' }); });
+ }).catch(error => { if (active) {
+ console.error('K1 spatial viewer startup failed', error);
+ publish({ ...pendingPreview, lidar: 'Визуализатор не загрузился. Обновите страницу.' }); } });
return () => { active = false; setNative(null); host.dispose(); };
}, [createRerunHost, spatial, onStatus]);
const [view, setView] = useState<{
@@ -60,20 +66,24 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
useEffect(() => {
const currentView = view?.session === device.snapshot.context.session_id && view?.acquisition === device.control?.acquisition_id;
const paused = device.snapshot.acquisition === 'streaming'
- ? {lidar:'Лидар: нет связи с БК', camera:'Камера: нет связи с БК'}
+ ? {lidar:'Лидар: связь с K1 не подтверждена', camera:'Камера: связь с K1 не подтверждена'}
: ['starting','preparing'].includes(device.snapshot.acquisition)
? {} : {lidar:'Лидар: приём завершён', camera:'Камера: изображение остановлено'};
- onStatus({...pendingPreview, hasScene:currentView ? view?.hasScene ?? false : false, ...(!enabled ? paused : {})});
+ publish({...pendingPreview, hasScene:currentView ? view?.hasScene ?? false : false, ...(!enabled ? paused : {})});
if (!native || !view || !currentView || !enabled)
return;
let active = true, failed = false, peerID: string | undefined;
+ let receivedBatches=0,receivedBytes=0,receivedAge:number|null=null;
+ const startedAt=performance.now();
+ const stages:Record={};
+ const mark=(name:string)=>{stages[name]??=Math.round(performance.now()-startedAt);};
let keepalive: ReturnType | undefined, follow: ReturnType | undefined, iceTimeout: ReturnType | undefined;
let status = { ...pendingPreview, hasScene: view.hasScene };
const update = (patch: Partial) => { if (active) {
const next = { ...status, ...patch };
if (JSON.stringify(next) !== JSON.stringify(status)) {
status = next;
- onStatus(status);
+ publish(status);
}
} };
const viewer = native, freshness = previewFreshness();
@@ -84,39 +94,34 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
let pc:RTCPeerConnection|null=null;
try {if(!transport.localPreview)pc=new RTCPeerConnection({iceServers:[]});}
catch {update({lidar:'Не удалось открыть канал просмотра',retry:false});return;}
- const local=transport.localPreview?localPreview(device,transport,{acquisition_id:device.control?.acquisition_id,view_id:view.id,after:view.recording.after},()=>fail()):null;
- let rrd:PreviewChannel|RTCDataChannel, camera:PreviewChannel|RTCDataChannel;
+ const local=transport.localPreview?localPreview(device,transport,{media:'cloud',acquisition_id:device.control?.acquisition_id,view_id:view.id,after:view.recording.after,...(settingsRef.current?{settings:k1ScenePatch(settingsRef.current)}:{})},()=>fail()):null;
+ let rrd:PreviewChannel|RTCDataChannel;
try {
rrd = local?.rrd ?? pc!.createDataChannel('rrd', { ordered: true });
- camera = local?.camera ?? pc!.createDataChannel('camera', { ordered: true });
} catch {
local?.close();pc?.close();
update({lidar:'Не удалось открыть канал просмотра',camera:'Просмотр недоступен',retry:false});return;
}
if('binaryType' in rrd)rrd.binaryType = 'arraybuffer';
- if('binaryType' in camera)camera.binaryType = 'arraybuffer';
const closeConnection=()=>{local?.close();pc?.close();};
const {channel, previousRecording} = view;
const fail = () => { if (!active || failed)
return; failed = true; update({ lidar: 'Лидар: восстанавливаем связь', camera: 'Камера: ожидаем соединение', retry: true, presented: false, cameraPresented: false }); clearInterval(follow); clearInterval(keepalive); closeConnection(); };
- let cameraDecoded = false, cameraFailed = false, lastVideoTime = -1, lastVideoProgress = 0, seenLidar = false;
- const cameraFail = () => { cameraFailed = true; update({ camera: 'Камера: изображение недоступно', cameraPresented: false }); camera.close(); };
- let decoder = previewCamera(video.current!, () => { cameraDecoded = true; lastVideoProgress = performance.now(); }, cameraFail);
- const cameraFrames = previewFrames(payload => decoder.push(payload));
+ let seenLidar = false;
let batch: {sequence: number; lidar: Record; received: number} | null = null;
const rrdFrames = previewFrames(payload => {
if (!batch || !channel.ready) throw new Error('Viewer unavailable');
if (view.recording.accept(batch.sequence, payload)) {
const age = batch.lidar.age_ms;
+ receivedAge=typeof age==='number'?age+performance.now()-batch.received:null;
freshness.receive({...batch.lidar, age_ms: typeof age === 'number' ? age + performance.now() - batch.received : age});
}
+ mark('first_rrd_accepted_ms');
rrd.send(JSON.stringify({ack: batch.sequence}));
batch = null;
});
rrd.onclose = () => { if (active && !failed)
fail(); };
- camera.onclose = () => { if (active && !failed)
- cameraFail(); };
rrd.onmessage = (event:{data:string|ArrayBuffer}) => {
if (!active)
return;
@@ -130,44 +135,33 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
}
if (batch || value.type !== 'rrd-batch' || !Number.isSafeInteger(value.sequence) || value.sequence < 1 || !value.lidar)
throw new Error('Invalid RRD batch');
- batch = {...value, received: performance.now()};
+ batch = {...value, received: performance.now()};receivedBatches++;mark('first_batch_ms');
+ if(receivedBatches===1)console.debug('K1 cloud first batch',JSON.stringify({view:view.id,sequence:value.sequence,lidar:value.lidar}));
}
- else if (event.data instanceof ArrayBuffer)
+ else if (event.data instanceof ArrayBuffer) {
+ receivedBytes+=event.data.byteLength;
rrdFrames.push(event.data);
+ }
}
- catch {
+ catch (error) {
+ console.error('K1 cloud preview rejected a native batch', error);
fail();
}
};
- camera.onmessage = (event:{data:string|ArrayBuffer}) => {
- if (!active || failed)
- return;
- try {
- if (typeof event.data === 'string') {
- const metadata = JSON.parse(event.data);
- if (metadata.type !== 'camera-ready' || typeof metadata.mime !== 'string')
- throw new Error('Invalid camera metadata');
- decoder.close();
- cameraDecoded = false; cameraFailed = false; lastVideoTime = -1;
- decoder = previewCamera(video.current!, () => {cameraDecoded = true; lastVideoProgress = performance.now();}, cameraFail);
- decoder.open(metadata.mime);
- }
- else if (event.data instanceof ArrayBuffer)
- cameraFrames.push(event.data);
- }
- catch {
- cameraFail();
- }
- };
const run = async () => {
+ let lastSettings='';
let synchronizedRecording: string | null = null;
follow = setInterval(() => {
if (!active || failed)
return;
+ const settingKey=JSON.stringify(settingsRef.current?k1ScenePatch(settingsRef.current):null);
+ if(!local&&rrd.readyState==='open'&&settingsRef.current&&settingKey!==lastSettings){rrd.send(JSON.stringify({settings:k1ScenePatch(settingsRef.current)}));lastSettings=settingKey;}
let presented = false;
+ let nativeState:Record={previousRecording};
try {
const id = viewer.get_active_recording_id();
const range = id ? viewer.get_time_range(id, 'stream_time') : null;
+ nativeState={...nativeState,recording:id,range};
if (id && range) {
if (synchronizedRecording !== id) {
viewer.set_active_timeline(id, 'stream_time');
@@ -176,24 +170,24 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
}
// Following is owned by the live blueprint. SetTime/SetPlaying would
// pin the cursor and override that profile on every heartbeat.
- presented = id !== previousRecording && freshness.fresh && range.max > range.min;
+ const hasData = id !== previousRecording && range.max > range.min && freshness.points > 0;
+ // A delayed first frame is still a scene. Keep the live
+ // badge age-gated without hiding valid received geometry.
+ view.hasScene ||= hasData;
+ presented = hasData && freshness.fresh;
}
}
- catch { /* Native recording/timeline creation is asynchronous. */ }
- seenLidar ||= presented;
+ catch (error) { nativeState.error=String(error); /* Native recording/timeline creation is asynchronous. */ }
+ if(view.hasScene)mark('first_scene_ms');
+ seenLidar ||= view.hasScene;
view.hasScene ||= presented;
- const v = video.current!;
- if (cameraDecoded && v.currentTime !== lastVideoTime) {
- lastVideoTime = v.currentTime;
- lastVideoProgress = performance.now();
- }
- const cameraPresented = cameraDecoded && !cameraFailed && performance.now() - lastVideoProgress < 2000;
- update({ presented, hasScene: view.hasScene, cameraPresented, points: presented ? freshness.points : 0,
- lidar: presented ? 'Лидар: данные поступают' : seenLidar ? 'Лидар: нет свежих данных' : 'Лидар: ожидаем данные',
- camera: cameraFailed ? 'Камера: изображение недоступно' : cameraPresented ? 'Камера: изображение поступает' : cameraDecoded ? 'Камера: нет свежих кадров' : 'Камера: ожидаем изображение' });
+ update({ presented, hasScene: view.hasScene, points: presented ? freshness.points : 0,
+ lidar: presented ? 'Лидар: данные поступают' : seenLidar ? 'Лидар: нет свежих данных' : 'Лидар: ожидаем данные' });
+ if(spatial.current)spatial.current.dataset.k1Preview=JSON.stringify({view:view.id,elapsed_ms:Math.round(performance.now()-startedAt),batches:receivedBatches,bytes:receivedBytes,source_age_ms:receivedAge,points:freshness.points,presented,hasScene:view.hasScene,native:nativeState,startup:startup.current.stages,stages});
}, 250);
if(local){await local.start();return;}
if(!pc)return;
+ mark('offer_started_ms');
await pc.setLocalDescription(await pc.createOffer());
if (pc.iceGatheringState !== 'complete')
await new Promise((resolve, reject) => {
@@ -205,12 +199,14 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
});
if (!active)
return;
+ mark('ice_ready_ms');
const answer = await perform<{
peer_id: string;
sdp: string;
type: 'answer';
media_protocol: string;
- }>(transport, device, 'offer', { sdp: privateCandidate(pc.localDescription!.sdp), acquisition_id: device.control?.acquisition_id, view_id: view.id, after: view.recording.after });
+ }>(transport, device, 'offer', { sdp: privateCandidate(pc.localDescription!.sdp), acquisition_id: device.control?.acquisition_id, view_id: view.id, after: view.recording.after, ...(settingsRef.current?{settings:k1ScenePatch(settingsRef.current)}:{}) });
+ mark('answer_received_ms');
peerID = answer.peer_id;
if (!active) {
void perform(transport, device, 'close-peer', { peer_id: peerID }).catch(() => { });
@@ -223,30 +219,28 @@ export function useK1Preview(device: Sensor, transport: SensorTransport, createR
update({ lidar: 'Для просмотра требуется обновление приложения на БК', camera: 'Камера: ожидаем обновление', retry: false });
return;
}
- pc.onconnectionstatechange = () => { if (active && ['failed', 'closed'].includes(pc?.connectionState ?? 'closed'))
+ pc.onconnectionstatechange = () => { if(pc?.connectionState==='connected')mark('connected_ms'); console.debug('K1 cloud peer state', JSON.stringify({view:view.id,peer:peerID,state:pc?.connectionState,batches:receivedBatches,bytes:receivedBytes}));if (active && ['failed', 'closed'].includes(pc?.connectionState ?? 'closed'))
fail(); };
await pc.setRemoteDescription({ type: answer.type, sdp: answer.sdp });
- keepalive = setInterval(() => { for (const c of [rrd, camera])
+ keepalive = setInterval(() => { for (const c of [rrd])
if (c.readyState === 'open')
c.send('keepalive'); }, 5000);
};
- void run().catch(fail);
+ void run().catch(error => { console.error('K1 cloud preview connection failed', error); fail(); });
return () => {
active = false;
+ if(spatial.current)delete spatial.current.dataset.k1Preview;
clearInterval(keepalive);
clearInterval(follow);
clearTimeout(iceTimeout);
rrd.onmessage = null;
- camera.onmessage = null;
- camera.onclose = null;
rrd.onclose = null;
if(pc){pc.onconnectionstatechange = null;pc.onicegatheringstatechange = null;}
closeConnection();
rrdFrames.close();
- cameraFrames.close();
- decoder.close();
if (peerID)
void perform(transport, device, 'close-peer', { peer_id: peerID }).catch(() => { });
};
- }, [native, view, device.snapshot.context.session_id, device.control?.acquisition_id, transport, onStatus, video, generation, enabled]);
+ }, [native, view, device.snapshot.context.session_id, device.control?.acquisition_id, transport, onStatus, video, generation, enabled,localSettingsKey]);
+ return native;
}
diff --git a/plugins/xgrids-k1/frontend/src/sensors/useK1SceneSettings.ts b/plugins/xgrids-k1/frontend/src/sensors/useK1SceneSettings.ts
index 149bacd7..5532afe5 100644
--- a/plugins/xgrids-k1/frontend/src/sensors/useK1SceneSettings.ts
+++ b/plugins/xgrids-k1/frontend/src/sensors/useK1SceneSettings.ts
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
-import { defaultSceneSettings, type SceneSettings } from '@mission-core/sensor-sdk';
+import { defaultSceneSettings, type SceneSettings, type SensorDetailProps } from '@mission-core/sensor-sdk';
import { perform, type Sensor, type SensorTransport } from './runtime';
const fields = { pointSize: 'point_size', accumulationSeconds: 'accumulation_seconds', colorMode: 'color_mode', palette: 'palette', customColor: 'custom_color', showPoints: 'show_points', showTrajectory: 'show_trajectory', showGrid: 'show_grid' } as const;
export function k1SceneSettings(value: Record = {}): SceneSettings {
@@ -13,9 +13,14 @@ export function k1ScenePatch(settings: SceneSettings) {
return Object.fromEntries(Object.entries(fields).map(([key, field]) => [field, settings[key as keyof typeof fields]]));
}
/** One serialized autosave owner. Scene changes never issue physical commands. */
-export function useK1SceneSettings(device: Sensor, transport: SensorTransport, failure: (error: unknown) => void) {
- const [draft, setDraft] = useState(() => k1SceneSettings(device.live_settings));
+export function useK1SceneSettings(device: Sensor, transport: SensorTransport, failure: (error: unknown) => void, profile?: SensorDetailProps['sceneProfile']) {
+ const [draft, setDraft] = useState(() => profile?.settings ?? k1SceneSettings(device.live_settings));
const current = useRef(draft), dirty = useRef(false), running = useRef(false), queued = useRef(false), active = useRef(true);
+ const external=profile?.settings ?? k1SceneSettings(device.live_settings);
+ const externalKey=JSON.stringify(external);
+ useEffect(()=>{if(!dirty.current&&!running.current){current.current=external;setDraft(external);}},[externalKey]);
+ const saveRef=useRef(profile?.save);saveRef.current=profile?.save;
+ useEffect(()=>()=>{if(dirty.current&&saveRef.current)saveRef.current(current.current);},[]);
const [pending, setPending] = useState(false);
useEffect(() => { active.current = true; return () => { active.current = false; queued.current = false; }; }, []);
const stage = (patch: Partial) => { current.current = { ...current.current, ...patch }; dirty.current = true; setDraft(current.current); };
@@ -32,7 +37,8 @@ export function useK1SceneSettings(device: Sensor, transport: SensorTransport, f
queued.current = false;
dirty.current = false;
const settings = k1ScenePatch(current.current);
- await perform(transport, device, 'option', { profile: 'live-acquisition', settings });
+ if(saveRef.current)saveRef.current({...current.current});
+ else await perform(transport, device, 'option', { profile: 'live-acquisition', settings });
}
}
catch (error) {
diff --git a/plugins/xgrids-k1/packaging/build_deb.py b/plugins/xgrids-k1/packaging/build_deb.py
index e6baa5ca..c10d08d0 100644
--- a/plugins/xgrids-k1/packaging/build_deb.py
+++ b/plugins/xgrids-k1/packaging/build_deb.py
@@ -22,7 +22,7 @@ from credential_install import PROFILE_ID, validate # noqa: E402
from debian import package # noqa: E402
from runtime_payload import files as runtime_files # noqa: E402
-VERSION = "0.1.16"
+VERSION = "0.1.43"
RESOURCES = (
"plugins/xgrids-k1/profile_loader.py",
"plugins/xgrids-k1/plugin.manifest.json",
diff --git a/plugins/xgrids-k1/packaging/runtime-files.json b/plugins/xgrids-k1/packaging/runtime-files.json
index f08727af..80bcb7c1 100644
--- a/plugins/xgrids-k1/packaging/runtime-files.json
+++ b/plugins/xgrids-k1/packaging/runtime-files.json
@@ -25,6 +25,7 @@
"src/k1link/device_plugins/xgrids_k1/connection_attempt.py",
"src/k1link/device_plugins/xgrids_k1/connection_supervisor.py",
"src/k1link/device_plugins/xgrids_k1/device_identity_pin_store.py",
+ "src/k1link/device_plugins/xgrids_k1/device_management.py",
"src/k1link/device_plugins/xgrids_k1/facade.py",
"src/k1link/device_plugins/xgrids_k1/firmware_credential.py",
"src/k1link/device_plugins/xgrids_k1/host_diagnostics.py",
@@ -36,6 +37,7 @@
"src/k1link/device_plugins/xgrids_k1/network_provisioning_idempotency_journal.py",
"src/k1link/device_plugins/xgrids_k1/node_bridge.py",
"src/k1link/device_plugins/xgrids_k1/node_sensor.py",
+ "src/k1link/device_plugins/xgrids_k1/node_usb.py",
"src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py",
"src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py",
"src/k1link/device_plugins/xgrids_k1/protocol/__init__.py",
@@ -48,6 +50,8 @@
"src/k1link/device_plugins/xgrids_k1/protocol/application_session.py",
"src/k1link/device_plugins/xgrids_k1/protocol/calibration_file.py",
"src/k1link/device_plugins/xgrids_k1/protocol/calibration_mqtt.py",
+ "src/k1link/device_plugins/xgrids_k1/protocol/device_management.py",
+ "src/k1link/device_plugins/xgrids_k1/protocol/management_mailbox.py",
"src/k1link/device_plugins/xgrids_k1/protocol/modeling.py",
"src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py",
"src/k1link/device_plugins/xgrids_k1/protocol/modeling_safety.py",
@@ -56,6 +60,7 @@
"src/k1link/device_plugins/xgrids_k1/protocol/streams.py",
"src/k1link/device_plugins/xgrids_k1/quick_connect_profile.py",
"src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py",
+ "src/k1link/device_plugins/xgrids_k1/usb_network.py",
"src/k1link/device_plugins/xgrids_k1/viewer/__init__.py",
"src/k1link/device_plugins/xgrids_k1/viewer/messages.py",
"src/k1link/device_plugins/xgrids_k1/viewer/replay.py",
@@ -83,6 +88,7 @@
"src/k1link/sessions/store.py",
"src/k1link/viewer/__init__.py",
"src/k1link/viewer/metrics.py",
+ "src/k1link/viewer/node_camera.py",
"src/k1link/viewer/node_local_media.py",
"src/k1link/viewer/node_media.py",
"src/k1link/viewer/node_rerun.py",
diff --git a/plugins/xgrids-k1/plugin.manifest.json b/plugins/xgrids-k1/plugin.manifest.json
index b360c9f8..135316b7 100644
--- a/plugins/xgrids-k1/plugin.manifest.json
+++ b/plugins/xgrids-k1/plugin.manifest.json
@@ -34,6 +34,7 @@
{ "id": "state.read", "mutating": false, "secretFields": [] },
{ "id": "discovery.scan", "mutating": false, "secretFields": [] },
{ "id": "device.inspect", "mutating": false, "secretFields": [] },
+ { "id": "device.manage", "mutating": true, "secretFields": [] },
{ "id": "sensor.catalog.read", "mutating": false, "secretFields": [] },
{ "id": "calibration.device-snapshot.read", "mutating": false, "secretFields": [] },
{ "id": "network.provision", "mutating": true, "secretFields": ["password"] },
diff --git a/plugins/xgrids-k1/profile_loader.py b/plugins/xgrids-k1/profile_loader.py
index 5dc4220b..44285323 100644
--- a/plugins/xgrids-k1/profile_loader.py
+++ b/plugins/xgrids-k1/profile_loader.py
@@ -164,6 +164,14 @@ def _validate_connection_modes(scope: dict[str, Any]) -> None:
"acceptance": "prepared-macos-host-physical-accepted",
},
}
+ expected["usb"] = {
+ 'topology': 'usb-ethernet',
+ 'direction': 'k1-usb-ethernet-to-board',
+ 'device_network_action': 'none',
+ 'host_network_action': 'existing-os-rndis-dhcp',
+ 'target_address_policy': 'usb-dhcp-peer-and-exact-kernel-route',
+ 'acceptance': 'firmware-3.0.2-physical-transport-qualified',
+ }
if set(modes) != set(expected):
raise CompatibilityProfileError("connection mode set differs from reviewed evidence")
for mode_id, expected_fields in expected.items():
diff --git a/plugins/xgrids-k1/profiles/fw-3.0.2/local-network.v2.json b/plugins/xgrids-k1/profiles/fw-3.0.2/local-network.v2.json
index 28fdfae5..a6657ee9 100644
--- a/plugins/xgrids-k1/profiles/fw-3.0.2/local-network.v2.json
+++ b/plugins/xgrids-k1/profiles/fw-3.0.2/local-network.v2.json
@@ -11,7 +11,7 @@
"version": "3.0.2"
},
"topology": "local-network-matrix",
- "claim_limit": "One owner-controlled K1 on exact firmware 3.0.2. Bridge/Mission Core is physically accepted. Quick Connect AP activation and association are accepted only on one prepared macOS host with a preinstalled firmware provider; clean-host bootstrap is not implemented. Direct Connect reuses the physically accepted 99-byte BLE Wi-Fi frame but still requires its own Mission Core physical acceptance. This is not a vendor API or a cross-firmware compatibility claim.",
+ "claim_limit": "One owner-controlled K1 on exact firmware 3.0.2. Bridge/Mission Core is physically accepted. Quick Connect AP activation and association are accepted only on one prepared macOS host with a preinstalled firmware provider; clean-host bootstrap is not implemented. Direct Connect reuses the physically accepted 99-byte BLE Wi-Fi frame but still requires its own Mission Core physical acceptance. This is not a vendor API or a cross-firmware compatibility claim. USB Ethernet START, point/pose capture, camera and STOP were physically qualified on Ubuntu with one K1 FW 3.0.2; hotplug and product UI acceptance are separate gates.",
"connection_modes": [
{
"id": "bridge",
@@ -39,6 +39,15 @@
"host_network_action": "exact-firmware-provider-and-single-corewlan-association",
"target_address_policy": "reviewed-fixed-k1-ap-private-ipv4",
"acceptance": "prepared-macos-host-physical-accepted"
+ },
+ {
+ "id": "usb",
+ "topology": "usb-ethernet",
+ "direction": "k1-usb-ethernet-to-board",
+ "device_network_action": "none",
+ "host_network_action": "existing-os-rndis-dhcp",
+ "target_address_policy": "usb-dhcp-peer-and-exact-kernel-route",
+ "acceptance": "firmware-3.0.2-physical-transport-qualified"
}
]
},
diff --git a/src/k1link/device_plugins/xgrids_k1/active_acquisition_recovery_checkpoint.py b/src/k1link/device_plugins/xgrids_k1/active_acquisition_recovery_checkpoint.py
index 9044a39f..a781fbd4 100644
--- a/src/k1link/device_plugins/xgrids_k1/active_acquisition_recovery_checkpoint.py
+++ b/src/k1link/device_plugins/xgrids_k1/active_acquisition_recovery_checkpoint.py
@@ -67,6 +67,7 @@ ActiveAcquisitionRecoveryConnectionMode = Literal[
"bridge",
"quick-connect",
"direct-connect",
+ "usb",
]
ActiveAcquisitionRecoveryEvidencePolicy = Literal["required", "best-effort", "disabled"]
ActiveAcquisitionRecoveryMountType = Literal["handheld"]
@@ -120,7 +121,7 @@ ActiveAcquisitionRecoveryTransitionKind = Literal[
]
_CHECKPOINT_STATES = frozenset({"prepared", "active", "ceased"})
-_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
+_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
_EVIDENCE_POLICIES = frozenset({"required", "best-effort", "disabled"})
_MOUNT_TYPES = frozenset({"handheld"})
_GNSS_MODES = frozenset({"none"})
diff --git a/src/k1link/device_plugins/xgrids_k1/connection_attempt.py b/src/k1link/device_plugins/xgrids_k1/connection_attempt.py
index 9469668a..6d85aeca 100644
--- a/src/k1link/device_plugins/xgrids_k1/connection_attempt.py
+++ b/src/k1link/device_plugins/xgrids_k1/connection_attempt.py
@@ -112,7 +112,7 @@ def _network_attempt_matches_live_control_authority(
and isinstance(transport_ref, str)
and transport_ref
and context.get("transport_ref") == transport_ref
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and context.get("connection_mode") == connection_mode
and isinstance(target_ipv4, str)
and target_ipv4
@@ -187,7 +187,7 @@ def _owned_control_bootstrap_matches_network_attempt(
and network_result.get("parent_intent_id") == network_operation_id
and isinstance(transport_ref, str)
and transport_ref
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and target_ipv4
and target_port == CONTROL_MQTT_PORT
@@ -252,7 +252,7 @@ def _recovery_verify_matches_network_attempt(
and network_result.get("parent_intent_id") == network_operation_id
and isinstance(transport_ref, str)
and transport_ref
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and target_ipv4
and target_port == CONTROL_MQTT_PORT
diff --git a/src/k1link/device_plugins/xgrids_k1/connection_supervisor.py b/src/k1link/device_plugins/xgrids_k1/connection_supervisor.py
index 335829b7..909bb4e1 100644
--- a/src/k1link/device_plugins/xgrids_k1/connection_supervisor.py
+++ b/src/k1link/device_plugins/xgrids_k1/connection_supervisor.py
@@ -16,7 +16,7 @@ from k1link.device_plugins.xgrids_k1.host_diagnostics import (
host_diagnostics_for_reasons,
)
-ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
+ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
RouteClass = Literal["direct", "default", "tunnel", "unavailable", "unknown"]
TcpState = Literal["unknown", "reachable", "unreachable"]
IdentityState = Literal["unverified", "verified", "stale", "mismatch"]
@@ -27,6 +27,7 @@ DeviceNetworkSource = Literal[
"ble-post-write-status",
"ble-read-only-status",
"durable-semantic-topology",
+ "usb-enumeration",
]
AllowedAction = Literal[
"select-connection-intent",
diff --git a/src/k1link/device_plugins/xgrids_k1/device_management.py b/src/k1link/device_plugins/xgrids_k1/device_management.py
new file mode 100644
index 00000000..acb756a0
--- /dev/null
+++ b/src/k1link/device_plugins/xgrids_k1/device_management.py
@@ -0,0 +1,68 @@
+"""Plugin action boundary for explicit, idle-only XGRIDS maintenance."""
+from __future__ import annotations
+
+import hashlib
+from typing import Any, Literal, Self, cast
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from k1link.web.device_lifecycle import TERMINAL_ACQUISITION_STATES
+
+ACTION_DEVICE_MANAGE = "device.manage"
+
+
+class DeviceManagementRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ operation_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,128}$")
+ operation: Literal["info", "projects", "delete-projects", "format-storage", "usb-storage",
+ "usb-data", "power-off", "reboot"]
+ expected_session_generation: int = Field(ge=0)
+ expected_state_revision: int = Field(ge=0)
+ operator_confirmed: bool = False
+ project_ids: list[str] = Field(default_factory=list, max_length=4096)
+ catalog_revision: str | None = None
+
+ @model_validator(mode="after")
+ def validate_operation(self) -> Self:
+ if self.operation not in {"info", "projects"} and not self.operator_confirmed:
+ raise ValueError("Подтвердите операцию с K1")
+ if (self.operation == "delete-projects") != bool(self.project_ids):
+ raise ValueError("Выберите проекты для удаления")
+ if len(set(self.project_ids)) != len(self.project_ids):
+ raise ValueError("Проекты повторяются в выборе")
+ return self
+
+
+def manage_device(service: Any, request: DeviceManagementRequest) -> dict[str, object]:
+ with service._lock:
+ acquisition = service._acquisition
+ if acquisition is not None and acquisition.state not in TERMINAL_ACQUISITION_STATES:
+ raise ValueError("Сначала завершите съёмку K1")
+ device_id, session_id = service._device_id, service._device_session_id
+ fingerprint = hashlib.sha256(request.model_dump_json().encode()).hexdigest()
+ record, created = service._operations.begin(
+ ACTION_DEVICE_MANAGE, operation_id=request.operation_id,
+ idempotency_key=request.operation_id, device_id=device_id, device_session_id=session_id,
+ deadline_seconds=30, request_fingerprint=fingerprint,
+ )
+ if not created:
+ return cast(dict[str, object], record.result) if record.result else {
+ "status": "unknown", "message": "Операция уже была принята",
+ }
+ try:
+ result = service._application_control_session.manage_device(
+ operation=request.operation, identifier=request.operation_id,
+ project_ids=tuple(request.project_ids), catalog_revision=request.catalog_revision,
+ expected_session_generation=request.expected_session_generation,
+ expected_state_revision=request.expected_state_revision,
+ )
+ except ValueError as exc:
+ result = {"status": "blocked", "message": str(exc)}
+ except Exception:
+ result = {"status": "unknown", "message": "K1 не подтвердил результат операции"}
+ service._operations.transition(
+ record.operation_id, "succeeded" if result["status"] == "succeeded" else "failed",
+ stage_code="device-management", message_code="device.management." + result["status"],
+ result=result,
+ )
+ return cast(dict[str, object], result)
diff --git a/src/k1link/device_plugins/xgrids_k1/facade.py b/src/k1link/device_plugins/xgrids_k1/facade.py
index aa0c0c1d..090f80ea 100644
--- a/src/k1link/device_plugins/xgrids_k1/facade.py
+++ b/src/k1link/device_plugins/xgrids_k1/facade.py
@@ -19,14 +19,14 @@ import unicodedata
from collections.abc import Awaitable, Callable, Collection, Iterator, Mapping, Sequence
from concurrent.futures import Future as ConcurrentFuture
from concurrent.futures import TimeoutError as ConcurrentFutureTimeout
-from contextlib import AbstractContextManager, ExitStack, contextmanager, suppress
+from contextlib import AbstractContextManager, ExitStack, contextmanager, nullcontext, suppress
from dataclasses import dataclass
from dataclasses import replace as dataclass_replace
from datetime import UTC, datetime
from functools import wraps
from pathlib import Path
from typing import Any, Concatenate, Literal, Protocol, Self, cast
-from uuid import uuid4
+from uuid import NAMESPACE_URL, uuid4, uuid5
from bleak.exc import BleakDeviceNotFoundError, BleakError
from missioncore_plugin_sdk.v0alpha2 import (
@@ -144,6 +144,11 @@ from k1link.device_plugins.xgrids_k1.device_identity_pin_store import (
DeviceIdentityPinStoreCorrupt,
DeviceIdentityPinStoreError,
)
+from k1link.device_plugins.xgrids_k1.device_management import (
+ ACTION_DEVICE_MANAGE,
+ DeviceManagementRequest,
+ manage_device,
+)
from k1link.device_plugins.xgrids_k1.firmware_credential import (
K1_FW302_CREDENTIAL_PROVIDER_ID,
)
@@ -263,6 +268,8 @@ from k1link.web.plugin_runtime import (
PluginExecutionError,
)
+from .usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
+
XGRIDS_K1_PLUGIN_ID = "nodedc.device.xgrids-lixelkity-k1"
XGRIDS_K1_PLUGIN_VERSION = "0.7.5"
XGRIDS_K1_MODEL_ID = "xgrids.lixelkity-k1"
@@ -332,12 +339,13 @@ def _capture_network_intent_device(
return capture_discovered_device(macos_uuid)
-ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
-ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot"]
+ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
+ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot", "usb-ethernet"]
CONNECTION_TOPOLOGY_BY_MODE: dict[ConnectionMode, ConnectionTopology] = {
"bridge": "direct-lan",
"quick-connect": "device-ap",
"direct-connect": "controller-hotspot",
+ "usb": "usb-ethernet",
}
@@ -424,6 +432,7 @@ class ConfiguredEndpointProbeError(RuntimeError):
ACTION_STATE_READ = "state.read"
+
ACTION_DISCOVERY_SCAN = "discovery.scan"
ACTION_DEVICE_INSPECT = "device.inspect"
ACTION_SENSOR_CATALOG_READ = "sensor.catalog.read"
@@ -1030,7 +1039,7 @@ class ConnectRequest(StrictRequest):
device_id: str = Field(min_length=1, max_length=128)
ssid: str | None = Field(default=None, min_length=1, max_length=128)
password: SecretStr | None = Field(default=None, min_length=1, max_length=256)
- connection_mode: ConnectionMode = "bridge"
+ connection_mode: Literal["bridge", "quick-connect", "direct-connect"] = "bridge"
compatibility_attestation: CompatibilityAttestationRequest
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
idempotency_key: str = Field(min_length=16, max_length=160)
@@ -1077,9 +1086,9 @@ class ConnectionVerifyRequest(StrictRequest):
# the service resolves that form only from its current/durable exact
# target. New clients send the complete server-issued target contract.
device_id: str | None = Field(default=None, min_length=1, max_length=128)
- source: Literal["fresh-scan", "retained-current-process", "durable-configured-state"] = (
- "fresh-scan"
- )
+ source: Literal[
+ "fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
+ ] = "fresh-scan"
compatibility_attestation: CompatibilityAttestationRequest | None = None
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
# New clients bind Verify to the exact mode draft rendered at the click.
@@ -1239,12 +1248,13 @@ class _ProvisionalFreshBridgeTopology:
discovery_generation: int
device_session_id: str
transport_ref: str
- connection_mode: Literal["bridge"]
+ connection_mode: Literal["bridge", "usb"]
ipv4: str
firmware_version: str
observed_at_utc: str
semantic_predecessor_revision: int
+ usb_generation: str | None = None
@dataclass(frozen=True, slots=True)
class _ScenarioResetRetiredTransportAuthority:
@@ -1395,7 +1405,7 @@ class ViewerSettingsRequest(StrictRequest):
color_mode: Literal["intensity", "height", "distance", "rgb", "class"] = "intensity"
palette: Literal["turbo", "viridis", "plasma", "grayscale", "custom"] = "turbo"
custom_color: str = Field(default="#f7f8f4", pattern=r"^#[0-9A-Fa-f]{6}$")
- accumulation_seconds: float = Field(default=12.0, ge=0.0, le=120.0)
+ accumulation_seconds: float = Field(default=12.0, ge=0.0, allow_inf_nan=False)
show_points: bool = True
show_trajectory: bool = True
show_grid: bool = True
@@ -1476,6 +1486,7 @@ class XgridsK1CompatibilityService:
application_authority_loader: ApplicationAuthorityLoader | None = None,
calibration_snapshot_reader: DeviceCalibrationSnapshotReader | None = None,
host_wifi_association_probe: HostWifiAssociationProbe | None = None,
+ usb_network_probe: LinuxK1UsbProbe | None = None,
visualization_bridge_factory: Callable[..., Any] | None = None,
) -> None:
self.repository_root = repository_root.resolve()
@@ -1486,6 +1497,7 @@ class XgridsK1CompatibilityService:
# network/control lifecycle owner.
configure_ble_runtime_process_lease(self.repository_root)
self.evidence_root = resolve_missioncore_evidence_dir(self.repository_root)
+ self._usb_network_probe = usb_network_probe
self._host_wifi_association_probe = (
host_wifi_association_probe
or HostWifiAssociationIdentityProbe(
@@ -2163,7 +2175,9 @@ class XgridsK1CompatibilityService:
and topology_record is not None
and topology_record.transport_ref == transport_ref
and topology_record.connection_mode == connection_mode
- and topology_record.source in {"ble-post-write-status", "ble-read-only-status"}
+ and topology_record.source in {
+ "ble-post-write-status", "ble-read-only-status", "usb-enumeration"
+ }
and ledger_record.last_observation.ipv4 == topology_record.ipv4
and topology_record.compatibility_profile_id == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
):
@@ -2259,7 +2273,7 @@ class XgridsK1CompatibilityService:
ipv4: str,
compatibility_attestation: CompatibilityAttestationRequest,
captured_device: CapturedDiscoveredDevice | None,
- source: Literal["ble-post-write-status", "ble-read-only-status"],
+ source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
observed_at_utc: str,
) -> str | None:
"""Commit what the K1 reported, independently from the Mac route.
@@ -2311,6 +2325,7 @@ class XgridsK1CompatibilityService:
"ble-post-write-status",
"ble-read-only-status",
"durable-semantic-topology",
+ "usb-enumeration",
],
observed_at_utc: str,
force_new_session: bool,
@@ -2387,7 +2402,8 @@ class XgridsK1CompatibilityService:
self._connection_mode = connection_mode
self._device_id = self._device_ids_by_transport_ref.setdefault(
transport_ref,
- new_device_id(),
+ (f"device-{uuid5(NAMESPACE_URL, 'xgrids-k1:' + transport_ref)}"
+ if connection_mode == "usb" else new_device_id()),
)
self._device_session_id = next_device_session_id
self._device_session_opened_at = observed_at_utc
@@ -2433,7 +2449,7 @@ class XgridsK1CompatibilityService:
connection_mode: ConnectionMode,
ipv4: str,
firmware_version: str,
- source: Literal["ble-post-write-status", "ble-read-only-status"],
+ source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
observed_at_utc: str,
predecessor_revision: int | None = None,
) -> None:
@@ -2557,6 +2573,27 @@ class XgridsK1CompatibilityService:
"""Bind one kernel route sample to this service's Wi-Fi association."""
path = _inspect_host_path(target)
+ with self._lock:
+ usb_transport = self._selected_device_id if self._connection_mode == "usb" else None
+ if usb_transport is not None:
+ try:
+ attachment = self._require_usb_attachment(usb_transport)
+ if (attachment.peer_ipv4 != target or attachment.interface != path.interface
+ or attachment.source_ipv4 != path.source_ipv4):
+ raise OSError("USB route changed")
+ except OSError:
+ return HostPathProbeResult(
+ available=False, fingerprint=None, interface=path.interface,
+ source_ipv4=path.source_ipv4, route_class="unavailable",
+ reason_code="usb-attachment-unavailable",
+ )
+ if path.available and path.fingerprint is not None:
+ return dataclass_replace(
+ path, fingerprint=hashlib.sha256(
+ (path.fingerprint + ":" + attachment.generation).encode()
+ ).hexdigest(),
+ )
+ return path
association = self._host_wifi_association_probe.observe(
path.interface,
timeout_seconds=association_timeout_seconds,
@@ -2572,14 +2609,19 @@ class XgridsK1CompatibilityService:
if retained_unproven_path is not None:
return retained_unproven_path
if (
- fail_closed_unproven_association
- and not association["continuity_proven"]
- # Missing BSSID is a documented macOS privacy condition. Its
- # process-scoped fallback token still detects route/interface
- # transitions. The monitor marks that result as unproven below so
- # it cannot replace a verified association fingerprint merely
- # because macOS changed what identity fields it disclosed.
- and association_reason != "association-identity-unavailable"
+ not association["continuity_proven"]
+ and (
+ # Linux supplies no fallback token when NetworkManager cannot
+ # prove association. Report unavailable even during bootstrap;
+ # an empty token cannot be bound to a route fingerprint.
+ association["adapter"] == "linux-networkmanager"
+ or (
+ fail_closed_unproven_association
+ # macOS privacy-limited observations have a process-scoped
+ # fallback token. Preserve their existing continuity policy.
+ and association_reason != "association-identity-unavailable"
+ )
+ )
):
return HostPathProbeResult(
available=False,
@@ -3066,6 +3108,7 @@ class XgridsK1CompatibilityService:
semantic_predecessor_revision: int | None = None,
force_new_intent: bool = False,
persist_semantic_topology: bool = True,
+ source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
) -> str:
"""Bind an exact BLE status read to a fresh non-mutating intent."""
@@ -3081,7 +3124,7 @@ class XgridsK1CompatibilityService:
connection_mode=connection_mode,
ipv4=target.ipv4,
firmware_version=firmware_version,
- source="ble-read-only-status",
+ source=source,
observed_at_utc=observed_at_utc,
predecessor_revision=semantic_predecessor_revision,
)
@@ -3110,7 +3153,7 @@ class XgridsK1CompatibilityService:
transport_ref=transport_ref,
connection_mode=connection_mode,
target=target,
- source="ble-read-only-status",
+ source=source,
):
raise RuntimeError("read-only статус K1 потерял актуальность до admission")
return intent_id
@@ -3129,6 +3172,7 @@ class XgridsK1CompatibilityService:
force_new_intent: bool = False,
force_new_session: bool = False,
persist_semantic_topology: bool = True,
+ source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None = None,
) -> str:
"""Persist, supervise and project one exact non-mutating BLE status.
@@ -3168,6 +3212,7 @@ class XgridsK1CompatibilityService:
semantic_predecessor_revision=semantic_predecessor_revision,
force_new_intent=force_new_intent,
persist_semantic_topology=persist_semantic_topology,
+ source=source,
)
retired_ingress_session_id = self._project_applied_device_topology(
transport_ref=transport_ref,
@@ -3175,7 +3220,7 @@ class XgridsK1CompatibilityService:
target=target,
compatibility_attestation=attestation_snapshot,
captured_device=captured_device,
- source="ble-read-only-status",
+ source=source,
observed_at_utc=observed_at_utc,
force_new_session=force_new_session,
retained_prepared_stop_owner=retained_prepared_stop_owner,
@@ -5731,7 +5776,7 @@ class XgridsK1CompatibilityService:
provisional.reconfiguration_intent_id
or f"fresh-verify-rejected-{provisional.device_session_id}"
),
- requested_mode="bridge",
+ requested_mode=provisional.connection_mode,
expected_device_id=None,
)
with self._lock:
@@ -5817,12 +5862,21 @@ class XgridsK1CompatibilityService:
"DeviceInfo identity не закреплена за выбранным BLE transport",
reason_code="device-identity-pin-mismatch",
)
+ if provisional.connection_mode == "usb":
+ attachment = self._require_usb_attachment(provisional.transport_ref)
+ if (attachment.generation != provisional.usb_generation
+ or attachment.peer_ipv4 != provisional.ipv4):
+ raise ConnectionVerificationError(
+ "USB-подключение изменилось во время проверки",
+ reason_code="usb-attachment-changed",
+ )
self._persist_semantic_topology(
transport_ref=provisional.transport_ref,
connection_mode=provisional.connection_mode,
ipv4=provisional.ipv4,
firmware_version=provisional.firmware_version,
- source="ble-read-only-status",
+ source=("usb-enumeration" if provisional.connection_mode == "usb"
+ else "ble-read-only-status"),
observed_at_utc=provisional.observed_at_utc,
predecessor_revision=provisional.semantic_predecessor_revision,
)
@@ -6385,7 +6439,9 @@ class XgridsK1CompatibilityService:
),
physical_recovery_mode=(
cast(ConnectionMode, recovery_connection_mode)
- if recovery_connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ if recovery_connection_mode in {
+ "bridge", "quick-connect", "direct-connect", "usb"
+ }
else None
),
)
@@ -10045,7 +10101,7 @@ class XgridsK1CompatibilityService:
and isinstance(scenario_reset_id, str)
and isinstance(scenario_reset_revision, int)
and scenario_reset_mode
- in {"bridge", "quick-connect", "direct-connect"}
+ in {"bridge", "quick-connect", "direct-connect", "usb"}
and scenario_reset_revision == self._desired_connection_mode_revision
and scenario_reset_mode == self._desired_connection_mode
):
@@ -12642,6 +12698,25 @@ class XgridsK1CompatibilityService:
persisted = checkpoint.current_active_physical_proof
status = checkpoint.current_active_status_proof
+ # The physical READY commit may precede checkpoint cessation (including
+ # a process exit between fsyncs). Reconstruct only that immediate local
+ # predecessor for the existing exact reset/reopen ancestry predicate.
+ # This is an in-memory proof check, never a ledger rewrite or new edge.
+ reopened = record
+ if (
+ record.stage == "resolved"
+ and record.resolution == "start-active-observed"
+ and record.reconciliations
+ and record.reconciliations[-1].kind == "resolved-active-cessation"
+ and record.reconciliations[-1].resolution == "physical-standby-observed"
+ ):
+ reopened = dataclass_replace(
+ record,
+ revision=record.revision - 1,
+ stage="observing",
+ resolution=None,
+ reconciliations=record.reconciliations[:-1],
+ )
if not (
persisted is not None
and status is not None
@@ -12653,12 +12728,11 @@ class XgridsK1CompatibilityService:
and record.operation_id == checkpoint.original_start_operation_id
and record.acquisition_id == checkpoint.acquisition_id
and record.action == "start"
- and record.stage == "observing"
- and record.resolution is None
+ and reopened.stage == "observing"
+ and reopened.resolution is None
and record.revision > persisted.ledger_revision
and record.payload_sha256 == checkpoint.start_payload_sha256
- and record.reopened_resolved_start_requires_reconciliation
- and record.reconciled_physical_state == "active"
+ and reopened.reopened_resolved_start_requires_reconciliation
):
return False
@@ -15913,6 +15987,7 @@ class XgridsK1CompatibilityService:
"direct-lan": "bridge",
"device-ap": "quick-connect",
"controller-hotspot": "direct-connect",
+ "usb-ethernet": "usb",
}[request.compatibility_attestation.topology]
if request.compatibility_attestation is not None
else None
@@ -15990,7 +16065,8 @@ class XgridsK1CompatibilityService:
reason_code="connection-verify-control-dispatch-active",
)
command_dispatch_gate_acquired = True
- with self._borrow_network_ble_process_lease():
+ with (nullcontext() if requested_mode == "usb"
+ else self._borrow_network_ble_process_lease()):
(
verify_operation_id,
verify_created,
@@ -18152,7 +18228,7 @@ class XgridsK1CompatibilityService:
if (
not isinstance(transport_ref, str)
or not transport_ref.strip()
- or connection_mode not in {"bridge", "quick-connect", "direct-connect"}
+ or connection_mode not in {"bridge", "quick-connect", "direct-connect", "usb"}
):
raise ConnectionVerificationError(
"Физическая recovery-цель K1 отсутствует в durable ledger",
@@ -18303,6 +18379,7 @@ class XgridsK1CompatibilityService:
"direct-lan": "bridge",
"device-ap": "quick-connect",
"controller-hotspot": "direct-connect",
+ "usb-ethernet": "usb",
}[request.compatibility_attestation.topology],
)
self._require_connection_mode_draft_for_verify(
@@ -18874,13 +18951,83 @@ class XgridsK1CompatibilityService:
)
return association, observation, supervisor_epoch_before
+ def _require_usb_attachment(self, transport_ref: str) -> UsbNetworkAttachment:
+ if self._usb_network_probe is None:
+ raise OSError("USB-подключение доступно только на подготовленном БК")
+ return self._usb_network_probe.require(transport_ref)
+
+ async def _adopt_usb_connection_owned(
+ self,
+ transport_ref: str,
+ attestation: CompatibilityAttestationRequest,
+ *,
+ retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None,
+ ) -> tuple[str, _ProvisionalFreshBridgeTopology]:
+ """Supply topology to the existing Verify/DeviceInfo/recovery transaction.
+
+ Caller owns lifecycle, dispatch, provisioning and process gates and has
+ checked active receiver/STOP ownership. No BLE or network write occurs.
+ DHCP is provisional; the common commit still requires the identity pin.
+ """
+ if self._network_mutation_ledger.snapshot().status in {"corrupt", "unresolved"}:
+ raise ConnectionVerificationError(
+ "Предыдущая настройка сети K1 требует завершения",
+ reason_code="usb-network-reconciliation-required",
+ )
+ self._require_semantic_topology_store_writable()
+ assert self._semantic_topology_store is not None
+ semantic = self._semantic_topology_store.snapshot()
+ attachment = await _run_blocking_operation_without_abandonment(
+ self._require_usb_attachment, transport_ref,
+ )
+ self._retire_application_control_for_network_change(allow_terminal_failure=True)
+ observed_at = _utc_now_iso()
+ intent_id = self._apply_read_only_device_topology(
+ transport_ref=transport_ref, connection_mode="usb",
+ ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
+ compatibility_attestation=_attestation_snapshot(attestation),
+ observed_at_utc=observed_at, force_new_intent=True, force_new_session=True,
+ persist_semantic_topology=False, source="usb-enumeration",
+ retained_prepared_stop_owner=retained_prepared_stop_owner,
+ )
+ with self._lock:
+ assert self._device_session_id is not None
+ provisional = _ProvisionalFreshBridgeTopology(
+ reconfiguration_intent_id=None,
+ reconfiguration_revision=self._connection_reconfiguration_revision,
+ supervisor_intent_id=intent_id,
+ discovery_generation=self._ble_discovery_generation,
+ device_session_id=self._device_session_id,
+ transport_ref=transport_ref, connection_mode="usb",
+ ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
+ observed_at_utc=observed_at,
+ semantic_predecessor_revision=semantic.record.revision if semantic.record else 0,
+ usb_generation=attachment.generation,
+ )
+ try:
+ observation = await _run_blocking_operation_without_abandonment(
+ self._probe_control_endpoint, attachment.peer_ipv4,
+ )
+ current = await _run_blocking_operation_without_abandonment(
+ self._require_usb_attachment, transport_ref,
+ )
+ if current != attachment or not observation.reachable:
+ raise ConnectionVerificationError(
+ "K1 найден по USB, но управляющий канал пока недоступен",
+ reason_code="usb-control-endpoint-unavailable",
+ )
+ except BaseException:
+ self._reset_provisional_fresh_bridge_topology(provisional)
+ raise
+ return attachment.peer_ipv4, provisional
+
async def _adopt_existing_lan_connection(
self,
device_id: str,
compatibility_attestation: CompatibilityAttestationRequest,
*,
verification_source: Literal[
- "fresh-scan", "retained-current-process", "durable-configured-state"
+ "fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
] = "fresh-scan",
expected_discovery_generation: int | None = None,
expected_mode_revision: int | None = None,
@@ -18895,6 +19042,8 @@ class XgridsK1CompatibilityService:
requested_mode = "quick-connect"
elif compatibility_attestation.topology == "controller-hotspot":
requested_mode = "direct-connect"
+ elif compatibility_attestation.topology == "usb-ethernet":
+ requested_mode = "usb"
else:
raise ValueError("read-only K1 adoption received an unsupported topology")
self._require_connection_mode_draft_for_verify(
@@ -18991,6 +19140,13 @@ class XgridsK1CompatibilityService:
verification_fence_active = False
provisional_topology: _ProvisionalFreshBridgeTopology | None = None
try:
+ if requested_mode == "usb":
+ return await self._adopt_usb_connection_owned(
+ actual_transport_ref, compatibility_attestation,
+ retained_prepared_stop_owner=(
+ retained_prepared_stop_owner if retained_stop_recovery else None
+ ),
+ )
ledger_snapshot = self._network_mutation_ledger.snapshot()
if (
ledger_snapshot.status == "unresolved"
@@ -20155,6 +20311,14 @@ class XgridsK1CompatibilityService:
rediscover: bool,
) -> str:
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
+ if connection_mode == "usb":
+ attachment = self._require_usb_attachment(selected_device_id)
+ if attachment.peer_ipv4 != current_target:
+ raise ConnectionVerificationError(
+ "Адрес USB изменился; подтвердите подключение K1",
+ reason_code="usb-attachment-changed",
+ )
+ return attachment.peer_ipv4
if connection_mode == "quick-connect":
return self._confirm_quick_connect_endpoint(
selected_device_id,
@@ -20216,6 +20380,14 @@ class XgridsK1CompatibilityService:
rediscover: bool,
) -> str:
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
+ if connection_mode == "usb":
+ attachment = self._require_usb_attachment(selected_device_id)
+ if attachment.peer_ipv4 != current_target:
+ raise ConnectionVerificationError(
+ "Адрес USB изменился; подтвердите подключение K1",
+ reason_code="usb-attachment-changed",
+ )
+ return attachment.peer_ipv4
if connection_mode == "quick-connect":
return await _run_blocking_operation_without_abandonment(
self._confirm_quick_connect_endpoint,
@@ -21905,6 +22077,9 @@ class XgridsK1CompatibilityService:
runtime_state=runtime_state,
)
failure_stage = "evidence-lease-acquire"
+ # Match restart rehydration: a dead writer leaves only an unlocked
+ # marker. The canonical helper preserves live owners and all data.
+ recover_stale_active_session_marker(out_dir.parent)
lease = ActiveSessionLease.acquire(out_dir.parent, out_dir)
with self._lock:
if self._acquisition_session_lease is not None:
@@ -23915,7 +24090,7 @@ class XgridsK1CompatibilityService:
"control_session_id",
)
)
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and all(
isinstance(values[field], int) and not isinstance(values[field], bool)
for field in (
@@ -24066,7 +24241,7 @@ class XgridsK1CompatibilityService:
and isinstance(selected_device_id, str)
and isinstance(device_id, str)
and isinstance(device_session_id, str)
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and control.get("state") == "scanning"
):
@@ -24478,7 +24653,7 @@ class XgridsK1CompatibilityService:
and isinstance(selected_device_id, str)
and isinstance(device_id, str)
and isinstance(device_session_id, str)
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and runtime_snapshot.get("source_mode") == "live"
and (
@@ -24552,7 +24727,7 @@ class XgridsK1CompatibilityService:
assert isinstance(runtime_generation, int)
assert intent is not None
assert isinstance(selected_device_id, str)
- assert connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ assert connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
assert isinstance(target_ipv4, str)
if prepared_stop_owner_current:
assert prepared_stop_owner is not None
@@ -25035,11 +25210,14 @@ class XgridsK1CompatibilityService:
checkpoint_snapshot = store.snapshot()
checkpoint = checkpoint_snapshot.checkpoint
if checkpoint is not None and checkpoint.state == "ceased":
- return bool(
+ owned = bool(
checkpoint.acquisition_id == expected_acquisition_id
and checkpoint.original_start_operation_id
== expected_start_operation_id
)
+ if owned:
+ self._set_active_acquisition_checkpoint_reason(None)
+ return owned
if not (
checkpoint_snapshot.status in {"prepared", "active"}
and checkpoint is not None
@@ -27881,6 +28059,33 @@ class XgridsK1CompatibilityService:
self._connection_loss_confirmation_count = 0
return
+ # A short association gap can revoke the control epoch while the
+ # data socket survives. Once the host path returns, negative probe
+ # streaks are already zero and no MQTT disconnect wakes the receiver.
+ # Hand that exact confirmed START to the existing read-only recovery;
+ # never promote the old control proof into the new host epoch.
+ returned_path = self._connection_supervisor.snapshot()
+ verified = application_control_session.get("verified_control")
+ verified_epoch = (
+ verified.get("host_path_epoch") if isinstance(verified, Mapping) else None
+ )
+ if (
+ application_control_session.get("state") == "scanning"
+ and returned_path.host_path.available
+ and returned_path.control_plane.reason_code == "host-path-epoch-changed"
+ and isinstance(verified_epoch, int)
+ and not isinstance(verified_epoch, bool)
+ and 0 < verified_epoch < returned_path.host_path.epoch
+ and self._request_active_stream_recovery_for_local_loss(
+ "host-path-epoch-changed"
+ )
+ ):
+ with self._lock:
+ self._connection_loss_signature = None
+ self._connection_loss_evidence_token = None
+ self._connection_loss_confirmation_count = 0
+ return
+
# STOP PREPARE replaces the current successful START ledger row before
# the transport can acquire its dispatch fence. Preserve only this
# exact, bounded, still-undispatched owner; a terminal control state,
@@ -30508,10 +30713,27 @@ class XgridsK1CompatibilityService:
stop_operation_id=current_stop_operation_id,
)
checkpoint_snapshot_status: str | None = None
+ completed_checkpoint_owned = False
if self._active_acquisition_checkpoint is not None:
try:
- checkpoint_snapshot_status = (
- self._active_acquisition_checkpoint.snapshot().status
+ checkpoint_snapshot = self._active_acquisition_checkpoint.snapshot()
+ checkpoint_snapshot_status = checkpoint_snapshot.status
+ checkpoint = checkpoint_snapshot.checkpoint
+ # Completed local cleanup releases operation/evidence owners.
+ # A ceased journal for this same completed acquisition remains
+ # terminal proof; it grants no recovery or command authority.
+ completed_checkpoint_owned = bool(
+ current is not None
+ and current.state == "completed"
+ and checkpoint_snapshot_status == "ceased"
+ and checkpoint is not None
+ and checkpoint.acquisition_id == current.acquisition_id
+ and (
+ canonical_start_operation_id is None
+ or checkpoint.original_start_operation_id
+ == canonical_start_operation_id
+ )
+ and self._active_acquisition_checkpoint_trust == "trusted"
)
except (ActiveAcquisitionRecoveryCheckpointError, OSError, ValueError):
checkpoint_snapshot_status = None
@@ -30522,7 +30744,10 @@ class XgridsK1CompatibilityService:
# have no checkpoint to cease. Missing/corrupt storage does not
# enter this compatibility branch and remains fail closed.
or checkpoint_snapshot_status == "empty"
+ or completed_checkpoint_owned
)
+ if completed_checkpoint_owned:
+ self._set_active_acquisition_checkpoint_reason(None)
if (
current is not None
and current.control_mode == "plugin-commanded"
@@ -31922,6 +32147,7 @@ class XgridsK1ServicePort(Protocol):
_SNAPSHOT_RUNTIME_FENCED_MUTATING_ACTIONS = frozenset(
{
+ ACTION_DEVICE_MANAGE,
ACTION_DISCOVERY_SCAN,
ACTION_NETWORK_PROVISION,
ACTION_CONNECTION_MODE_SELECT,
@@ -31950,6 +32176,7 @@ class XgridsK1PluginFacade:
plugin_id = XGRIDS_K1_PLUGIN_ID
action_ids = frozenset(
{
+ ACTION_DEVICE_MANAGE,
ACTION_STATE_READ,
ACTION_DISCOVERY_SCAN,
ACTION_DEVICE_INSPECT,
@@ -32078,6 +32305,10 @@ class XgridsK1PluginFacade:
mode_request,
)
self.service.bind_runtime_event_loop(asyncio.get_running_loop())
+ if action_id == ACTION_DEVICE_MANAGE:
+ return await asyncio.to_thread(
+ manage_device, self.service, DeviceManagementRequest.model_validate(payload),
+ )
if action_id == ACTION_STATE_READ:
EmptyRequest.model_validate(payload)
return await self._read_state_single_flight()
@@ -33080,7 +33311,7 @@ def _physical_command_pending_reopened_reconciliation_mode(
if not (
isinstance(operation_id, str)
and isinstance(revision, int)
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(retirements, list)
and isinstance(reopens, list)
):
@@ -33322,7 +33553,9 @@ def _resolved_apply_durable_observation_target(
and isinstance(semantic_record, Mapping)
and semantic_record.get("schema_version") == "missioncore.xgrids-k1-semantic-topology/v1"
and semantic_record.get("compatibility_profile_id") == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
- and semantic_record.get("source") in {"ble-post-write-status", "ble-read-only-status"}
+ and semantic_record.get("source") in {
+ "ble-post-write-status", "ble-read-only-status", "usb-enumeration"
+ }
):
return None
@@ -33332,7 +33565,7 @@ def _resolved_apply_durable_observation_target(
if not (
isinstance(transport_ref, str)
and transport_ref
- and connection_mode in {"bridge", "quick-connect", "direct-connect"}
+ and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(ipv4, str)
and ipv4
and physical_transport_ref_comparison_key(transport_ref)
@@ -33704,7 +33937,7 @@ def _connection_policy_projection(
)
recovery_mode = (
recovery_mode_raw
- if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect"}
+ if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect", "usb"}
else None
)
recovery_advertised = bool(
@@ -33820,7 +34053,7 @@ def _connection_policy_projection(
semantic_topology_record.get("connection_mode")
if isinstance(semantic_topology_record, Mapping)
and semantic_topology_record.get("connection_mode")
- in {"bridge", "quick-connect", "direct-connect"}
+ in {"bridge", "quick-connect", "direct-connect", "usb"}
else None
)
if transport_is_retired(semantic_recovery_ref):
@@ -33947,7 +34180,7 @@ def _connection_policy_projection(
and semantic_topology_record.get("transport_ref")
and not transport_is_retired(semantic_topology_record.get("transport_ref"))
and semantic_topology_record.get("connection_mode")
- in {"bridge", "quick-connect", "direct-connect"}
+ in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(semantic_topology_record.get("ipv4"), str)
and semantic_topology_record.get("ipv4")
)
diff --git a/src/k1link/device_plugins/xgrids_k1/linux_host.py b/src/k1link/device_plugins/xgrids_k1/linux_host.py
index a1f48f1b..c4417876 100644
--- a/src/k1link/device_plugins/xgrids_k1/linux_host.py
+++ b/src/k1link/device_plugins/xgrids_k1/linux_host.py
@@ -25,7 +25,12 @@ from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
def _run(args: list[str], timeout: float = 8) -> str:
- result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
+ # nmcli localizes even terse ACTIVE values (for example yes/no -> да/нет).
+ # Pin machine output only for this child; keep UTF-8 SSIDs and host locale.
+ result = subprocess.run(
+ args, capture_output=True, text=True, encoding="utf-8", timeout=timeout,
+ check=False, env={**os.environ, "LC_ALL": "C", "LANG": "C"},
+ )
if result.returncode:
# Never forward subprocess diagnostics: SSIDs or other local data may occur.
raise OSError("Network observation unavailable")
diff --git a/src/k1link/device_plugins/xgrids_k1/network_mutation_ledger.py b/src/k1link/device_plugins/xgrids_k1/network_mutation_ledger.py
index 247245a1..03df3856 100644
--- a/src/k1link/device_plugins/xgrids_k1/network_mutation_ledger.py
+++ b/src/k1link/device_plugins/xgrids_k1/network_mutation_ledger.py
@@ -24,6 +24,7 @@ NETWORK_MUTATION_LEDGER_LOCK_FILENAME = ".network-mutation.lock"
NETWORK_MUTATION_LEDGER_MAX_BYTES = 64 * 1024
NetworkConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
+PreviousConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
NetworkMutationStage = Literal["prepared", "dispatching", "observing", "resolved"]
NetworkMutationWriteMode = Literal["with_response", "without_response"]
NetworkMutationResolution = Literal[
@@ -105,13 +106,14 @@ class PreviousConnectionEvidence:
"""Last admitted topology retained as evidence, never as live reachability."""
transport_ref: str
- mode: NetworkConnectionMode
+ mode: PreviousConnectionMode
ipv4: str | None
device_session_id: str | None
def __post_init__(self) -> None:
_validate_identifier(self.transport_ref, field_name="transport_ref")
- _validate_connection_mode(self.mode)
+ if self.mode != "usb":
+ _validate_connection_mode(self.mode)
if self.ipv4 is not None:
try:
parsed = ipaddress.ip_address(self.ipv4)
@@ -856,10 +858,11 @@ def _previous_connection_from_mapping(value: object) -> PreviousConnectionEviden
label="previous connection",
)
mode_raw = _required_string(document["mode"], field_name="mode")
- _validate_connection_mode(mode_raw)
+ if mode_raw != "usb":
+ _validate_connection_mode(mode_raw)
return PreviousConnectionEvidence(
transport_ref=_required_string(document["transport_ref"], field_name="transport_ref"),
- mode=cast(NetworkConnectionMode, mode_raw),
+ mode=cast(PreviousConnectionMode, mode_raw),
ipv4=_optional_string(document["ipv4"], field_name="ipv4"),
device_session_id=_optional_string(
document["device_session_id"], field_name="device_session_id"
diff --git a/src/k1link/device_plugins/xgrids_k1/node_bridge.py b/src/k1link/device_plugins/xgrids_k1/node_bridge.py
index 5cd4bd67..3ea23990 100644
--- a/src/k1link/device_plugins/xgrids_k1/node_bridge.py
+++ b/src/k1link/device_plugins/xgrids_k1/node_bridge.py
@@ -10,6 +10,7 @@ import asyncio
import logging
import re
import traceback
+from contextlib import suppress
from datetime import UTC, datetime
from pathlib import Path
from uuid import UUID, uuid5
@@ -30,6 +31,7 @@ from .facade import (
)
from .linux_host import LinuxApplicationAuthorityLoader, LinuxWifiAssociationProbe, wifi_networks
from .protocol.application_authority import ApplicationAuthorityLoadError
+from .usb_network import LinuxK1UsbProbe
ATTESTATION = {
"firmware_version": "3.0.2",
@@ -42,25 +44,48 @@ def verification_parameters(state, operation_id, *, requested_device_id=None):
"""Use the admitted persisted Bridge target before asking for BLE again.
The facade still checks its ledger, exact identity, route, DeviceInfo and
- physical reconciliation fences. A saved address alone never grants START.
+ physical reconciliation fences, including any required live GATT read.
+ A saved address alone never grants START.
"""
parameters = {
"expected_snapshot_runtime_id": state["snapshot_runtime_id"],
"operation_id": operation_id,
}
+ if state.get("active_connection_mode") == "usb" or (
+ state.get("active_connection_mode") is None
+ and state.get("desired_connection_mode") == "usb"
+ ):
+ target = state.get("selected_device_id")
+ if isinstance(target, str) and target.startswith("usb:"):
+ parameters.update(
+ device_id=target, source="usb-enumeration",
+ compatibility_attestation={**ATTESTATION, "topology": "usb-ethernet"},
+ expected_mode_revision=state.get("desired_connection_mode_revision"),
+ )
+ return parameters
policy = (state.get("connection_policy") or {}).get("actions", {})
+ fresh = policy.get("observe-fresh-device-network") or {}
+ if requested_device_id is not None and fresh.get("allowed") is True and any(
+ item.get("likely_k1") is True
+ and str(item.get("device_id", "")).casefold() == requested_device_id.casefold()
+ for item in state.get("devices", [])
+ ):
+ # The caller already carries the current discovery generation. Preserve
+ # the explicitly selected scan result instead of replacing it with the
+ # durable target, whose BlueZ device reference may belong to an old scan.
+ return parameters
decision = policy.get("observe-configured-device-network") or {}
target = decision.get("required_transport_ref")
- selected = state.get("selected_device_id")
- if (decision.get("allowed") is True
- and decision.get("requires_live_gatt_validation") is False
- and decision.get("required_connection_mode") == "bridge"
- and isinstance(target, str) and isinstance(selected, str)
- and target.casefold() == selected.casefold()
- and (requested_device_id is None
- or target.casefold() == requested_device_id.casefold())):
+ if (
+ decision.get("allowed") is True
+ and decision.get("required_connection_mode") == "bridge"
+ and isinstance(target, str)
+ and bool(target.strip())
+ and (requested_device_id is None or target.casefold() == requested_device_id.casefold())
+ ):
parameters.update(
- device_id=target, source="durable-configured-state",
+ device_id=target,
+ source="durable-configured-state",
compatibility_attestation=ATTESTATION,
expected_mode_revision=state.get("desired_connection_mode_revision"),
)
@@ -99,15 +124,24 @@ def failure_transport_facts(error: BaseException) -> str:
seen.add(id(current))
stage = getattr(current, "operation_stage", None)
if isinstance(stage, str) and stage in {
- "resolution", "exact-uuid-scan", "connect", "gatt-contract",
- "baseline-read", "gatt-write", "status-poll", "status-read",
+ "resolution",
+ "exact-uuid-scan",
+ "connect",
+ "gatt-contract",
+ "baseline-read",
+ "gatt-write",
+ "status-poll",
+ "status-read",
}:
facts["stage"] = stage
bluez = getattr(current, "dbus_error", None)
if isinstance(bluez, str) and bluez in {
- "org.bluez.Error.InProgress", "org.bluez.Error.NotReady",
- "org.bluez.Error.Failed", "org.bluez.Error.NotAuthorized",
- "org.bluez.Error.NotSupported", "org.bluez.Error.DoesNotExist",
+ "org.bluez.Error.InProgress",
+ "org.bluez.Error.NotReady",
+ "org.bluez.Error.Failed",
+ "org.bluez.Error.NotAuthorized",
+ "org.bluez.Error.NotSupported",
+ "org.bluez.Error.DoesNotExist",
"org.freedesktop.DBus.Error.UnknownObject",
}:
facts["bluez"] = bluez
@@ -156,6 +190,7 @@ class NodeBridge:
def __init__(self, repository_root: Path, *, service=None):
self.rerun = NodeRerunHub()
self.application_authority_available = None
+ self.usb_probe = LinuxK1UsbProbe() if service is None else None
if service is None:
_validate_installed_compatibility_profile(repository_root)
loader = LinuxApplicationAuthorityLoader()
@@ -170,6 +205,7 @@ class NodeBridge:
repository_root,
application_authority_loader=loader,
host_wifi_association_probe=LinuxWifiAssociationProbe(),
+ usb_network_probe=self.usb_probe,
visualization_bridge_factory=self.rerun.create,
)
self.service = service
@@ -191,8 +227,56 @@ class NodeBridge:
for key in ("attempt_id", "recovery_operation_id"):
if key in attempt:
attempt[key] = node_operation_id(attempt[key])
+ target = verification_parameters(snapshot, "projection")
+ checkpoint = snapshot.get("active_acquisition_recovery_checkpoint") or {}
+ reset = snapshot.get("connection_scenario_reset") or {}
+ reset_completed = (reset.get("timing") or {}).get("completed_at_utc")
+ verification = next(
+ (
+ operation
+ for operation in reversed(snapshot.get("operations", []))
+ if operation.get("action") == "connection.verify"
+ and (operation.get("context") or {}).get("snapshot_runtime_id")
+ == snapshot["snapshot_runtime_id"]
+ and (
+ not reset_completed
+ or (
+ operation.get("accepted_at")
+ and datetime.fromisoformat(operation["accepted_at"])
+ > datetime.fromisoformat(reset_completed)
+ )
+ )
+ ),
+ None,
+ )
return {
+ "reconnect_target": (
+ {"device_id": target["device_id"], "source": target["source"]}
+ if "source" in target
+ else None
+ ),
+ "acquisition_recovery": {
+ key: checkpoint[key]
+ for key in (
+ "status",
+ "state",
+ "gap_open",
+ "restart_rehydration_phase",
+ "reason_code",
+ )
+ if key in checkpoint
+ },
+ "verification": (
+ {
+ "operation_id": node_operation_id(verification.get("operation_id")),
+ "status": verification.get("status"),
+ "error_code": (verification.get("error") or {}).get("code"),
+ }
+ if verification
+ else None
+ ),
"available": True,
+ "can_reset": True,
"model": "XGRIDS K1",
"mode": "bridge",
"runtime_id": snapshot["snapshot_runtime_id"],
@@ -292,6 +376,44 @@ class NodeBridge:
action, identifier = command["action"], command["operation_id"]
plugin_identifier = plugin_operation_id(identifier)
parameters = command.get("parameters", {})
+ if action == "reset":
+ # The existing reset owns cancellation, quiescence and local retirement.
+ # Never queue it behind this adapter's network-operation lock or bind
+ # the old monitor through state.read before the canonical reset runs.
+ if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
+ raise NodeEnrollmentRejected("command-expired")
+ if (
+ set(parameters) != {"mode_revision"}
+ or type(parameters["mode_revision"]) is not int
+ or parameters["mode_revision"] < 0
+ ):
+ raise NodeEnrollmentRejected("device-selection-changed")
+ result = await self.invoke(
+ "connection.mode.select",
+ {
+ "connection_mode": "bridge",
+ "expected_revision": parameters["mode_revision"],
+ "expected_snapshot_runtime_id": command.get("runtime_id"),
+ "reset_scenario": True,
+ "reset_id": plugin_identifier,
+ },
+ identifier,
+ )
+ marker = result.get("connection_scenario_reset") or {}
+ committed = (
+ marker.get("reset_id") == plugin_identifier
+ and marker.get("revision") == parameters["mode_revision"] + 1
+ and marker.get("local_session_closed") is True
+ )
+ return {
+ **self.project(result),
+ "command_result": {
+ "operation_id": identifier,
+ "action": action,
+ "status": "succeeded" if committed else "failed",
+ "error_code": None if committed else "connection-scenario-reset-unconfirmed",
+ },
+ }
if action not in {"scan", "networks", "connect", "verify"}:
raise NodeEnrollmentRejected("unsupported-action")
async with self.lock:
@@ -316,10 +438,21 @@ class NodeBridge:
else:
# Do not derive fences at dispatch: they are the exact version
# shown to the operator before credentials were submitted.
+ recovery = (
+ verification_parameters(
+ snapshot, plugin_identifier, requested_device_id=parameters.get("device_id")
+ )
+ if action == "verify"
+ else {}
+ )
if (
parameters.get("discovery_generation") != state["discovery_generation"]
or parameters.get("mode_revision") != state["mode_revision"]
- or parameters.get("device_id") not in {v["id"] for v in state["candidates"]}
+ or (
+ "source" not in recovery
+ and parameters.get("device_id")
+ not in {v["id"] for v in state["candidates"]}
+ )
):
raise NodeEnrollmentRejected("device-selection-changed")
payload = {
@@ -339,9 +472,11 @@ class NodeBridge:
password=parameters.get("password"),
)
else:
- payload.update(verification_parameters(
- snapshot, plugin_identifier, requested_device_id=parameters["device_id"],
- ))
+ payload.update(recovery)
+ if "source" in recovery:
+ # The adapter already fenced the displayed discovery generation.
+ # The canonical durable Verify contract has no fresh-scan token.
+ payload.pop("expected_discovery_generation", None)
try:
result = await self.invoke_journalled(
"network.provision" if action == "connect" else "connection.verify",
@@ -383,7 +518,8 @@ def create_app(repository_root: Path):
sensor = NodeK1Sensor(bridge, peers)
from fastapi.responses import Response
- from k1link.viewer.node_local_media import start_local, read_local
+
+ from k1link.viewer.node_local_media import read_local, start_local
async def preview_request(request):
data = await request.body()
@@ -393,9 +529,18 @@ def create_app(repository_root: Path):
@asynccontextmanager
async def lifespan(_app):
- yield
- await peers.close_all()
- await asyncio.to_thread(bridge.service.close)
+ from .node_usb import NodeK1UsbObserver
+
+ observer = NodeK1UsbObserver(bridge, bridge.usb_probe)
+ task = asyncio.create_task(observer.run(), name="k1-usb-observer")
+ try:
+ yield
+ finally:
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+ await peers.close_all()
+ await asyncio.to_thread(bridge.service.close)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
@@ -403,6 +548,10 @@ def create_app(repository_root: Path):
async def status():
return await bridge.state()
+ @app.get("/preview-health")
+ async def preview_health():
+ return peers.snapshot()
+
@app.get("/inventory")
async def inventory(request: Request):
return await sensor.inventory(request.headers["X-Node-Id"])
@@ -414,10 +563,13 @@ def create_app(repository_root: Path):
if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
raise ValueError("Preview request expired")
await sensor.admit_preview(command, request.headers["X-Node-Id"])
- identifier = await start_local(peers, command['parameters'])
- data = await read_local(peers, identifier, command['parameters'].get('after', 0))
- return Response(data, media_type="application/vnd.missioncore.preview",
- headers={"Cache-Control": "no-store"})
+ identifier = await start_local(peers, command["parameters"])
+ data = await read_local(peers, identifier, command["parameters"].get("after", 0))
+ return Response(
+ data,
+ media_type="application/vnd.missioncore.preview",
+ headers={"Cache-Control": "no-store"},
+ )
except (ValueError, KeyError, TypeError):
return JSONResponse({"error": "Preview unavailable"}, status_code=409)
@@ -425,9 +577,12 @@ def create_app(repository_root: Path):
async def preview_read(request: Request):
try:
data = await preview_request(request)
- payload = await read_local(peers, data['peer_id'], data['after'])
- return Response(payload, media_type="application/vnd.missioncore.preview",
- headers={"Cache-Control": "no-store"})
+ payload = await read_local(peers, data["peer_id"], data["after"])
+ return Response(
+ payload,
+ media_type="application/vnd.missioncore.preview",
+ headers={"Cache-Control": "no-store"},
+ )
except (ValueError, KeyError, TypeError):
return JSONResponse({"error": "Preview expired"}, status_code=409)
@@ -460,7 +615,8 @@ def create_app(repository_root: Path):
except Exception as error:
logging.getLogger(__name__).warning(
"K1 sensor operation failed: exception=%s chain=%s",
- type(error).__name__, failure_locations(error),
+ type(error).__name__,
+ failure_locations(error),
)
return {
"state": "unknown",
diff --git a/src/k1link/device_plugins/xgrids_k1/node_sensor.py b/src/k1link/device_plugins/xgrids_k1/node_sensor.py
index e57a188b..9d000600 100644
--- a/src/k1link/device_plugins/xgrids_k1/node_sensor.py
+++ b/src/k1link/device_plugins/xgrids_k1/node_sensor.py
@@ -1,10 +1,16 @@
"""SDK projection and explicit acquisition actions for the Node-owned K1."""
import asyncio
+import base64
import hashlib
+import math
+import re
import time
from datetime import UTC, datetime
+from k1link.viewer.recorded import recorded_blueprint_rrd, recorded_blueprint_sessions
+from k1link.viewer.rerun_bridge import RerunSceneSettings
+
from .facade import (
XGRIDS_K1_MODEL_ID,
XGRIDS_K1_PLUGIN_ID,
@@ -23,6 +29,20 @@ PHYSICAL_ACCEPTANCE_KEYS = (
)
+def _storage_status(control, connected):
+ value = (control.get("transport") or {}).get("storage_status")
+ if not connected or not isinstance(value, dict):
+ return None
+ used, observed = value.get("used_percent"), value.get("observed_at")
+ if type(used) not in {int, float} or not math.isfinite(used) or not 0 <= used <= 100:
+ return None
+ try:
+ age = (datetime.now(UTC) - datetime.fromisoformat(observed)).total_seconds()
+ except (ValueError, TypeError):
+ return None
+ return {"used_percent": used, "observed_at": observed} if 0 <= age <= 5 else None
+
+
def project_sensor(snapshot, node_id):
session = snapshot.get("device_session")
if not session:
@@ -31,7 +51,7 @@ def project_sensor(snapshot, node_id):
lifecycle = snapshot.get("connection_lifecycle", {})
connected = (
lifecycle.get("connection_ready") is True
- and snapshot.get("active_connection_mode") == "bridge"
+ and snapshot.get("active_connection_mode") in {"bridge", "usb"}
)
acquisition = snapshot.get("acquisition") or {}
acquisition_state = {
@@ -66,6 +86,15 @@ def project_sensor(snapshot, node_id):
}
control = snapshot.get("application_control_session") or {}
attempt = snapshot.get("connection_attempt") or {}
+ connection_mode = snapshot.get("active_connection_mode")
+ if (
+ connection_mode is None
+ and snapshot.get("desired_connection_mode") == "usb"
+ and str(snapshot.get("selected_device_id") or "").startswith("usb:")
+ ):
+ # Transport identity survives a retired control socket; it does not
+ # imply that the device is online or that START is admitted.
+ connection_mode = "usb"
return {
"id": identifier,
"name": "XGRIDS K1",
@@ -76,7 +105,10 @@ def project_sensor(snapshot, node_id):
"verified": connected,
"online": connected,
"usb": "",
- "connection_label": "Wi-Fi · " + (snapshot.get("k1_ip") or "—"),
+ "connection_label": (
+ "USB · " if connection_mode == "usb" else "Wi-Fi · "
+ ) + (snapshot.get("k1_ip") or "—"),
+ "connection_mode": connection_mode,
"layers": ["points", "camera"],
"snapshot": {
"context": context,
@@ -92,15 +124,21 @@ def project_sensor(snapshot, node_id):
"phase": control.get("state"),
"can_start": lifecycle.get("ready_to_start", False),
"can_stop": control.get("state") in {"start-requested", "initializing", "scanning"},
- "can_verify": any(action in lifecycle.get("allowed_actions", []) for action in (
- "verify-control-read-only", "observe-current-device-network",
- "observe-configured-device-network", "observe-fresh-device-network",
- )),
+ "can_verify": any(
+ action in lifecycle.get("allowed_actions", [])
+ for action in (
+ "verify-control-read-only",
+ "observe-current-device-network",
+ "observe-configured-device-network",
+ "observe-fresh-device-network",
+ )
+ ),
"network_applied": connected or attempt.get("phase") == "network_applied",
"reason_code": None if connected else attempt.get("public_error_code"),
"acquisition_id": acquisition.get("acquisition_id"),
"acquisition_phase": acquisition.get("state"),
},
+ "storage_status": _storage_status(control, connected),
"live_settings": snapshot.get("viewer_settings", {}),
"frames": snapshot.get("metrics", {}),
"recordings": [],
@@ -134,12 +172,16 @@ class NodeK1Sensor:
async def admit_preview(self, command, node_id):
item = project_sensor(await self.raw_state(), node_id)
- if (not item or command.get("action_id") != "offer"
- or command.get("session", {}).get("device_id") != item["id"]
- or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
- or item["snapshot"]["acquisition"] != "streaming"
- or not item["control"]["acquisition_id"]
- or command.get("parameters", {}).get("acquisition_id") != item["control"]["acquisition_id"]):
+ if (
+ not item
+ or command.get("action_id") != "offer"
+ or command.get("session", {}).get("device_id") != item["id"]
+ or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
+ or item["snapshot"]["acquisition"] != "streaming"
+ or not item["control"]["acquisition_id"]
+ or command.get("parameters", {}).get("acquisition_id")
+ != item["control"]["acquisition_id"]
+ ):
raise ValueError("Acquisition is not active or changed")
return item
@@ -159,7 +201,70 @@ class NodeK1Sensor:
)
plugin_identifier = plugin_operation_id(identifier)
if action == "details":
- return item
+ if "preview_blueprint" not in params:
+ return item
+ request = params["preview_blueprint"]
+ if not isinstance(request, dict):
+ raise ValueError("Invalid preview blueprint")
+ recording, owner = request.get("recording_id"), request.get("owner")
+ if (
+ not isinstance(recording, str)
+ or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", recording)
+ or not isinstance(owner, str)
+ or not re.fullmatch(r"[a-f0-9]{32}", owner)
+ ):
+ raise ValueError("Invalid preview identity")
+ if request.get("release") is True:
+ recorded_blueprint_sessions.release(
+ ("nodedc_mission_core_spatial", recording, owner)
+ )
+ return {"released": True}
+ if request.get("view") not in {"3d", "plan"}:
+ raise ValueError("Invalid spatial view")
+ settings = ViewerSettingsRequest.model_validate(
+ request.get("settings", state.get("viewer_settings", {}))
+ )
+ follow = request.get("follow_trajectory", False)
+ if not isinstance(follow, bool):
+ raise ValueError("Invalid follow state")
+ host_playback = request.get("host_playback", False)
+ if not isinstance(host_playback, bool):
+ raise ValueError("Invalid playback owner")
+ eye = request.get("eye")
+ eye_fields = {}
+ if eye is not None:
+ import math
+
+ if not isinstance(eye, dict) or set(eye) != {"position", "lookTarget", "eyeUp"}:
+ raise ValueError("Invalid spatial eye")
+ for key, target in (
+ ("position", "eye_position"),
+ ("lookTarget", "eye_look_target"),
+ ("eyeUp", "eye_up"),
+ ):
+ value = eye[key]
+ if (
+ not isinstance(value, list)
+ or len(value) != 3
+ or any(type(v) not in {int, float} or not math.isfinite(v) for v in value)
+ ):
+ raise ValueError("Invalid spatial eye")
+ eye_fields[target] = tuple(value)
+ payload = await asyncio.to_thread(
+ recorded_blueprint_rrd,
+ RerunSceneSettings(**settings.model_dump()),
+ application_id="nodedc_mission_core_spatial",
+ recording_id=recording,
+ blueprint_session_id=owner,
+ timeline="stream_time",
+ plan_view=request["view"] == "plan",
+ follow_trajectory=follow,
+ reactivate_updates=True,
+ initialize_playback=not host_playback,
+ **eye_fields,
+ )
+ return {"rrd": base64.b64encode(payload).decode("ascii")}
+
if action == "close-peer":
await self.peers.close(params.get("peer_id"))
if params.get("retire_view") is True:
@@ -167,17 +272,22 @@ class NodeK1Sensor:
return {"ok": True}
if action == "offer":
acquisition_id = item["control"]["acquisition_id"]
- if (item["snapshot"]["acquisition"] != "streaming" or not acquisition_id
- or params.get("acquisition_id") != acquisition_id):
+ if (
+ item["snapshot"]["acquisition"] != "streaming"
+ or not acquisition_id
+ or params.get("acquisition_id") != acquisition_id
+ ):
raise ValueError("Acquisition is not active or changed")
answer = await self.peers.offer(params)
# Signalling may outlive STOP or a replacement acquisition. Retire
# that disposable preview instead of attaching it to another run.
current = project_sensor(await self.raw_state(), node_id)
- if (current is None or current["snapshot"]["acquisition"] != "streaming"
- or current["snapshot"]["context"]["session_id"]
- != command["session"]["session_id"]
- or current["control"]["acquisition_id"] != acquisition_id):
+ if (
+ current is None
+ or current["snapshot"]["acquisition"] != "streaming"
+ or current["snapshot"]["context"]["session_id"] != command["session"]["session_id"]
+ or current["control"]["acquisition_id"] != acquisition_id
+ ):
await self.peers.close(answer["peer_id"])
raise ValueError("Acquisition changed during preview signalling")
return answer
@@ -192,6 +302,17 @@ class NodeK1Sensor:
):
raise ValueError("Device session changed")
runtime = state["snapshot_runtime_id"]
+ if action == "management":
+ if (params.get("control_generation") != current["control"]["generation"]
+ or params.get("control_revision") != current["control"]["revision"]):
+ raise ValueError("Состояние K1 изменилось. Обновите окно")
+ return await self.bridge.invoke("device.manage", {
+ **{key: value for key, value in params.items()
+ if key not in {"control_generation", "control_revision"}},
+ "operation_id": plugin_identifier,
+ "expected_snapshot_runtime_id": runtime,
+ **self.cas(state, acquisition=False),
+ }, identifier)
if action == "option":
if (
set(params) != {"profile", "settings"}
@@ -252,8 +373,11 @@ class NodeK1Sensor:
control = state.get("application_control_session") or {}
phase = control.get("state")
physical = control.get("physical_command") or state.get("physical_command") or {}
- if ("acquisition.start" in dispatched
- and phase in {"start-requested", "initializing", "scanning"}):
+ if "acquisition.start" in dispatched and phase in {
+ "start-requested",
+ "initializing",
+ "scanning",
+ }:
# The just-admitted START owns its pending physical edge.
# Returning its state does not dispatch or reconcile it again.
return project_sensor(state, node_id)
@@ -277,8 +401,15 @@ class NodeK1Sensor:
operation_id=prepare_identifier,
idempotency_key=prepare_identifier,
project_name=project_name,
- mount_type=params["mount_type"], gnss_mode=params["gnss_mode"],
- compatibility_attestation=ATTESTATION,
+ mount_type=params["mount_type"],
+ gnss_mode=params["gnss_mode"],
+ compatibility_attestation={
+ **ATTESTATION,
+ "topology": (
+ "usb-ethernet"
+ if state.get("active_connection_mode") == "usb" else "direct-lan"
+ ),
+ },
)
elif phase == "project-ready" and acquisition.get("state") == "prepared":
if acquisition.get("project_name") != project_name:
diff --git a/src/k1link/device_plugins/xgrids_k1/node_usb.py b/src/k1link/device_plugins/xgrids_k1/node_usb.py
new file mode 100644
index 00000000..35ce6d78
--- /dev/null
+++ b/src/k1link/device_plugins/xgrids_k1/node_usb.py
@@ -0,0 +1,89 @@
+"""Node-owned USB hotplug observation feeding the existing K1 Verify pipeline."""
+
+import asyncio
+import logging
+from typing import TYPE_CHECKING
+
+from .usb_network import LinuxK1UsbProbe
+
+if TYPE_CHECKING:
+ from .node_bridge import NodeBridge
+
+from .facade import (
+ CompatibilityAttestationRequest,
+ ConnectionVerifyRequest,
+ DesiredConnectionModeRequest,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class NodeK1UsbObserver:
+ def __init__(self, bridge: "NodeBridge", probe: LinuxK1UsbProbe) -> None:
+ self.bridge, self.probe = bridge, probe
+ self.accepted_generation: str | None = None
+
+ async def observe_once(self) -> None:
+ candidates = await asyncio.to_thread(self.probe.discover)
+ if len(candidates) != 1:
+ self.accepted_generation = None
+ return
+ attachment = candidates[0]
+ # Observe-only hotplug never steals a live wireless dialogue. The
+ # facade repeats all physical/receiver/lease checks under its gates.
+ async with self.bridge.lock:
+ state = await self.bridge.invoke("state.read", {}, "usb-observe")
+ mode = state.get("active_connection_mode")
+ if self.accepted_generation == attachment.generation:
+ lifecycle = state.get("connection_lifecycle") or {}
+ acquisition = state.get("acquisition") or {}
+ # A terminal STOP timeout can retire local control without a
+ # USB hotplug. Re-enter the same read-only Verify transaction;
+ # the physical ledger, not enumeration, decides its outcome.
+ # A live receiver remains owned by the connection monitor.
+ if (
+ lifecycle.get("connection_ready") is True
+ or state.get("source_mode") != "idle"
+ or acquisition.get("state") not in {None, "completed", "failed", "aborted"}
+ ):
+ return
+ if mode not in {None, "usb"} and (
+ state.get("connection_lifecycle", {}).get("connection_ready") is True
+ or state.get("source_mode") != "idle"
+ ):
+ return
+ if (state.get("connection_reconfiguration") or {}).get("intent"):
+ return
+ if state.get("desired_connection_mode") != "usb":
+ state = await asyncio.to_thread(
+ self.bridge.service.select_connection_mode, DesiredConnectionModeRequest(
+ connection_mode="usb",
+ expected_revision=state["desired_connection_mode_revision"],
+ )
+ )
+ # DeviceInfo-only, then the already implemented physical START
+ # reconciliation. This path never creates or reissues START.
+ await self.bridge.service.verify_connection(ConnectionVerifyRequest(
+ device_id=attachment.transport_ref, source="usb-enumeration",
+ compatibility_attestation=CompatibilityAttestationRequest(
+ firmware_version="3.0.2", topology="usb-ethernet",
+ verification="live-device-info",
+ ),
+ expected_mode_revision=state["desired_connection_mode_revision"],
+ ))
+ self.accepted_generation = attachment.generation
+
+ async def run(self) -> None:
+ while True:
+ try:
+ await self.observe_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ # Bound retries of topology observation only. Never log native
+ # USB details/credentials or issue a device command here.
+ logger.info("K1 USB observation pending", extra={
+ "event_code": "k1_usb_observation_pending",
+ "reason_code": getattr(error, "reason_code", type(error).__name__),
+ })
+ await asyncio.sleep(5)
diff --git a/src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py b/src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py
index 2b359885..0eb82802 100644
--- a/src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py
+++ b/src/k1link/device_plugins/xgrids_k1/physical_command_coordinator.py
@@ -57,7 +57,7 @@ class PhysicalCommandRuntimeBinding:
compatibility_profile_id: str
intent_id: str
transport_ref: str
- connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
+ connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
target_ipv4: str
target_port: int
host_path_epoch: int
diff --git a/src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py b/src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py
index 0ff68452..773a8a3d 100644
--- a/src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py
+++ b/src/k1link/device_plugins/xgrids_k1/physical_command_ledger.py
@@ -45,7 +45,7 @@ _PHYSICAL_COMMAND_ARCHIVE_AFTER_LINK_FSYNC_FAILPOINT: Callable[[], None] | None
PHYSICAL_COMMAND_APPLICATION_SUCCESS_CODE = 302252033
PhysicalCommandAction = Literal["start", "stop"]
-PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
+PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
PhysicalCommandStage = Literal["prepared", "dispatching", "observing", "resolved"]
PhysicalCommandResolution = Literal[
"not-dispatched",
@@ -120,7 +120,7 @@ PhysicalSessionState = Literal[
]
_ACTIONS = frozenset({"start", "stop"})
-_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
+_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
_STAGES = frozenset({"prepared", "dispatching", "observing", "resolved"})
_RESOLUTIONS = frozenset(
{
@@ -2483,6 +2483,7 @@ class PhysicalCommandLedger:
if (
current.reconciled_physical_state != "active"
and not current.reopened_physical_state_requires_reconciliation
+ and reopened_resolved_start is None
):
raise PhysicalCommandTransitionError(
"active rebind requires a resolved active physical state"
@@ -2573,6 +2574,8 @@ class PhysicalCommandLedger:
prior_active_observation = (
latest_recovery.observation
if latest_recovery is not None
+ else reopened_resolved_start.last_status
+ if reopened_resolved_start is not None
else current.last_status
if current.resolution == "start-active-observed"
else _latest_reconciliation_for_operation(current).observation
@@ -2692,6 +2695,7 @@ class PhysicalCommandLedger:
if (
current.reconciled_physical_state != "active"
and not reopened_physical_state_requires_reconciliation
+ and reopened_resolved_start is None
and not awaiting_ready_after_scan_over
):
raise PhysicalCommandTransitionError(
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/application_acceptance.py b/src/k1link/device_plugins/xgrids_k1/protocol/application_acceptance.py
index 0c15bdb9..97f73e0f 100644
--- a/src/k1link/device_plugins/xgrids_k1/protocol/application_acceptance.py
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/application_acceptance.py
@@ -361,6 +361,7 @@ class PhysicalAcceptanceDialogueExecutor:
event_observed: Callable[[], bool],
*,
reconciled_active_observed: Callable[[], bool] | None = None,
+ standby_work: Callable[[], None] | None = None,
) -> OperatorDialogueCheckpoint | None:
"""Service the original socket until one exact operator UI event occurs."""
@@ -382,6 +383,8 @@ class PhysicalAcceptanceDialogueExecutor:
"active recovery may replace only the workspace-entry checkpoint"
)
while True:
+ if standby_work is not None:
+ standby_work()
if reconciled_active_observed is not None and reconciled_active_observed():
if not self._transport.scan_initialization_complete(binding):
raise ApplicationAcceptanceError(
@@ -806,11 +809,15 @@ class PhysicalAcceptanceDialogueExecutor:
self._active_authority = None
self._active_binding = None
- def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
+ def maintain_standby_until_next_acquisition(
+ self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
+ ) -> None:
"""Pump the retained socket after READY; issue no device commands."""
if self._dialogue_stage != "standby-confirmed" or self._standby_binding is None:
raise ApplicationAcceptanceError("next acquisition requires confirmed standby")
while True:
+ if standby_work is not None:
+ standby_work()
self._transport.maintain_open_for(
CONTROL_NETWORK_PUMP_QUANTUM_SECONDS,
allowed_response_topics={MODELING_STATUS_RESPONSE_TOPIC},
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/application_mqtt.py b/src/k1link/device_plugins/xgrids_k1/protocol/application_mqtt.py
index 57449aa0..25c2f935 100644
--- a/src/k1link/device_plugins/xgrids_k1/protocol/application_mqtt.py
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/application_mqtt.py
@@ -53,6 +53,16 @@ from k1link.device_plugins.xgrids_k1.protocol.modeling_safety import (
MODELING_REQUEST_TOPIC,
)
+from .device_management import (
+ CONTROL_REQUEST,
+ CONTROL_RESPONSE,
+ MAX_PROJECT_RESPONSE_BYTES,
+ PROJECT_REQUEST,
+ PROJECT_RESPONSE,
+ management_action,
+ management_identity,
+)
+
MODELING_RESPONSE_TOPIC = "lixel/application/response/modeling"
CONTROL_KEEPALIVE_SECONDS = 60
CONTROL_CONNECT_TIMEOUT_SECONDS = 10.0
@@ -61,6 +71,10 @@ CONTROL_LOOP_INTERVAL_SECONDS = 0.05
MAX_CONTROL_MAINTAIN_SECONDS = 30.0
MAX_CONTROL_RESPONSE_BYTES = 64 * 1024
SYSTEM_ERROR_TOPIC = "lixel/application/report/system_error"
+# Exact non-terminating report observed on FW 3.0.2, with LixelGO's
+# severity-1 handling independently reviewed. Do not generalize by bit prefix:
+# unknown reports and known session faults remain blocking. See MQTT profile.
+_NON_TERMINATING_SYSTEM_REPORTS = frozenset({0x12041002})
CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
# DeviceInfo proves identity only at one instant. Thereafter the unchanged
# control socket must keep producing reviewed MQTT evidence. Ninety seconds
@@ -71,6 +85,8 @@ CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
CONTROL_PROOF_TTL_SECONDS = 90.0
APPLICATION_RESPONSE_TOPIC_BY_REQUEST_TOPIC = {
+ CONTROL_REQUEST: CONTROL_RESPONSE,
+ PROJECT_REQUEST: PROJECT_RESPONSE,
DEVICE_INFO_REQUEST_TOPIC: DEVICE_INFO_RESPONSE_TOPIC,
MODELING_STATUS_REQUEST_TOPIC: MODELING_STATUS_RESPONSE_TOPIC,
GET_RTK_ADVANCE_REQUEST_TOPIC: GET_RTK_ADVANCE_RESPONSE_TOPIC,
@@ -149,6 +165,7 @@ CONTROL_SUBSCRIPTION_GROUPS: tuple[tuple[tuple[str, int], ...], ...] = (
APPLICATION_RESPONSE_TOPICS = frozenset(
{
+ CONTROL_RESPONSE, PROJECT_RESPONSE,
DEVICE_INFO_RESPONSE_TOPIC,
MODELING_STATUS_RESPONSE_TOPIC,
GET_RTK_ADVANCE_RESPONSE_TOPIC,
@@ -168,6 +185,7 @@ CONTROL_REPORT_TOPICS = frozenset(
APPLICATION_REQUEST_ALLOWLIST = frozenset(
{
+ CONTROL_REQUEST, PROJECT_REQUEST,
"lixel/application/request/device_info",
"lixel/application/request/modeling_status",
"lixel/application/request/get_rtk_advance",
@@ -287,6 +305,7 @@ class _ApplicationResponseExpectation:
topic: str
identity: ApplicationMessageIdentity
modeling_action: ModelingAction | None = None
+ management_action: int | None = None
@property
def correlation_key(self) -> tuple[str, str, ModelingAction | None]:
@@ -296,9 +315,12 @@ class _ApplicationResponseExpectation:
self,
observed: ApplicationMessageIdentity,
observed_modeling_action: ModelingAction | None,
+ observed_management_action: int | None = None,
) -> bool:
if self.modeling_action is not observed_modeling_action:
return False
+ if self.management_action != observed_management_action:
+ return False
if not hmac.compare_digest(self.identity.session_id, observed.session_id):
return False
if not hmac.compare_digest(self.identity.openapi_key, observed.openapi_key):
@@ -338,6 +360,7 @@ class ApplicationMqttTransportSnapshot:
control_proof_source: str | None
control_proof_fresh: bool
control_proof_age_seconds: float | None
+ storage_status: dict[str, object] | None = None
clean_session: bool = False
keepalive_seconds: int = CONTROL_KEEPALIVE_SECONDS
automatic_reconnect: bool = False
@@ -374,6 +397,7 @@ class ApplicationMqttTransportSnapshot:
"control_proof_source": self.control_proof_source,
"control_proof_fresh": self.control_proof_fresh,
"control_proof_age_seconds": self.control_proof_age_seconds,
+ "storage_status": dict(self.storage_status) if self.storage_status else None,
"clean_session": self.clean_session,
"keepalive_seconds": self.keepalive_seconds,
"automatic_reconnect": self.automatic_reconnect,
@@ -460,11 +484,14 @@ class ReviewedApplicationMqttTransport:
self._late_known_responses = 0
self._device_status_reports = 0
self._system_error_reports = 0
+ self._blocking_system_error = False
self._report_decode_errors = 0
self._retained_control_reports_ignored = 0
self._retained_application_responses_rejected = 0
self._latest_device_session_state: str | None = None
self._latest_device_project_bound: bool | None = None
+ self._validated_status_identity: tuple[str, str] | None = None
+ self._latest_storage_status: dict[str, object] | None = None
self._latest_device_init_ready: bool | None = None
self._latest_device_id: str | None = None
self._latest_device_serial: str | None = None
@@ -1006,6 +1033,14 @@ class ReviewedApplicationMqttTransport:
and proof_age <= self._control_proof_ttl_seconds
),
control_proof_age_seconds=proof_age,
+ storage_status=(
+ dict(self._latest_storage_status)
+ if self._latest_storage_status
+ and self._validated_status_identity is not None
+ and (self._latest_device_id, self._latest_device_serial)
+ == self._validated_status_identity
+ else None
+ ),
)
def _new_client(self) -> mqtt.Client:
@@ -1108,7 +1143,9 @@ class ReviewedApplicationMqttTransport:
self._set_callback_error("control MQTT received an unreviewed subscribed topic")
return
payload = bytes(message.payload)
- if len(payload) > MAX_CONTROL_RESPONSE_BYTES:
+ response_limit = (MAX_PROJECT_RESPONSE_BYTES if message.topic == PROJECT_RESPONSE
+ else MAX_CONTROL_RESPONSE_BYTES)
+ if len(payload) > response_limit:
self._set_callback_error("control MQTT response exceeds the reviewed bound")
return
mqtt_retained = bool(getattr(message, "retain", False))
@@ -1210,6 +1247,11 @@ class ReviewedApplicationMqttTransport:
)
self._latest_device_project_bound = bool(device_report.project_id)
self._latest_device_init_ready = device_report.init_ready
+ self._latest_storage_status = (
+ {"used_percent": device_report.storage_used_percent,
+ "observed_at": evidence.observed_at_utc}
+ if device_report.storage_used_percent is not None else None
+ )
self._latest_device_id = (
device_report.header.device_id if device_report.header is not None else None
)
@@ -1239,6 +1281,9 @@ class ReviewedApplicationMqttTransport:
return
with self._lock:
self._system_error_reports += 1
+ self._blocking_system_error |= (
+ system_error_report.error_code not in _NON_TERMINATING_SYSTEM_REPORTS
+ )
self._latest_system_error_code = system_error_report.error_code
self._latest_system_error_state = (
system_error_report.session_state.name.casefold()
@@ -1254,7 +1299,7 @@ class ReviewedApplicationMqttTransport:
raise ApplicationControlDeviceFault(
"K1 control report decoding failed; no further automatic action is admissible"
)
- if self._system_error_reports or self._latest_device_fault:
+ if self._blocking_system_error or self._latest_device_fault:
state = self._latest_system_error_state or self._latest_device_session_state
raise ApplicationControlDeviceFault(
f"K1 reported a control fault state: {state or 'unknown'}"
@@ -1288,6 +1333,10 @@ class ReviewedApplicationMqttTransport:
raise ApplicationControlProofStale(
"K1 control proof expired without fresh MQTT evidence"
)
+ # Bind display telemetry to the proven DeviceInfo identity. Subsequent
+ # reports need not be promoted to command authority just to display
+ # their storage value; each still has to match this exact identity.
+ self._validated_status_identity = (binding.vendor_device_id, binding.device_serial)
def _mark_control_proof_locked(
self,
@@ -1496,14 +1545,24 @@ class ReviewedApplicationMqttTransport:
ambiguous_reason_code = "retained_application_response"
break
try:
- observed = decode_application_message_identity(payload)
- except ApplicationBootstrapError:
+ observed = (management_identity(payload) if topic == PROJECT_RESPONSE
+ else decode_application_message_identity(payload))
+ except (ApplicationBootstrapError, ValueError):
self._poison_locked("response identity decoding failed")
ambiguous_message = "control response identity could not be decoded safely"
ambiguous_reason_code = "response_identity_decode_failed"
break
observed_modeling_action: ModelingAction | None = None
+ observed_management_action: int | None = None
observed_result_code: int | None = None
+ if topic in {CONTROL_RESPONSE, PROJECT_RESPONSE}:
+ try:
+ observed_management_action = management_action(payload)
+ except ValueError:
+ self._poison_locked("management response action decoding failed")
+ ambiguous_message = "control management response has no exact action"
+ ambiguous_reason_code = "management_response_decode_failed"
+ break
if topic == MODELING_RESPONSE_TOPIC:
try:
modeling_response = decode_modeling_response(payload)
@@ -1523,6 +1582,7 @@ class ReviewedApplicationMqttTransport:
if self._known_response_expectations[operation_key].matches(
observed,
observed_modeling_action,
+ observed_management_action,
)
]
next_unobserved = next(
@@ -1604,7 +1664,8 @@ class ReviewedApplicationMqttTransport:
if response_topic is None:
raise ValueError("control request has no reviewed response topic")
try:
- identity = decode_application_message_identity(envelope.payload)
+ identity = (management_identity(envelope.payload) if envelope.topic == PROJECT_REQUEST
+ else decode_application_message_identity(envelope.payload))
except ApplicationBootstrapError as exc:
raise ValueError("control request identity is not decodable") from exc
modeling_action: ModelingAction | None = None
@@ -1620,6 +1681,8 @@ class ReviewedApplicationMqttTransport:
topic=response_topic,
identity=identity,
modeling_action=modeling_action,
+ management_action=(management_action(envelope.payload)
+ if envelope.topic in {CONTROL_REQUEST, PROJECT_REQUEST} else None),
)
@staticmethod
@@ -1671,6 +1734,14 @@ class ReviewedApplicationMqttTransport:
dispatch_admission_commit: Callable[[], None] | None,
) -> None:
observer = self._evidence_observer_snapshot()
+ if evidence.operation_key.startswith(("management:", "management-info:")):
+ # The physical START/STOP coordinator deliberately ignores these
+ # explicit idle-only operations. Own their final no-retry admission
+ # here, even when that observer is installed on the shared socket.
+ self._require_dispatch_deadline_open(dispatch_admission_deadline_reached)
+ if dispatch_admission_commit is not None:
+ dispatch_admission_commit()
+ return
if observer is not None:
observer.publish_dispatching(
evidence,
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/application_session.py b/src/k1link/device_plugins/xgrids_k1/protocol/application_session.py
index a6d21ad1..626609fe 100644
--- a/src/k1link/device_plugins/xgrids_k1/protocol/application_session.py
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/application_session.py
@@ -6,6 +6,7 @@ import threading
import time
from collections.abc import Callable, Mapping
from dataclasses import dataclass
+from functools import partial
from typing import Literal
from k1link.device_plugins.xgrids_k1.physical_command_coordinator import (
@@ -39,6 +40,10 @@ from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
from k1link.device_plugins.xgrids_k1.protocol.application_publish import (
OneShotPublishEnvelope,
)
+from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
+ MaintenanceJob,
+ ManagementMailbox,
+)
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import (
CommandHeaderIdentity,
ModelingAction,
@@ -126,7 +131,7 @@ class ApplicationConnectionBinding:
host_path_epoch: int
target_ipv4: str
target_port: int
- connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
+ connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
def __post_init__(self) -> None:
if not self.intent_id.strip():
@@ -264,6 +269,40 @@ class InteractiveApplicationControlSession:
# browser response cannot advance a later session that happens to be
# in the same named phase.
self._state_revision = 0
+ self._management = ManagementMailbox()
+
+ def manage_device(
+ self, *, operation: str, identifier: str, project_ids: tuple[str, ...],
+ expected_session_generation: int, expected_state_revision: int,
+ catalog_revision: str | None = None,
+ ) -> dict[str, object]:
+ job = MaintenanceJob(operation, identifier, project_ids, expected_session_generation,
+ expected_state_revision, time.monotonic() + 25, catalog_revision)
+ self._validate_management_job(job)
+ return self._management.submit(job)
+
+ def _validate_management_job(self, job: MaintenanceJob) -> None:
+ coordinator = self._physical_command_coordinator
+ if coordinator is not None:
+ physical = coordinator.snapshot()
+ if physical.get("recovery_requirement") or physical.get("requires_reconciliation"):
+ raise ValueError("Сначала подтвердите состояние предыдущей съёмки K1")
+ with self._lock:
+ self._require_checkpoint_locked(expected_session_generation=job.generation,
+ expected_state_revision=job.revision)
+ if (self._phase not in {"connection-ready", "completed"} or self._cancel_requested
+ or self._workspace_requested.is_set()
+ or self._active_recovery_requested.is_set()):
+ raise ValueError("Обслуживание доступно только после завершения съёмки K1")
+ if job.operation == "usb-storage" and (
+ self._connection_binding is None
+ or self._connection_binding.connection_mode != "bridge"
+ ):
+ raise ValueError(
+ "Режим носителя отключает USB-связь. Подключите K1 через Bridge "
+ "для переключения и возврата. Проекты доступны и без смены режима."
+ )
+ self._validate_connection_binding_snapshot("device-management-dispatch")
def open(
self,
@@ -389,6 +428,8 @@ class InteractiveApplicationControlSession:
return self.snapshot()
def _require_workspace_entry_locked(self) -> None:
+ if self._management.pending is not None or self._management.block_start:
+ raise ValueError("Завершите обслуживание K1 и подтвердите режим передачи данных")
if (self._phase == "completed" and self._transport is not None
and not self._cancel_requested):
return
@@ -968,6 +1009,9 @@ class InteractiveApplicationControlSession:
"workspace-entered",
self._workspace_requested.is_set,
reconciled_active_observed=self._active_recovery_requested.is_set,
+ standby_work=partial(self._management.pump,
+ transport, authority, binding, self._validate_management_job,
+ ),
)
if workspace is None:
self._validate_connection_binding("active-recovery-adoption")
@@ -1159,7 +1203,12 @@ class InteractiveApplicationControlSession:
self._scanning_observer_confirmed = self._scanning_observer is None
completed_acquisition = True
self._set_phase_locked("completed")
- executor.maintain_standby_until_next_acquisition(self._workspace_requested.is_set)
+ executor.maintain_standby_until_next_acquisition(
+ self._workspace_requested.is_set,
+ standby_work=partial(self._management.pump,
+ transport, authority, binding, self._validate_management_job,
+ ),
+ )
self._validate_connection_binding_snapshot("next-acquisition-preflight")
# Operation keys and response correlations are one-shot per MQTT
# dialogue. A new explicit scan gets a fresh socket, never reset
@@ -1488,6 +1537,7 @@ class InteractiveApplicationControlSession:
},
)
finally:
+ self._management.cancel_queued()
final_dialogue_snapshot: dict[str, object] | None = None
final_transport_snapshot: dict[str, object] | None = None
if executor is not None:
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/device_management.py b/src/k1link/device_plugins/xgrids_k1/protocol/device_management.py
new file mode 100644
index 00000000..5c4f86d4
--- /dev/null
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/device_management.py
@@ -0,0 +1,177 @@
+"""Bounded vendor device/storage messages; no SDK client or new authentication.
+
+Wire reference: XGRIDS Lixel_OpenAPI aiot_msgs.proto at
+a60a73773b0c2da3e582607ff71b32baa1238d4e. Execution belongs to the existing
+interactive control worker, exclusively at its confirmed standby checkpoint.
+"""
+from __future__ import annotations
+
+import hashlib
+from enum import IntEnum
+
+from .application_bootstrap import (
+ ApplicationControlAuthority,
+ ApplicationMessageIdentity,
+ ApplicationRequestHeader,
+ LiveDeviceControlBinding,
+ _bytes_field,
+ _encode_header,
+ _text_field,
+ _varint_field,
+ decode_application_message_identity,
+)
+from .application_publish import OneShotPublishEnvelope
+from .modeling_control import OPENAPI_SUCCESS
+from .protobuf_wire import ProtoField, iter_fields
+
+PROJECT_REQUEST = "lixel/application/request/project_list"
+PROJECT_RESPONSE = "lixel/application/response/project_list"
+CONTROL_REQUEST = "lixel/application/request/device_control"
+CONTROL_RESPONSE = "lixel/application/response/device_control"
+MAX_PROJECT_RESPONSE_BYTES = 4 * 1024 * 1024
+MAX_PROJECTS = 4096
+
+
+class ManagementAction(IntEnum):
+ USB_MASS = 15
+ USB_ETHER = 16
+ DISK_FORMAT = 17
+ POWER_OFF = 20
+ SYSTEM_REBOOT = 22
+ LIST_PROJECTS = 23
+ DELETE_PROJECTS = 25
+
+
+OPERATIONS = {
+ "projects": ManagementAction.LIST_PROJECTS,
+ "delete-projects": ManagementAction.DELETE_PROJECTS,
+ "format-storage": ManagementAction.DISK_FORMAT,
+ "usb-storage": ManagementAction.USB_MASS,
+ "usb-data": ManagementAction.USB_ETHER,
+ "power-off": ManagementAction.POWER_OFF,
+ "reboot": ManagementAction.SYSTEM_REBOOT,
+}
+
+
+def management_envelope(
+ operation: str, operation_id: str, authority: ApplicationControlAuthority,
+ binding: LiveDeviceControlBinding, project_ids: tuple[str, ...] = (),
+) -> OneShotPublishEnvelope:
+ action = OPERATIONS[operation]
+ if len(project_ids) > MAX_PROJECTS or len(set(project_ids)) != len(project_ids):
+ raise ValueError("Invalid project selection")
+ if (action == ManagementAction.DELETE_PROJECTS) != bool(project_ids):
+ raise ValueError("Only project deletion accepts a nonempty project selection")
+ if any(not value or len(value.encode("utf-8")) > 256 for value in project_ids):
+ raise ValueError("Invalid project identifier")
+ project_request = action in {ManagementAction.LIST_PROJECTS, ManagementAction.DELETE_PROJECTS}
+ header = ApplicationRequestHeader(
+ "ProjectListRequest" if project_request else "DeviceControlRequest",
+ authority, binding, context=operation_id,
+ )
+ payload = _bytes_field(1, _encode_header(header)) + _varint_field(2, int(action))
+ payload += b"".join(_text_field(3 if len(project_ids) == 1 else 5, value)
+ for value in project_ids)
+ return OneShotPublishEnvelope(
+ operation_key=f"management:{operation_id}",
+ topic=PROJECT_REQUEST if project_request else CONTROL_REQUEST,
+ payload=payload, payload_sha256=hashlib.sha256(payload).hexdigest(),
+ payload_bytes=len(payload), qos=2, retain=False,
+ )
+
+
+def unique_fields(payload: bytes, *, maximum: int = 64) -> dict[int, ProtoField]:
+ result: dict[int, ProtoField] = {}
+ for item in iter_fields(payload, max_fields=maximum):
+ if item.number in result:
+ raise ValueError("Duplicate singular vendor field")
+ result[item.number] = item
+ return result
+
+
+def management_identity(payload: bytes) -> ApplicationMessageIdentity:
+ """Bound repeated project fields without widening ordinary control decoding."""
+ if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
+ raise ValueError("Project response exceeds the bounded catalog")
+ header = None
+ for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
+ if item.number == 1:
+ if header is not None or item.wire_type != 2 or not isinstance(item.value, bytes):
+ raise ValueError("Invalid project response header")
+ header = item.value
+ if header is None:
+ raise ValueError("Project response header is missing")
+ return decode_application_message_identity(_bytes_field(1, header))
+
+
+def uint(fields: dict[int, ProtoField], key: int, default: int | None = None) -> int:
+ value = fields.get(key)
+ if value is None and default is not None:
+ return default
+ if value is None or value.wire_type != 0 or not isinstance(value.value, int):
+ raise ValueError("Missing vendor integer")
+ return value.value
+
+
+def management_action(payload: bytes) -> int:
+ """Read the exact action without interpreting repeated project entries."""
+ actions = [item for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32)
+ if item.number == 2]
+ if len(actions) != 1:
+ raise ValueError("Missing or repeated management action")
+ return uint({2: actions[0]}, 2)
+
+
+def data(fields: dict[int, ProtoField], key: int) -> bytes:
+ value = fields.get(key)
+ if value is None or value.wire_type != 2 or not isinstance(value.value, bytes):
+ raise ValueError("Missing vendor message")
+ return value.value
+
+
+def decode_management_response(payload: bytes, operation: str) -> dict[str, object]:
+ if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
+ raise ValueError("Project response exceeds the bounded catalog")
+ fields: dict[int, ProtoField] = {}
+ projects: list[dict[str, object]] = []
+ seen: set[str] = set()
+ for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
+ if item.number == 4 and operation in {"projects", "delete-projects"}:
+ if not isinstance(item.value, bytes) or item.wire_type != 2:
+ raise ValueError("Invalid project entry")
+ project = unique_fields(item.value)
+ identifier = data(project, 1).decode("utf-8")
+ name = data(project, 2).decode("utf-8")
+ if (not identifier or len(identifier.encode()) > 256 or len(name.encode()) > 1024
+ or identifier in seen or len(projects) >= MAX_PROJECTS):
+ raise ValueError("Invalid or duplicate project identity")
+ seen.add(identifier)
+ # URLs, directory JSON and file paths never cross the product boundary.
+ projects.append({"id": identifier, "name": name})
+ else:
+ if item.number in fields:
+ raise ValueError("Duplicate management response field")
+ fields[item.number] = item
+ if uint(fields, 2) != int(OPERATIONS[operation]):
+ raise ValueError("Vendor response belongs to another command")
+ code = uint(unique_fields(data(fields, 15)), 1)
+ return {"status": "succeeded" if code == OPENAPI_SUCCESS else "rejected",
+ "result_code": code, **({"projects": projects} if operation == "projects" else {})}
+
+
+def decode_storage_mode(payload: bytes) -> dict[str, object]:
+ """DeviceInfo owns observed mode; an accepted mode command is not evidence."""
+ top = unique_fields(payload)
+ if uint(unique_fields(data(top, 15)), 1) != OPENAPI_SUCCESS:
+ raise ValueError("DeviceInfo rejected")
+ device = unique_fields(data(top, 2))
+ working = unique_fields(data(device, 7))
+ mass = uint(working, 4, 0)
+ if mass not in {0, 1}:
+ raise ValueError("Invalid USB mode")
+ storage = unique_fields(data(device, 10)) if 10 in device else {}
+ storage_code = uint(storage, 1, 0)
+ storage_type = (storage_code >> 1) ^ -(storage_code & 1)
+ return {"usb_mode": "storage" if mass else "data",
+ "storage_type": {0: "internal", 1: "microSD", 2: "external-usb"}.get(
+ storage_type, "unknown") if 10 in device else "unknown"}
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/management_mailbox.py b/src/k1link/device_plugins/xgrids_k1/protocol/management_mailbox.py
new file mode 100644
index 00000000..1e303172
--- /dev/null
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/management_mailbox.py
@@ -0,0 +1,171 @@
+"""Explicit maintenance work on the existing control worker, never a second client."""
+from __future__ import annotations
+
+import hashlib
+import json
+import threading
+import time
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, cast
+
+from .application_bootstrap import (
+ DEVICE_INFO_REQUEST_TOPIC,
+ ApplicationControlAuthority,
+ ApplicationRequestHeader,
+ LiveDeviceControlBinding,
+ _bytes_field,
+ _encode_header,
+)
+from .application_publish import OneShotPublishEnvelope
+from .device_management import decode_management_response, decode_storage_mode, management_envelope
+
+if TYPE_CHECKING:
+ from .application_mqtt import ReviewedApplicationMqttTransport
+
+
+@dataclass
+class MaintenanceJob:
+ operation: str
+ identifier: str
+ project_ids: tuple[str, ...]
+ generation: int
+ revision: int
+ deadline: float
+ catalog_revision: str | None = None
+ finished: threading.Event = field(default_factory=threading.Event)
+ result: dict[str, Any] | None = None
+
+
+class ManagementMailbox:
+ def __init__(self) -> None:
+ self.lock = threading.Lock()
+ self.pending: MaintenanceJob | None = None
+ self.block_start = False
+ self.mode: dict[str, object] = {}
+ self.generation = -1
+ self.catalog_revision: str | None = None
+ self.project_ids: set[str] = set()
+
+ def submit(self, job: MaintenanceJob) -> dict[str, Any]:
+ with self.lock:
+ if self.pending is not None:
+ raise ValueError("Другая операция K1 ещё выполняется")
+ self.pending = job
+ if not job.finished.wait(max(0.0, job.deadline - time.monotonic()) + 1):
+ # An expired queued job can never be published later. A dispatch
+ # already on the wire stays unknown and is never retried here.
+ return {"status": "unknown", "message": "K1 не подтвердил результат операции"}
+ return job.result or {"status": "unknown"}
+
+ def cancel_queued(self) -> None:
+ """Called by the sole worker only after any in-flight pump has ended."""
+ with self.lock:
+ job, self.pending = self.pending, None
+ if job is not None:
+ job.result = {"status": "blocked", "message": "Управляющее соединение K1 закрыто"}
+ job.finished.set()
+
+ def pump(
+ self, transport: ReviewedApplicationMqttTransport,
+ authority: ApplicationControlAuthority, binding: LiveDeviceControlBinding,
+ validate: Callable[[MaintenanceJob], None],
+ ) -> None:
+ with self.lock:
+ job = self.pending
+ if job is None:
+ return
+ dispatched = False
+ deleted: list[str] = []
+ try:
+ validate(job)
+ if time.monotonic() >= job.deadline:
+ raise ValueError("Время ожидания операции истекло до отправки")
+ if not transport.standby_complete(binding):
+ raise ValueError("K1 не подтвердил завершение съёмки. Остановите запись")
+ if job.operation == "delete-projects" and (
+ job.generation != self.generation or not self.catalog_revision
+ or job.catalog_revision != self.catalog_revision
+ or not set(job.project_ids) <= self.project_ids
+ ):
+ raise ValueError("Список проектов изменился. Обновите его перед удалением")
+
+ def expired() -> bool:
+ validate(job)
+ return time.monotonic() >= job.deadline
+
+ def mark_dispatched() -> None:
+ nonlocal dispatched
+ dispatched = True
+
+ def exchange(envelope: OneShotPublishEnvelope) -> bytes:
+ return transport.exchange_batch_once(
+ (envelope,), required_response_operation_keys=(envelope.operation_key,),
+ dispatch_admission_deadline_reached=expired,
+ dispatch_admission_commit=mark_dispatched,
+ )[envelope.operation_key]
+
+ result: dict[str, Any]
+ if job.operation == "info":
+ result = {"status": "succeeded"}
+ else:
+ if job.operation in {"delete-projects", "format-storage"}:
+ self.catalog_revision = None
+ # The qualified K1 firmware accepts the singular project ID but
+ # rejects the newer repeated-ID request. Keep group selection in
+ # this same fenced worker and await each ordinary vendor reply.
+ selections = [(value,) for value in job.project_ids] if (
+ job.operation == "delete-projects"
+ ) else [job.project_ids]
+ for index, selection in enumerate(selections):
+ envelope = management_envelope(
+ job.operation, f"{job.identifier}-{index}", authority, binding, selection,
+ )
+ result = decode_management_response(exchange(envelope), job.operation)
+ if result["status"] != "succeeded":
+ if job.operation == "delete-projects":
+ result["message"] = (
+ f"Удалено {len(deleted)} из {len(job.project_ids)}. "
+ "K1 отклонил следующее удаление. Обновите список проектов."
+ )
+ break
+ if job.operation == "delete-projects":
+ deleted.extend(selection)
+ if job.operation == "delete-projects":
+ result["deleted_project_ids"] = deleted
+ if result["status"] == "succeeded" and job.operation == "projects":
+ projects = cast(list[dict[str, str]], result["projects"])
+ self.project_ids = {item["id"] for item in projects}
+ self.catalog_revision = hashlib.sha256(
+ json.dumps([job.generation, result["projects"]], sort_keys=True).encode()
+ ).hexdigest()
+ result["catalog_revision"] = self.catalog_revision
+ if result["status"] == "succeeded" and job.operation not in {"power-off", "reboot"}:
+ header = ApplicationRequestHeader("DeviceInfoRequest", authority, binding,
+ context=job.identifier + "-info")
+ payload = _bytes_field(1, _encode_header(header))
+ envelope = OneShotPublishEnvelope(
+ "management-info:" + job.identifier, DEVICE_INFO_REQUEST_TOPIC,
+ payload, hashlib.sha256(payload).hexdigest(), len(payload), 2, False,
+ )
+ mode = decode_storage_mode(exchange(envelope))
+ self.mode, self.generation = mode, job.generation
+ self.block_start = mode["usb_mode"] == "storage"
+ result.update(mode)
+ elif result["status"] == "succeeded":
+ self.block_start = True
+ job.result = result
+ except Exception as exc:
+ if dispatched and job.operation not in {"info", "projects"}:
+ self.block_start = True
+ # A lost reply is not a rejected command. Never retry a write.
+ job.result = {
+ "status": "unknown" if dispatched else "blocked",
+ "message": ("K1 не подтвердил результат. Проверьте состояние устройства."
+ if dispatched else str(exc)),
+ **({"deleted_project_ids": deleted} if job.operation == "delete-projects" else {}),
+ }
+ finally:
+ with self.lock:
+ self.pending = None
+ job.finished.set()
diff --git a/src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py b/src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py
index 9d848fb1..976c7c1e 100644
--- a/src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py
+++ b/src/k1link/device_plugins/xgrids_k1/protocol/modeling_control.py
@@ -188,8 +188,8 @@ class DeviceStatusReport:
"""Recovered acquisition subset of ``DeviceStatusReport``.
Vendor identity and project strings are intentionally redacted from repr.
- Nested system/RTK messages are bounded by the outer parser but are not
- interpreted by this modeling state machine.
+ Storage occupancy is optional display telemetry; nested system/RTK messages
+ never decide this modeling state machine.
"""
header: ObservedHeader | None = field(repr=False)
@@ -201,6 +201,7 @@ class DeviceStatusReport:
init_ready: bool
system_status_present: bool
rtk_status_present: bool
+ storage_used_percent: float | None = None
@dataclass(frozen=True, slots=True)
@@ -338,6 +339,7 @@ def decode_device_status_report(
init_ready = False
system_status_present = False
rtk_status_present = False
+ storage_used_percent = None
seen: set[int] = set()
try:
for proto_field in iter_fields(payload, max_fields=64):
@@ -366,7 +368,8 @@ def decode_device_status_report(
init_ready = bool(raw_ready)
elif proto_field.number == 7:
_mark_once(seen, 7, "device_status.system_status")
- _bytes_value(proto_field, "device_status.system_status")
+ system = _bytes_value(proto_field, "device_status.system_status")
+ storage_used_percent = _storage_used_percent(system)
system_status_present = True
elif proto_field.number == 8:
_mark_once(seen, 8, "device_status.rtk_status")
@@ -387,9 +390,32 @@ def decode_device_status_report(
init_ready=init_ready,
system_status_present=system_status_present,
rtk_status_present=rtk_status_present,
+ storage_used_percent=storage_used_percent,
)
+def _storage_used_percent(payload: bytes) -> float | None:
+ """Optional display telemetry from reviewed SystemStatus fields 4/5.
+
+ Units are not inferred; only the dimensionless ratio is exposed. Invalid
+ auxiliary telemetry must not change the existing acquisition state machine.
+ Proto3 may omit DiskUsed when it is zero.
+ """
+ values: dict[int, int] = {}
+ try:
+ for field in iter_fields(payload, max_fields=64):
+ if field.number in {4, 5}:
+ if field.number in values:
+ return None
+ values[field.number] = _uint_value(
+ field, "system_status.storage", max_value=(1 << 63) - 1
+ )
+ except ValueError:
+ return None
+ total, used = values.get(4, 0), values.get(5, 0)
+ return 100.0 * used / total if total > 0 and used <= total else None
+
+
def session_state_from_code(code: int) -> SessionState | None:
"""Map the captured base-offset status code, preserving unknown values."""
diff --git a/src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py b/src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py
index b24d2504..ef731157 100644
--- a/src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py
+++ b/src/k1link/device_plugins/xgrids_k1/semantic_topology_store.py
@@ -23,12 +23,12 @@ SEMANTIC_TOPOLOGY_LOCK_FILENAME = ".semantic-topology.lock"
SEMANTIC_TOPOLOGY_MAX_BYTES = 16 * 1024
SEMANTIC_TOPOLOGY_MAX_REVISION = (1 << 63) - 1
-TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
-TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status"]
+TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
+TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"]
SemanticTopologyStoreStatus = Literal["empty", "available", "corrupt"]
-_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
-_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status"})
+_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
+_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status", "usb-enumeration"})
_SAFE_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:+-]{0,159}$")
_SAFE_FIRMWARE_VERSION = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+() -]{0,63}$")
diff --git a/src/k1link/device_plugins/xgrids_k1/usb_network.py b/src/k1link/device_plugins/xgrids_k1/usb_network.py
new file mode 100644
index 00000000..683bbbdb
--- /dev/null
+++ b/src/k1link/device_plugins/xgrids_k1/usb_network.py
@@ -0,0 +1,121 @@
+"""Read-only Linux USB Ethernet discovery for the physically qualified K1.
+
+Addresses come from the device's DHCP lease, never from a product default.
+Enumeration is only a candidate: the existing DeviceInfo/identity admission
+must still succeed before any acquisition command can be sent.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import ipaddress
+import json
+import re
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Protocol
+
+from .linux_host import _run, nm_fields
+
+
+class NetworkObservationRunner(Protocol):
+ def __call__(self, args: list[str], *, timeout: float) -> str: ...
+
+
+@dataclass(frozen=True, slots=True)
+class UsbNetworkAttachment:
+ transport_ref: str
+ interface: str
+ peer_ipv4: str
+ source_ipv4: str
+ generation: str
+ speed: str
+
+
+class LinuxK1UsbProbe:
+ """Observe an already enumerated RNDIS interface; never configure the OS."""
+
+ def __init__(
+ self, sys_net: Path = Path("/sys/class/net"),
+ runner: NetworkObservationRunner | None = None,
+ ) -> None:
+ self.sys_net = sys_net
+ self.run = runner or _run
+
+ def discover(self) -> tuple[UsbNetworkAttachment, ...]:
+ found = []
+ for interface in sorted(self.sys_net.iterdir()):
+ if not re.fullmatch(r"[A-Za-z0-9_.:-]{1,64}", interface.name):
+ continue
+ try:
+ attachment = self._read(interface)
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
+ continue
+ if attachment is not None:
+ found.append(attachment)
+ # Same serial or same peer on multiple links is not an exact route.
+ # Supporting those devices requires explicit routing isolation first.
+ return tuple(
+ item for item in found
+ if sum(other.transport_ref == item.transport_ref for other in found) == 1
+ and sum(other.peer_ipv4 == item.peer_ipv4 for other in found) == 1
+ )
+
+ def require(self, transport_ref: str) -> UsbNetworkAttachment:
+ matches = [item for item in self.discover() if item.transport_ref == transport_ref]
+ if len(matches) != 1:
+ raise OSError("USB K1 не найден. Проверьте питание и USB-кабель.")
+ return matches[0]
+
+ def _read(self, interface: Path) -> UsbNetworkAttachment | None:
+ device = (interface / "device").resolve(strict=True)
+ usb = next((parent for parent in (device, *device.parents)
+ if (parent / "idVendor").is_file()), None)
+ if usb is None or (usb / "idVendor").read_text().strip().lower() != "2207":
+ return None
+ if (usb / "idProduct").read_text().strip().lower() != "0019":
+ return None
+ if (usb / "product").read_text().strip() != "XGRIDS Device":
+ return None
+ if (device / "driver").resolve(strict=True).name != "rndis_host":
+ return None
+ serial = (usb / "serial").read_text().strip()
+ if not serial or len(serial) > 128 or (interface / "carrier").read_text().strip() != "1":
+ return None
+ options = self.run([
+ "nmcli", "-t", "--escape", "yes", "-f", "DHCP4.OPTION",
+ "device", "show", interface.name,
+ ], timeout=2)
+ peers = set()
+ for line in options.splitlines():
+ fields = nm_fields(line)
+ if len(fields) != 2:
+ continue
+ key, separator, value = fields[1].partition(" = ")
+ if separator and key.strip() == "dhcp_server_identifier":
+ peer = ipaddress.IPv4Address(value.strip())
+ if peer.is_private and not (peer.is_loopback or peer.is_link_local
+ or peer.is_multicast or peer.is_unspecified):
+ peers.add(str(peer))
+ if len(peers) != 1:
+ return None
+ peer_ipv4 = peers.pop()
+ routes = json.loads(self.run(["ip", "-j", "route", "get", peer_ipv4], timeout=2))
+ if not isinstance(routes, list) or len(routes) != 1:
+ return None
+ route = routes[0]
+ if (route.get("dev") != interface.name or route.get("gateway")
+ or route.get("type", "unicast") != "unicast"):
+ return None
+ source = str(ipaddress.IPv4Address(route["prefsrc"]))
+ generation = hashlib.sha256(json.dumps([
+ serial, str(usb), (usb / "busnum").read_text().strip(),
+ (usb / "devnum").read_text().strip(), (interface / "ifindex").read_text().strip(),
+ usb.stat().st_ino, source, peer_ipv4,
+ ]).encode()).hexdigest()
+ return UsbNetworkAttachment(
+ transport_ref="usb:" + hashlib.sha256(serial.encode()).hexdigest(),
+ interface=interface.name, peer_ipv4=peer_ipv4, source_ipv4=source,
+ generation=generation, speed=(usb / "speed").read_text().strip(),
+ )
diff --git a/src/k1link/fleet/device_enrollment.py b/src/k1link/fleet/device_enrollment.py
index f32c970b..8d66a8e7 100644
--- a/src/k1link/fleet/device_enrollment.py
+++ b/src/k1link/fleet/device_enrollment.py
@@ -13,7 +13,7 @@ from datetime import UTC, datetime
from .trust import PairingError
-ACTIONS = {"scan", "networks", "connect", "verify"}
+ACTIONS = {"scan", "networks", "connect", "verify", "reset"}
def validate(value):
@@ -45,10 +45,16 @@ def validate(value):
expected = {"device_id", "discovery_generation", "mode_revision"}
if value["action"] == "connect":
expected |= {"ssid", "password"}
+ elif value["action"] == "reset":
+ expected = {"mode_revision"}
elif value["action"] in {"scan", "networks"}:
expected = set()
if not isinstance(parameters, dict) or set(parameters) != expected:
raise PairingError("Неверные параметры подключения.")
+ if value["action"] == "reset" and (
+ type(parameters["mode_revision"]) is not int or parameters["mode_revision"] < 0
+ ):
+ raise PairingError("Обновите состояние подключения.")
if "device_id" in expected and (
not isinstance(parameters["device_id"], str)
or not 1 <= len(parameters["device_id"]) <= 128
diff --git a/src/k1link/fleet/sensors.py b/src/k1link/fleet/sensors.py
index f6b3d8f9..5db36653 100644
--- a/src/k1link/fleet/sensors.py
+++ b/src/k1link/fleet/sensors.py
@@ -15,6 +15,7 @@ ACTIONS = {
"details",
"rename",
"verify",
+ "management",
"start",
"replay",
"stop",
diff --git a/src/k1link/viewer/node_camera.py b/src/k1link/viewer/node_camera.py
new file mode 100644
index 00000000..aa8b9252
--- /dev/null
+++ b/src/k1link/viewer/node_camera.py
@@ -0,0 +1,242 @@
+"""Adaptive disposable camera preview from the acquisition's existing MP4 lease.
+
+The archive and RTSP producer remain owned by acquisition. Only decoded latest
+frames cross the preview budget; network stalls cannot queue encoded capture.
+"""
+
+import asyncio
+import io
+import logging
+import queue
+import threading
+import time
+from fractions import Fraction
+from uuid import uuid4
+
+import av
+from aiortc import (
+ RTCConfiguration,
+ RTCPeerConnection,
+ RTCRtpSender,
+ RTCSessionDescription,
+ VideoStreamTrack,
+)
+from aiortc.mediastreams import MediaStreamError
+from missioncore_plugin_sdk.link_budget import budget_peer
+from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
+
+logger = logging.getLogger(__name__)
+
+
+def open_live_camera(reader):
+ # The MP4 initialization already declares the codec. Bound stream analysis
+ # so avformat does not wait for seconds of future live samples.
+ return av.open(reader, format="mp4", mode="r",
+ options={"probesize": "32", "analyzeduration": "1"})
+
+
+class LeaseReader(io.RawIOBase):
+ def __init__(self, lease, stopped):
+ self.lease, self.stopped, self.pending = lease, stopped, b""
+ self.ended = False
+
+ def readable(self):
+ return True
+
+ def read(self, size=-1):
+ if self.ended:
+ return b""
+ if size < 0:
+ size = 32768
+ # A pipe read may be short. Waiting to fill FFmpeg's requested buffer
+ # holds a complete live fragment until future frames arrive.
+ while len(self.pending) < size and not self.stopped.is_set():
+ try:
+ segment = self.lease.segments.get(timeout=0 if self.pending else 0.25)
+ except queue.Empty:
+ if self.pending:
+ break
+ continue
+ if segment is None:
+ self.ended = True
+ break
+ self.pending += segment[1]
+ result, self.pending = self.pending[:size], self.pending[size:]
+ return result
+
+
+class CameraSource:
+ def __init__(self, camera):
+ self.camera = camera
+ self.closed = threading.Event()
+ self.lock = threading.Lock()
+ self.frame = None
+ self.sequence = 0
+ self.observed = 0.0
+ self.started = time.monotonic()
+ self.thread = threading.Thread(target=self.pump, name="k1-camera-preview", daemon=True)
+ self.thread.start()
+
+ def current(self):
+ with self.lock:
+ return self.sequence, self.frame, self.observed
+
+ def pump(self):
+ while not self.closed.is_set():
+ lease = None
+ try:
+ state = self.camera.snapshot()
+ recording = state.get("recording") or {}
+ if recording.get("source_end_expected"):
+ break
+ if not (
+ recording.get("active")
+ and recording.get("producer_alive")
+ and recording.get("media_ready")
+ and recording.get("active_epoch") == state.get("generation")
+ ):
+ self.closed.wait(0.25)
+ continue
+ lease = self.camera.open_delivery(state["generation"], require_recording=True)
+ with open_live_camera(LeaseReader(lease, self.closed)) as container:
+ stream = container.streams.video[0]
+ stream.codec_context.thread_count = 1
+ for packet in container.demux(stream):
+ if self.closed.is_set():
+ break
+ try:
+ frames = packet.decode()
+ except av.error.InvalidDataError:
+ continue # A late observer awaits the next capture keyframe.
+ for frame in frames:
+ now = time.monotonic()
+ if not (0 < frame.width <= 4096 and 0 < frame.height <= 2160):
+ raise ValueError("Camera preview dimensions exceed bound")
+ if now - self.observed < 1 / 15:
+ continue
+ width = min(1280, frame.width) // 2 * 2
+ height = max(2, round(frame.height * width / frame.width) // 2 * 2)
+ frame = frame.reformat(width=width, height=height, format="yuv420p")
+ frame.pts, frame.time_base = (
+ round((now - self.started) * 90000),
+ Fraction(1, 90000),
+ )
+ with self.lock:
+ self.sequence += 1
+ self.frame, self.observed = frame, now
+ self.camera.mark_streaming(lease)
+ except (OSError, ValueError, RuntimeError, IndexError) as error:
+ logger.debug("K1 camera observer awaiting producer (%s)", type(error).__name__)
+ finally:
+ if lease is not None:
+ self.camera.release_delivery(lease, client_closed=True)
+ self.closed.wait(0.25)
+ self.closed.set()
+ with self.lock:
+ self.frame = None
+
+ def close(self):
+ self.closed.set()
+
+
+class CameraTrack(VideoStreamTrack):
+ def __init__(self, source, budget):
+ super().__init__()
+ self.source, self.budget, self.sequence, self.next_at = source, budget, 0, 0.0
+
+ async def recv(self):
+ while self.readyState == "live" and not self.source.closed.is_set():
+ await asyncio.sleep(max(0, self.next_at - time.monotonic()))
+ width, fps = self.budget.video()
+ sequence, frame, observed = self.source.current()
+ if (
+ fps
+ and frame is not None
+ and sequence > self.sequence
+ and time.monotonic() - observed < 2
+ ):
+ self.sequence, self.next_at = sequence, time.monotonic() + 1 / fps
+ width = min(frame.width, width)
+ height = max(2, round(frame.height * width / frame.width) // 2 * 2)
+ resized = frame.reformat(width=width, height=height, format="yuv420p")
+ # Encoder keyframe requests must not mutate a shared source frame.
+ result = av.VideoFrame.from_ndarray(
+ resized.to_ndarray(format="yuv420p"), format="yuv420p"
+ )
+ result.pts, result.time_base = frame.pts, frame.time_base
+ return result
+ await asyncio.sleep(0.025)
+ raise MediaStreamError
+
+
+async def camera_offer(peers, parameters):
+ from .node_media import admit_sdp
+
+ admit_sdp(parameters.get("sdp"), camera=True)
+ if sum(entry.get("media") == "camera" for entry in peers.items.values()) >= 2:
+ raise ValueError("Close another camera viewer")
+ pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
+ identifier = "peer_" + uuid4().hex
+ entry = {
+ "pc": pc,
+ "seen": time.monotonic(),
+ "tasks": [],
+ "media": "camera",
+ "view_id": parameters.get("view_id"),
+ }
+ peers.items[identifier] = entry
+ source = getattr(peers, "camera_source", None)
+ if source is None or source.closed.is_set():
+ source = peers.camera_source = CameraSource(peers.camera)
+ entry["source"] = source
+
+ @pc.on("datachannel")
+ def channel_open(channel):
+ if channel.label != "sensor":
+ channel.close()
+ return
+
+ @channel.on("message")
+ def message(value):
+ if value == "keepalive":
+ entry["seen"] = time.monotonic()
+
+ @pc.on("connectionstatechange")
+ async def changed():
+ if pc.connectionState in {"closed", "failed"}:
+ await peers.close(identifier)
+
+ async def watchdog():
+ while identifier in peers.items:
+ if source.closed.is_set() or time.monotonic() - entry["seen"] > 30:
+ await peers.close(identifier)
+ return
+ await asyncio.sleep(1)
+
+ try:
+ budget = await adapt_peer(pc, "video")
+ entry["budget"] = budget
+ track = CameraTrack(source, budget)
+ entry["track"] = track
+ sender = pc.addTrack(track)
+ cap_video_sender(sender, budget)
+ pc.getTransceivers()[0].setCodecPreferences(
+ [
+ codec
+ for codec in RTCRtpSender.getCapabilities("video").codecs
+ if codec.mimeType.lower() in {"video/h264", "video/rtx"}
+ ]
+ )
+ await pc.setRemoteDescription(RTCSessionDescription(sdp=parameters["sdp"], type="offer"))
+ budget_peer(pc, "video", producer_id=budget.id)
+ await pc.setLocalDescription(await pc.createAnswer())
+ entry["tasks"].append(asyncio.create_task(watchdog()))
+ return {
+ "peer_id": identifier,
+ "sdp": pc.localDescription.sdp,
+ "type": "answer",
+ "transport": "webrtc-video",
+ }
+ except BaseException:
+ await peers.close(identifier)
+ raise
diff --git a/tests/fleet/test_device_enrollment.py b/tests/fleet/test_device_enrollment.py
index 38e536e2..a96cad40 100644
--- a/tests/fleet/test_device_enrollment.py
+++ b/tests/fleet/test_device_enrollment.py
@@ -109,3 +109,19 @@ def test_duplicate_id_cannot_replace_original_secret():
duplicate["parameters"]["password"] += "changed"
bus.submit(fleet, "vehicle", duplicate)
assert bus.pending[("vehicle", request["operation_id"])]["payload"] == request
+
+
+def test_reset_accepts_only_a_mode_revision_without_credentials_or_physical_action():
+ value = command()
+ value.update(action="reset", parameters={"mode_revision": 7})
+ validate(value)
+ for parameters in (
+ {},
+ {"mode_revision": True},
+ {"mode_revision": -1},
+ {"mode_revision": "7"},
+ {"mode_revision": 7, "device_id": "x"},
+ {"mode_revision": 7, "password": "synthetic"},
+ ):
+ with pytest.raises(PairingError):
+ validate({**value, "parameters": parameters})
diff --git a/tests/fleet/test_sensor_queue.py b/tests/fleet/test_sensor_queue.py
index 5c9e4624..504ed9a5 100644
--- a/tests/fleet/test_sensor_queue.py
+++ b/tests/fleet/test_sensor_queue.py
@@ -49,6 +49,21 @@ def test_pending_commands_still_have_the_original_32_slot_limit():
sensors.submit(fleet, "vehicle", request())
+def test_k1_management_uses_existing_queue_and_deduplicates_dispatch():
+ fleet = Fleet()
+ value = {**request(), "action_id": "management", "parameters": {
+ "operation": "projects", "control_generation": 3, "control_revision": 7,
+ }}
+ receipt = sensors.submit(fleet, "vehicle", value)
+ assert sensors.submit(fleet, "vehicle", value) is receipt
+ assert sensors.heartbeat(fleet.row, {})["sensor_commands"] == [value]
+ result = sensors.heartbeat(fleet.row, {"sensor_results": [{
+ "command": value, "state": "complete", "result": {"status": "succeeded", "projects": []},
+ }]})
+ assert result["sensor_commands"] == []
+ assert result["sensor_acknowledgements"] == [value["operation_id"]]
+
+
def test_receipt_storage_is_bounded_and_only_expired_terminal_receipts_are_reclaimable():
fleet = Fleet()
for _ in range(sensors.MAX_COMMAND_RECEIPTS):
diff --git a/tests/test_k1_connection_read_model.py b/tests/test_k1_connection_read_model.py
index c93c2b9d..88696dbf 100644
--- a/tests/test_k1_connection_read_model.py
+++ b/tests/test_k1_connection_read_model.py
@@ -97,7 +97,7 @@ def test_lost_invocation_is_observed_once_and_never_resubmitted(journaled):
if journaled:
current["operations"] = [
{
- "operation_id": identifier,
+ "operation_id": parameters["operation_id"],
"status": "failed",
"error": {"code": "k1-wifi-network-not-found"},
}
@@ -161,6 +161,7 @@ def test_delivery_distinguishes_pre_dispatch_rejection_from_lost_result():
result = await bridge.deliver(request)
assert result["command_result"] == {
"operation_id": request["operation_id"],
+ "action": "connect",
"status": "rejected",
"error_code": "runtime-changed",
}
diff --git a/tests/test_k1_device_management.py b/tests/test_k1_device_management.py
new file mode 100644
index 00000000..79e57802
--- /dev/null
+++ b/tests/test_k1_device_management.py
@@ -0,0 +1,243 @@
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+
+import pytest
+from test_xgrids_application_mqtt import FakeControlClient, _binding
+
+from k1link.device_plugins.xgrids_k1.device_management import DeviceManagementRequest
+from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
+ ApplicationControlAuthority,
+)
+from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
+ _bytes_field as blob,
+)
+from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
+ _text_field as text,
+)
+from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
+ _varint_field as uint,
+)
+from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
+ ApplicationCommandOutcomeUnknown,
+ ReviewedApplicationMqttTransport,
+)
+from k1link.device_plugins.xgrids_k1.protocol.application_session import (
+ ApplicationConnectionBinding,
+ InteractiveApplicationControlSession,
+)
+from k1link.device_plugins.xgrids_k1.protocol.device_management import (
+ CONTROL_RESPONSE,
+ PROJECT_RESPONSE,
+ decode_management_response,
+ decode_storage_mode,
+ management_action,
+ management_envelope,
+ management_identity,
+)
+from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
+ MaintenanceJob,
+ ManagementMailbox,
+)
+from k1link.device_plugins.xgrids_k1.protocol.modeling_control import OPENAPI_SUCCESS
+from k1link.device_plugins.xgrids_k1.protocol.protobuf_wire import iter_fields
+
+
+def envelope(operation="projects", ids=()):
+ return management_envelope(operation, "synthetic-op", ApplicationControlAuthority(
+ openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), ids)
+
+
+def response(operation="projects", projects=()):
+ request = envelope(operation, ("synthetic",) if operation == "delete-projects" else ())
+ header = next(item.value for item in iter_fields(request.payload) if item.number == 1)
+ return (blob(1, header) + uint(2, management_action(request.payload))
+ + b"".join(blob(4, text(1, ident) + text(2, name) + text(12, "private-url"))
+ for ident, name in projects)
+ + blob(15, uint(1, OPENAPI_SUCCESS)))
+
+
+def info(*, storage=False, storage_type=1):
+ return blob(2, blob(7, uint(4, int(storage))) + blob(10, uint(1, storage_type * 2))) \
+ + blob(15, uint(1, OPENAPI_SUCCESS))
+
+
+@pytest.mark.parametrize("operation,code", [
+ ("usb-storage", 15), ("usb-data", 16), ("format-storage", 17),
+ ("power-off", 20), ("reboot", 22), ("projects", 23), ("delete-projects", 25),
+])
+def test_vendor_actions_and_exact_single_or_batch_delete(operation, code):
+ request = envelope(operation, ("one",) if operation == "delete-projects" else ())
+ assert management_action(request.payload) == code
+ assert request.qos == 2 and not request.retain
+ if operation == "delete-projects":
+ assert [p.number for p in iter_fields(request.payload)] == [1, 2, 3]
+ assert [p.number for p in iter_fields(envelope(operation, ("one", "two")).payload)] \
+ == [1, 2, 5, 5]
+
+
+def test_large_catalog_retains_names_only_and_rejects_duplicate_ids():
+ raw = response(projects=[(str(i), f"Проект {i}") for i in range(100)])
+ assert management_identity(raw).session_id.endswith(":synthetic-op")
+ result = decode_management_response(raw, "projects")
+ assert len(result["projects"]) == 100
+ assert result["projects"][0] == {"id": "0", "name": "Проект 0"}
+ with pytest.raises(ValueError, match="duplicate"):
+ decode_management_response(response(projects=[("one", "A"), ("one", "B")]), "projects")
+
+
+def test_mode_is_observed_and_never_inferred_from_command():
+ assert decode_storage_mode(info(storage=True)) == {
+ "usb_mode": "storage", "storage_type": "microSD",
+ }
+ assert decode_storage_mode(info())["usb_mode"] == "data"
+ with pytest.raises(ValueError):
+ decode_storage_mode(response("usb-storage"))
+
+
+def test_mismatched_action_cannot_satisfy_same_session_response():
+ request = envelope("reboot")
+ fake = FakeControlClient(response_topic=CONTROL_RESPONSE)
+ transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
+ transport.open()
+ # Same identity, wrong action: neither UI success nor control proof.
+ fake.events.append(("message", (CONTROL_RESPONSE, response("power-off"))))
+ with pytest.raises(ApplicationCommandOutcomeUnknown):
+ transport.exchange_batch_once([request],
+ required_response_operation_keys={request.operation_key})
+ assert transport.snapshot().correlated_responses == 0
+
+
+def test_management_dispatch_commit_runs_with_physical_observer_noop():
+ fake = FakeControlClient(response_topic=PROJECT_RESPONSE)
+ transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
+ transport.install_evidence_observer(SimpleNamespace(
+ publish_dispatching=lambda *a, **kw: None, publish_result=lambda *a, **kw: None,
+ qos2_completed=lambda *a: None, application_response=lambda *a: None,
+ ))
+ transport.open()
+ commits = []
+ request = envelope()
+ transport.exchange_batch_once([request],
+ required_response_operation_keys={request.operation_key},
+ dispatch_admission_commit=lambda: commits.append(True))
+ transport.close()
+ assert commits == [True]
+
+
+class MailboxTransport:
+ def __init__(self, *, standby=True, lose_reply=False):
+ self.standby, self.lose_reply, self.sent = standby, lose_reply, []
+
+ def standby_complete(self, binding):
+ return self.standby
+
+ def exchange_batch_once(self, batch, **kwargs):
+ assert not kwargs["dispatch_admission_deadline_reached"]()
+ kwargs["dispatch_admission_commit"]()
+ self.sent.append(batch[0])
+ if self.lose_reply:
+ raise TimeoutError()
+ raw = info() if batch[0].operation_key.startswith("management-info:") else response()
+ return {batch[0].operation_key: raw}
+
+
+def pump(box, transport, operation="projects", *, stale=False, expired=False, ids=()):
+ job = MaintenanceJob(operation, "synthetic-op", ids, 1, 2,
+ time.monotonic() + (-1 if expired else 5))
+ box.pending = job
+ def validate(_job):
+ if stale:
+ raise ValueError("stale checkpoint")
+ box.pump(transport, ApplicationControlAuthority(
+ openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), validate)
+ assert job.finished.is_set() and box.pending is None
+ return job.result
+
+
+@pytest.mark.parametrize("reason", ["active", "stale", "expired", "unknown-catalog"])
+def test_no_hardware_publish_without_current_idle_admission(reason):
+ box, transport = ManagementMailbox(), MailboxTransport(standby=reason != "active")
+ result = pump(box, transport, "delete-projects" if reason == "unknown-catalog" else "projects",
+ stale=reason == "stale", expired=reason == "expired",
+ ids=("one",) if reason == "unknown-catalog" else ())
+ assert result["status"] == "blocked" and not transport.sent
+
+
+def test_lost_write_reply_is_unknown_blocks_start_and_is_not_retried():
+ box, transport = ManagementMailbox(), MailboxTransport(lose_reply=True)
+ result = pump(box, transport, "usb-storage")
+ assert result["status"] == "unknown" and box.block_start
+ box.pump(transport, None, None, lambda job: None)
+ assert len(transport.sent) == 1
+
+
+def test_closed_worker_cancels_queued_unpublished_job():
+ box = ManagementMailbox()
+ job = MaintenanceJob("projects", "synthetic-op", (), 1, 2, time.monotonic() + 5)
+ box.pending = job
+ box.cancel_queued()
+ assert box.pending is None and job.finished.is_set() and job.result["status"] == "blocked"
+
+
+@pytest.mark.parametrize("failure", [None, "reject-second", "lose-second"])
+def test_group_deletion_uses_confirmed_single_requests_and_stops_on_failure(failure):
+ class DeletingTransport(MailboxTransport):
+ def exchange_batch_once(self, batch, **kwargs):
+ assert not kwargs["dispatch_admission_deadline_reached"]()
+ kwargs["dispatch_admission_commit"]()
+ request = batch[0]
+ self.sent.append(request)
+ if request.operation_key.startswith("management-info:"):
+ return {request.operation_key: info()}
+ fields = list(iter_fields(request.payload))
+ assert [p.number for p in fields] == [1, 2, 3]
+ index = len(self.sent)
+ if failure == "lose-second" and index == 2:
+ raise TimeoutError()
+ code = 839122945 if failure == "reject-second" and index == 2 else OPENAPI_SUCCESS
+ raw = blob(1, fields[0].value) + uint(2, 25) + blob(15, uint(1, code))
+ return {request.operation_key: raw}
+
+ box, transport = ManagementMailbox(), DeletingTransport()
+ box.generation, box.catalog_revision, box.project_ids = 1, "catalog", {"one", "two", "three"}
+ job = MaintenanceJob("delete-projects", "batch", ("one", "two", "three"), 1, 2,
+ time.monotonic() + 5, catalog_revision="catalog")
+ box.pending = job
+ box.pump(transport, ApplicationControlAuthority(
+ openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), lambda _: None)
+ assert job.finished.is_set()
+ requests = [p for p in transport.sent if p.operation_key.startswith("management:")]
+ assert len({p.operation_key for p in requests}) == len(requests)
+ assert [next(f.value for f in iter_fields(p.payload) if f.number == 3) for p in requests] \
+ == ([b"one", b"two"] if failure else [b"one", b"two", b"three"])
+ assert job.result["deleted_project_ids"] == (["one"] if failure else ["one", "two", "three"])
+ expected = {None: "succeeded", "reject-second": "rejected", "lose-second": "unknown"}
+ assert job.result["status"] == expected[failure]
+ assert box.block_start is (failure == "lose-second")
+
+
+def test_destructive_request_requires_confirmation_and_no_arbitrary_parameters():
+ base = dict(operation_id="synthetic-op", expected_session_generation=1,
+ expected_state_revision=2, operation="format-storage")
+ with pytest.raises(ValueError):
+ DeviceManagementRequest(**base)
+ with pytest.raises(ValueError):
+ DeviceManagementRequest(**base, operator_confirmed=True, path="/arbitrary")
+
+
+def test_mass_storage_cannot_remove_its_only_control_path():
+ session = InteractiveApplicationControlSession(SimpleNamespace())
+ session._phase = "connection-ready"
+ job = MaintenanceJob("usb-storage", "synthetic-op", (), 0, 0, time.monotonic() + 5)
+ for mode in ("usb", "quick-connect", "direct-connect", "bridge"):
+ session._connection_binding = ApplicationConnectionBinding(
+ "synthetic-intent", "synthetic-transport", 1, "192.0.2.1", 1883, mode,
+ )
+ if mode == "bridge":
+ session._validate_management_job(job)
+ else:
+ with pytest.raises(ValueError, match="Bridge"):
+ session._validate_management_job(job)
+ assert session._management.pending is None
diff --git a/tests/test_k1_installer.py b/tests/test_k1_installer.py
index 915a84b9..d918ba95 100644
--- a/tests/test_k1_installer.py
+++ b/tests/test_k1_installer.py
@@ -158,7 +158,7 @@ def test_private_release_contains_material_only_in_root_private_member(
position += 60 + length + length % 2
with tarfile.open(fileobj=io.BytesIO(members["control.tar.gz"]), mode="r:gz") as archive:
control = archive.extractfile("control").read().decode()
- assert "Depends: mission-core-node (>= 0.8.13)" in control
+ assert "Depends: mission-core-node (>= 0.8.49-57)" in control
assert "Replaces: mission-core-node (<< 0.8.0)" in control
diff --git a/tests/test_k1_usb_network.py b/tests/test_k1_usb_network.py
new file mode 100644
index 00000000..b9a91110
--- /dev/null
+++ b/tests/test_k1_usb_network.py
@@ -0,0 +1,225 @@
+import asyncio
+import json
+from dataclasses import replace
+from types import SimpleNamespace
+
+import pytest
+from pydantic import ValidationError
+from test_xgrids_acquisition_lifecycle import _direct_host_path, service_with_fake_runtime
+
+from k1link.device_plugins.xgrids_k1 import facade as facade_module
+from k1link.device_plugins.xgrids_k1.facade import (
+ ConnectionVerifyRequest,
+ ConnectRequest,
+ DesiredConnectionModeRequest,
+)
+from k1link.device_plugins.xgrids_k1.usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
+
+
+def attachment():
+ return UsbNetworkAttachment("usb:synthetic", "test0", "10.255.254.77",
+ "10.255.254.2", "generation-one", "480")
+
+
+def usb_tree(tmp_path):
+ usb = tmp_path / "devices" / "usb1" / "1-2"
+ net = usb / "1-2:1.0" / "net" / "test0"
+ net.mkdir(parents=True)
+ driver = tmp_path / "drivers" / "rndis_host"
+ driver.mkdir(parents=True)
+ (usb / "1-2:1.0" / "driver").symlink_to(driver)
+ (net / "device").symlink_to(usb / "1-2:1.0")
+ sys_net = tmp_path / "class" / "net"
+ sys_net.mkdir(parents=True)
+ (sys_net / "test0").symlink_to(net)
+ for name, value in {"idVendor": "2207", "idProduct": "0019", "serial": "synthetic",
+ "product": "XGRIDS Device", "busnum": "1", "devnum": "4",
+ "speed": "480"}.items():
+ (usb / name).write_text(value)
+ (net / "carrier").write_text("1")
+ (net / "ifindex").write_text("9")
+ return usb, net, sys_net
+
+
+def runner(args, **kwargs):
+ if args[0] == "nmcli":
+ return "DHCP4.OPTION[1]:dhcp_server_identifier = 10.255.254.77\n"
+ assert args == ["ip", "-j", "route", "get", "10.255.254.77"]
+ return json.dumps([{"dev": "test0", "prefsrc": "10.255.254.2"}])
+
+
+def test_discovery_uses_dhcp_not_address_default_and_keeps_identity_on_replug(tmp_path):
+ usb, net, sys_net = usb_tree(tmp_path)
+ probe = LinuxK1UsbProbe(sys_net, runner)
+ before, = probe.discover()
+ assert before.peer_ipv4 == "10.255.254.77"
+ (usb / "devnum").write_text("5")
+ (net / "ifindex").write_text("10")
+ after, = probe.discover()
+ assert after.transport_ref == before.transport_ref
+ assert after.generation != before.generation
+ (net / "carrier").write_text("0")
+ assert probe.discover() == ()
+
+
+@pytest.mark.parametrize("fault", ["vendor", "mass-storage", "dhcp", "route", "gateway"])
+def test_unproved_usb_topology_never_becomes_candidate(tmp_path, fault):
+ usb, _, sys_net = usb_tree(tmp_path)
+ if fault == "vendor":
+ (usb / "idVendor").write_text("1234")
+ if fault == "mass-storage":
+ (usb / "1-2:1.0" / "driver").unlink()
+
+ def broken(args, **kwargs):
+ if fault == "dhcp" and args[0] == "nmcli":
+ return ""
+ if args[0] == "ip" and fault in {"route", "gateway"}:
+ return json.dumps([{"dev": "wifi0" if fault == "route" else "test0",
+ "prefsrc": "10.255.254.2", "gateway": "10.255.254.1"}])
+ return runner(args, **kwargs)
+
+ assert LinuxK1UsbProbe(sys_net, broken).discover() == ()
+
+
+def test_usb_cannot_be_sent_as_wireless_provisioning():
+ with pytest.raises(ValidationError):
+ ConnectRequest.model_validate({"connection_mode": "usb"})
+
+
+def test_usb_verify_reuses_identity_admission_and_performs_no_ble(monkeypatch, tmp_path):
+ service, _ = service_with_fake_runtime(tmp_path)
+ live = [attachment()]
+ service._usb_network_probe = SimpleNamespace(require=lambda _: live[0])
+ monkeypatch.setattr(facade_module, "_inspect_host_path", _direct_host_path)
+ monkeypatch.setattr(facade_module, "_control_endpoint_reachable", lambda _: True)
+
+ def forbidden(*args, **kwargs):
+ raise AssertionError("USB must never contact BLE or mutate Wi-Fi")
+
+ monkeypatch.setattr(facade_module, "read_wifi_status_once", forbidden)
+ monkeypatch.setattr(facade_module, "provision_wifi_once", forbidden)
+ monkeypatch.setattr(service, "_borrow_network_ble_process_lease", forbidden)
+
+ async def verify():
+ state = service.select_connection_mode(DesiredConnectionModeRequest(
+ connection_mode="usb", expected_revision=0,
+ ))
+ return await service.verify_connection(ConnectionVerifyRequest(
+ device_id=live[0].transport_ref, source="usb-enumeration",
+ compatibility_attestation={"firmware_version": "3.0.2", "topology": "usb-ethernet",
+ "verification": "live-device-info"},
+ expected_mode_revision=state["desired_connection_mode_revision"],
+ ))
+
+ try:
+ state = asyncio.run(verify())
+ assert state["connection_lifecycle"]["connection_ready"] is True
+ assert state["active_connection_mode"] == "usb"
+ assert state["acquisition"] is None
+ assert state["physical_command"]["record"] is None
+ assert state["semantic_topology_store"]["record"]["source"] == "usb-enumeration"
+ before = service._sample_host_path(live[0].peer_ipv4)
+ live[0] = replace(live[0], generation="generation-two")
+ assert service._sample_host_path(live[0].peer_ipv4).fingerprint != before.fingerprint
+ live[0] = replace(live[0], interface="different")
+ assert service._sample_host_path(live[0].peer_ipv4).available is False
+ finally:
+ service.close()
+
+
+def test_usb_start_journal_survives_restart_without_changing_start(tmp_path):
+ from test_xgrids_physical_command_ledger import _connection, _prepare_start
+
+ from k1link.device_plugins.xgrids_k1.physical_command_ledger import PhysicalCommandLedger
+
+ ledger = PhysicalCommandLedger(tmp_path)
+ binding = replace(_connection(), connection_mode="usb", transport_ref="usb:synthetic")
+ _prepare_start(ledger, connection=binding)
+ before = ledger.snapshot().record
+ after = PhysicalCommandLedger(tmp_path).snapshot().record
+ assert after == before
+ assert after.action == "start"
+ assert after.connection.connection_mode == "usb"
+ assert after.stage == "prepared"
+
+
+def test_hotplug_observer_only_verifies_once_per_attachment(monkeypatch):
+ from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
+
+ calls = []
+ current = {"active_connection_mode": None, "desired_connection_mode": "bridge",
+ "desired_connection_mode_revision": 0, "source_mode": "idle"}
+
+ async def invoke(*args):
+ return dict(current)
+
+ def select(request):
+ calls.append("select")
+ current.update(desired_connection_mode=request.connection_mode,
+ desired_connection_mode_revision=1)
+ return dict(current)
+
+ async def verify(request):
+ calls.append(request)
+ current["active_connection_mode"] = "usb"
+ current["connection_lifecycle"] = {"connection_ready": True}
+
+ bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
+ service=SimpleNamespace(select_connection_mode=select,
+ verify_connection=verify))
+ observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
+
+ async def observe():
+ await observer.observe_once()
+ await observer.observe_once()
+
+ asyncio.run(observe())
+ assert calls[0] == "select"
+ assert len(calls) == 2
+ assert isinstance(calls[1], ConnectionVerifyRequest)
+ assert calls[1].source == "usb-enumeration"
+
+
+@pytest.mark.parametrize("source,phase,retries", [
+ ("idle", "failed", 1),
+ ("idle", "completed", 1),
+ ("live", "failed", 0),
+ ("idle", "stopping", 0),
+ ("live", "running", 0),
+])
+def test_unchanged_usb_rechecks_retired_control_without_stealing_receiver(source, phase, retries):
+ from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
+
+ calls = []
+ current = {"active_connection_mode": None, "desired_connection_mode": "usb",
+ "desired_connection_mode_revision": 2, "source_mode": source,
+ "acquisition": {"state": phase}, "connection_lifecycle": {"connection_ready": False}}
+
+ async def invoke(*args):
+ return current
+
+ async def verify(request):
+ calls.append(request)
+
+ bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke,
+ service=SimpleNamespace(verify_connection=verify))
+ observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
+ observer.accepted_generation = attachment().generation
+ asyncio.run(observer.observe_once())
+ assert len(calls) == retries
+ if calls:
+ assert calls[0].source == "usb-enumeration"
+ assert calls[0].expected_mode_revision == 2
+ assert calls[0].device_id == attachment().transport_ref
+
+
+def test_hotplug_cannot_steal_active_wireless_acquisition():
+ from k1link.device_plugins.xgrids_k1.node_usb import NodeK1UsbObserver
+
+ async def invoke(*args):
+ return {"active_connection_mode": "bridge", "source_mode": "live"}
+
+ bridge = SimpleNamespace(lock=asyncio.Lock(), invoke=invoke, service=object())
+ observer = NodeK1UsbObserver(bridge, SimpleNamespace(discover=lambda: (attachment(),)))
+ asyncio.run(observer.observe_once())
+ assert observer.accepted_generation is None
diff --git a/tests/test_node_camera.py b/tests/test_node_camera.py
new file mode 100644
index 00000000..3bc20e69
--- /dev/null
+++ b/tests/test_node_camera.py
@@ -0,0 +1,161 @@
+"""Preview decoding/adaptation never acquires a physical camera or a recorder."""
+
+import asyncio
+import io
+import queue
+import threading
+import time
+from fractions import Fraction
+from types import SimpleNamespace
+
+import av
+import numpy as np
+import pytest
+
+from k1link.viewer.node_camera import CameraSource, CameraTrack, LeaseReader, open_live_camera
+from k1link.viewer.node_media import admit_sdp
+
+
+def test_mp4_lease_decodes_to_one_latest_frame_without_network_or_capture_change():
+ output = io.BytesIO()
+ with av.open(
+ output,
+ "w",
+ format="mp4",
+ options={"movflags": "frag_keyframe+empty_moov+default_base_moof"},
+ ) as mux:
+ stream = mux.add_stream("libx264", rate=15)
+ stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
+ for index in range(10):
+ frame = av.VideoFrame.from_ndarray(
+ np.full((48, 64, 3), index * 10, dtype=np.uint8), format="rgb24"
+ )
+ for packet in stream.encode(frame):
+ mux.mux(packet)
+ for packet in stream.encode():
+ mux.mux(packet)
+ segments = queue.Queue()
+ data = output.getvalue()
+ for offset in range(0, len(data), 113):
+ segments.put(("media", data[offset : offset + 113]))
+ segments.put(None)
+ lease = SimpleNamespace(segments=segments)
+
+ class Camera:
+ opened = 0
+ released = 0
+ streamed = 0
+
+ def snapshot(self):
+ return {
+ "generation": 7,
+ "recording": {
+ "source_end_expected": self.released > 0,
+ "active": True,
+ "producer_alive": True,
+ "media_ready": True,
+ "active_epoch": 7,
+ },
+ }
+
+ def open_delivery(self, generation, *, require_recording):
+ assert generation == 7 and require_recording
+ self.opened += 1
+ return lease
+
+ def release_delivery(self, value, *, client_closed):
+ assert value is lease and client_closed
+ self.released += 1
+
+ def mark_streaming(self, value):
+ assert value is lease
+ self.streamed += 1
+
+ camera = Camera()
+ source = CameraSource(camera)
+ source.thread.join(3)
+ source.close()
+ source.thread.join(1)
+ assert not source.thread.is_alive()
+ assert source.sequence >= 1 and camera.streamed >= 1
+ assert camera.opened == camera.released == 1
+
+
+def test_closing_consumer_unblocks_mp4_reader():
+ stopped = threading.Event()
+ reader = LeaseReader(SimpleNamespace(segments=queue.Queue()), stopped)
+ result = []
+ worker = threading.Thread(target=lambda: result.append(reader.read(12)))
+ worker.start()
+ stopped.set()
+ worker.join(1)
+ assert not worker.is_alive() and result == [b""]
+
+
+def test_live_fragment_is_decoded_without_waiting_for_future_frames_or_eof():
+ output = io.BytesIO()
+ with av.open(output, "w", format="mp4", options={
+ "movflags": "empty_moov+default_base_moof+frag_every_frame",
+ }) as mux:
+ stream = mux.add_stream("libx264", rate=15)
+ stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
+ stream.options = {"tune": "zerolatency", "g": "1"}
+ for index in range(3):
+ frame = av.VideoFrame.from_ndarray(
+ np.full((48, 64, 3), index * 50, dtype=np.uint8), format="rgb24"
+ )
+ for packet in stream.encode(frame):
+ mux.mux(packet)
+ # Capture while the producer remains live: no trailer or EOF.
+ live = output.getvalue()
+ segments = queue.Queue()
+ segments.put(("media", live))
+ stopped, decoded = threading.Event(), threading.Event()
+
+ def consume():
+ reader = LeaseReader(SimpleNamespace(segments=segments), stopped)
+ with open_live_camera(reader) as container:
+ for _frame in container.decode(video=0):
+ decoded.set()
+ break
+
+ worker = threading.Thread(target=consume, daemon=True)
+ worker.start()
+ try:
+ assert decoded.wait(1), "live preview waited for future data or EOF"
+ finally:
+ stopped.set()
+ worker.join(2)
+ assert not worker.is_alive()
+
+
+def test_camera_track_obeys_shared_budget_and_never_mutates_source_frame():
+ frame = av.VideoFrame(1280, 720, "yuv420p")
+ frame.pts, frame.time_base = 123, Fraction(1, 90000)
+ source = SimpleNamespace(closed=threading.Event(), current=lambda: (1, frame, time.monotonic()))
+ budget = SimpleNamespace(video=lambda: (320, 4))
+
+ async def run():
+ track = CameraTrack(source, budget)
+ try:
+ result = await asyncio.wait_for(track.recv(), 1)
+ assert result.width == 320 and result.height == 180
+ assert result.pts == 123 and result is not frame and frame.width == 1280
+ finally:
+ track.stop()
+
+ asyncio.run(run())
+
+
+def test_camera_sdp_requires_exact_video_and_control_channel_and_private_ice():
+ invitation = (
+ "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n"
+ "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n"
+ )
+ admit_sdp(invitation, camera=True)
+ with pytest.raises(ValueError):
+ admit_sdp(invitation)
+ with pytest.raises(ValueError):
+ admit_sdp(invitation + "m=audio 9 UDP/TLS/RTP/SAVPF 0\r\n", camera=True)
+ with pytest.raises(ValueError):
+ admit_sdp(invitation + "a=candidate:1 1 udp 1 8.8.8.8 1234 typ host\r\n", camera=True)
diff --git a/tests/test_node_k1_bridge.py b/tests/test_node_k1_bridge.py
index b2e4044c..5de45398 100644
--- a/tests/test_node_k1_bridge.py
+++ b/tests/test_node_k1_bridge.py
@@ -52,6 +52,16 @@ class Facade:
async def invoke(self, request):
self.actions.append((request.action_id, copy.deepcopy(request.parameters)))
+ if request.action_id == "connection.verify":
+ from k1link.device_plugins.xgrids_k1.facade import ConnectionVerifyRequest
+
+ ConnectionVerifyRequest.model_validate(
+ {
+ key: value
+ for key, value in request.parameters.items()
+ if key != "expected_snapshot_runtime_id"
+ }
+ )
if request.action_id == "application-control.workspace.enter":
self.current["application_control_session"]["state"] = "workspace-ready"
elif request.action_id == "acquisition.prepare":
@@ -75,6 +85,28 @@ def bridge():
return result
+def test_retired_usb_control_keeps_transport_identity_without_claiming_connection():
+ snapshot = state()
+ snapshot.update(active_connection_mode=None, desired_connection_mode="usb",
+ selected_device_id="usb:synthetic", k1_ip="10.255.254.77",
+ connection_lifecycle={"connection_ready": False, "ready_to_start": False})
+ item = project_sensor(snapshot, "node-test")
+ assert item["connection_mode"] == "usb"
+ assert item["connection_label"] == "USB · 10.255.254.77"
+ assert not item["online"] and not item["verified"]
+ assert not item["control"]["can_start"]
+ parameters = verification_parameters(snapshot, "verify-usb")
+ assert parameters["source"] == "usb-enumeration"
+ assert parameters["device_id"] == "usb:synthetic"
+ assert parameters["compatibility_attestation"]["topology"] == "usb-ethernet"
+
+
+def test_usb_draft_does_not_replace_active_wireless_verification_target():
+ snapshot = state()
+ snapshot["desired_connection_mode"] = "usb"
+ assert "source" not in verification_parameters(snapshot, "verify-current")
+
+
@pytest.mark.parametrize("available", [False, True])
def test_startup_credential_check_does_not_authorize_control(monkeypatch, available):
from k1link.device_plugins.xgrids_k1 import node_bridge
@@ -124,9 +156,13 @@ def test_journalled_failure_logs_source_without_secret_and_does_not_repeat(caplo
return {"operations": [{"operation_id": native, "status": "failed"}]}
device.invoke = invoke
- result = asyncio.run(device.invoke_journalled(
- "network.provision", {"operation_id": native, "password": secret}, identifier,
- ))
+ result = asyncio.run(
+ device.invoke_journalled(
+ "network.provision",
+ {"operation_id": native, "password": secret},
+ identifier,
+ )
+ )
assert result["operations"][0]["status"] == "failed"
assert calls == ["network.provision", "state.read"]
assert "exception=BleakError" in caplog.text
@@ -156,20 +192,28 @@ def test_real_facade_preserves_native_failure_location_in_journalled_log(caplog)
async def connect(self, request):
calls.append("connect")
- self.current["operations"] = [{
- "operation_id": request.operation_id, "status": "failed",
- "error": {"code": "BleakError"},
- }]
+ self.current["operations"] = [
+ {
+ "operation_id": request.operation_id,
+ "status": "failed",
+ "error": {"code": "BleakError"},
+ }
+ ]
raise BleakError(secret)
async def run():
device = NodeBridge(Path.cwd(), service=Service())
command = {
- "operation_id": "op_" + "c" * 32, "runtime_id": "runtime-one",
+ "operation_id": "op_" + "c" * 32,
+ "runtime_id": "runtime-one",
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
- "action": "connect", "parameters": {
- "device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 1,
- "mode_revision": 0, "ssid": "test-network", "password": secret,
+ "action": "connect",
+ "parameters": {
+ "device_id": "AA:BB:CC:DD:EE:FF",
+ "discovery_generation": 1,
+ "mode_revision": 0,
+ "ssid": "test-network",
+ "password": secret,
},
}
result = await device.deliver(command)
@@ -274,7 +318,9 @@ def test_node_scan_reaches_service_through_real_facade_with_runtime_fence():
@pytest.mark.parametrize("radio_failure", [False, True])
def test_node_scan_real_service_preserves_operation_identity_and_replay(
- tmp_path, monkeypatch, radio_failure,
+ tmp_path,
+ monkeypatch,
+ radio_failure,
):
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
@@ -295,8 +341,13 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
self.callback(
BLEDevice("AA:BB:CC:DD:EE:FF", "XGR-TEST", None),
AdvertisementData(
- local_name="XGR-TEST", manufacturer_data={}, service_data={},
- service_uuids=[], tx_power=None, rssi=-50, platform_data=(),
+ local_name="XGR-TEST",
+ manufacturer_data={},
+ service_data={},
+ service_uuids=[],
+ tx_power=None,
+ rssi=-50,
+ platform_data=(),
),
)
return self
@@ -317,7 +368,8 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
"operation_id": "op_" + "b" * 32,
"runtime_id": current["runtime_id"],
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
- "action": "scan", "parameters": {},
+ "action": "scan",
+ "parameters": {},
}
result = await device.deliver(command)
if not radio_failure:
@@ -329,12 +381,16 @@ def test_node_scan_real_service_preserves_operation_identity_and_replay(
assert result["candidates"] == []
else:
assert result["candidates"][0]["id"] == "AA:BB:CC:DD:EE:FF"
- assert result["command_result"] == repeated["command_result"] == {
- "operation_id": command["operation_id"],
- "action": "scan",
- "status": "failed" if radio_failure else "succeeded",
- "error_code": "RuntimeError" if radio_failure else None,
- }
+ assert (
+ result["command_result"]
+ == repeated["command_result"]
+ == {
+ "operation_id": command["operation_id"],
+ "action": "scan",
+ "status": "failed" if radio_failure else "succeeded",
+ "error_code": "RuntimeError" if radio_failure else None,
+ }
+ )
try:
asyncio.run(run())
@@ -349,7 +405,8 @@ def test_node_attempt_projection_keeps_host_correlation_without_mutating_plugin_
"schema_version": "missioncore.xgrids-k1-connection-attempt/v1",
"attempt_id": plugin_operation_id(identifier),
"recovery_operation_id": plugin_operation_id("op_" + "b" * 32),
- "status": "failed", "public_error_code": "wifi-ssid-not-found",
+ "status": "failed",
+ "public_error_code": "wifi-ssid-not-found",
}
result = NodeBridge.project(current)
assert result["connection_attempt"]["attempt_id"] == identifier
@@ -420,11 +477,13 @@ def test_sensor_projection_binds_native_sdk_to_board():
def test_applied_wifi_does_not_grant_control_or_start_authority():
current = state()
current["connection_lifecycle"] = {
- "connection_ready": False, "ready_to_start": False,
+ "connection_ready": False,
+ "ready_to_start": False,
"allowed_actions": ["verify-control-read-only"],
}
current["connection_attempt"] = {
- "phase": "network_applied", "public_error_code": "application_authority_unavailable",
+ "phase": "network_applied",
+ "public_error_code": "application_authority_unavailable",
}
item = project_sensor(current, "node-test")
assert not item["online"] and not item["verified"]
@@ -441,7 +500,8 @@ def test_applied_wifi_does_not_grant_control_or_start_authority():
@pytest.mark.parametrize("initial_phase", ["connection-ready", "completed"])
@pytest.mark.parametrize("pending_start", [False, True])
def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
- initial_phase, pending_start,
+ initial_phase,
+ pending_start,
):
async def run():
device = bridge()
@@ -467,7 +527,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
"parameters": {
"operator_confirmed": True,
"project_name": " Synthetic survey ",
- "mount_type": "handheld", "gnss_mode": "none",
+ "mount_type": "handheld",
+ "gnss_mode": "none",
"control_generation": 1,
"acquisition_id": None,
},
@@ -488,7 +549,8 @@ def test_one_start_intent_preserves_canonical_enter_prepare_start_sequence(
assert payload["mount_type"] == "handheld" and payload["gnss_mode"] == "none"
if action in {"acquisition.prepare", "acquisition.start"}:
row, created = journal.begin(
- action, operation_id=payload["operation_id"],
+ action,
+ operation_id=payload["operation_id"],
idempotency_key=payload["idempotency_key"],
)
assert created
@@ -506,6 +568,104 @@ def test_networkmanager_ssids_are_not_split_at_escaped_colons():
assert nm_fields(r"field\:network\\name:88:WPA2") == ["field:network\\name", "88", "WPA2"]
+@pytest.mark.parametrize("locale", ["ru_RU.UTF-8", "en_US.UTF-8"])
+def test_linux_wifi_probe_uses_stable_cli_locale_without_changing_parent(
+ tmp_path,
+ monkeypatch,
+ locale,
+):
+ import os
+ import subprocess
+
+ from k1link.device_plugins.xgrids_k1 import linux_host
+ from k1link.host_network.wifi import bind_route_fingerprint_to_wifi_association
+
+ (tmp_path / "wlan0" / "wireless").mkdir(parents=True)
+ monkeypatch.setenv("LANG", locale)
+ monkeypatch.setenv("LC_ALL", locale)
+ parent_env = dict(os.environ)
+ calls = []
+
+ def run(args, **kwargs):
+ child_env = kwargs.get("env", os.environ)
+ calls.append(child_env)
+ active = "yes" if child_env.get("LC_ALL") == "C" else "да"
+ return subprocess.CompletedProcess(
+ args,
+ 0,
+ active + r":Поле\:сеть:AA\:BB\:CC\:DD\:EE\:FF" + "\n",
+ "",
+ )
+
+ monkeypatch.setattr(linux_host.subprocess, "run", run)
+ probe = linux_host.LinuxWifiAssociationProbe(tmp_path)
+ observed = probe.observe("wlan0")
+ assert observed["association_state"] == "associated"
+ assert observed["continuity_proven"] is True
+ assert observed["reason_code"] is None
+ fingerprint = bind_route_fingerprint_to_wifi_association("route", observed)
+ repeated = bind_route_fingerprint_to_wifi_association("route", probe.observe("wlan0"))
+ assert repeated == fingerprint
+ assert all(env["LC_ALL"] == env["LANG"] == "C" for env in calls)
+ assert dict(os.environ) == parent_env
+
+
+@pytest.mark.parametrize("unavailable", ["empty", "inactive", "ambiguous", "command-error"])
+@pytest.mark.parametrize("fail_closed", [False, True])
+def test_linux_missing_association_reports_unavailable_without_invalid_token(
+ tmp_path,
+ monkeypatch,
+ unavailable,
+ fail_closed,
+):
+ from k1link.device_plugins.xgrids_k1 import facade, linux_host
+
+ (tmp_path / "sys-net" / "wlan0" / "wireless").mkdir(parents=True)
+ probe = linux_host.LinuxWifiAssociationProbe(tmp_path / "sys-net")
+ service = facade.XgridsK1CompatibilityService(
+ tmp_path / "runtime",
+ host_wifi_association_probe=probe,
+ )
+ path = facade.HostPathProbeResult(
+ available=True,
+ fingerprint="synthetic-route",
+ interface="wlan0",
+ source_ipv4="192.168.1.2",
+ route_class="direct",
+ reason_code=None,
+ )
+ monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
+
+ def run(*_args, **_kwargs):
+ if unavailable == "command-error":
+ raise OSError("Network observation unavailable")
+ return {
+ "empty": "",
+ "inactive": r"no:test:AA\:BB\:CC\:DD\:EE\:FF",
+ "ambiguous": "yes:test:one\nyes:test:two\n",
+ }[unavailable]
+
+ def forbidden(*_args, **_kwargs):
+ raise AssertionError("Unobserved Wi-Fi must not authorize a TCP probe")
+
+ monkeypatch.setattr(linux_host, "_run", run)
+ monkeypatch.setattr(facade, "_control_endpoint_reachable", forbidden)
+ try:
+ observed = service._sample_host_path(
+ "192.168.1.7",
+ fail_closed_unproven_association=fail_closed,
+ )
+ assert observed.available is False
+ assert observed.fingerprint is None
+ assert observed.kernel_route_fingerprint == path.fingerprint
+ assert observed.reason_code == "host-wifi-observation-unavailable"
+ endpoint = service._probe_control_endpoint("192.168.1.7")
+ assert endpoint.reachable is False
+ assert endpoint.reason_code == observed.reason_code
+ finally:
+ service.close()
+
+
def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, monkeypatch):
from k1link.device_plugins.xgrids_k1 import linux_host
@@ -523,7 +683,9 @@ def test_wired_board_bridge_does_not_require_host_wifi_association(tmp_path, mon
@pytest.mark.parametrize("route_changes", [False, True])
def test_wired_board_real_service_correlates_route_and_control_endpoint(
- tmp_path, monkeypatch, route_changes,
+ tmp_path,
+ monkeypatch,
+ route_changes,
):
from dataclasses import replace
@@ -533,11 +695,16 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
(sys_net / "enp1s0").mkdir(parents=True)
probe = linux_host.LinuxWifiAssociationProbe(sys_net)
service = facade.XgridsK1CompatibilityService(
- tmp_path / "runtime", host_wifi_association_probe=probe,
+ tmp_path / "runtime",
+ host_wifi_association_probe=probe,
)
path = facade.HostPathProbeResult(
- available=True, fingerprint="synthetic-route", interface="enp1s0",
- source_ipv4="192.168.1.2", route_class="direct", reason_code=None,
+ available=True,
+ fingerprint="synthetic-route",
+ interface="enp1s0",
+ source_ipv4="192.168.1.2",
+ route_class="direct",
+ reason_code=None,
)
monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: path)
calls = []
@@ -545,9 +712,15 @@ def test_wired_board_real_service_correlates_route_and_control_endpoint(
def tcp(_target):
calls.append("tcp")
if route_changes:
- monkeypatch.setattr(facade, "_inspect_host_path", lambda _target: replace(
- path, fingerprint="new-route", source_ipv4="192.168.1.3",
- ))
+ monkeypatch.setattr(
+ facade,
+ "_inspect_host_path",
+ lambda _target: replace(
+ path,
+ fingerprint="new-route",
+ source_ipv4="192.168.1.3",
+ ),
+ )
return True
monkeypatch.setattr(facade, "_control_endpoint_reachable", tcp)
@@ -649,32 +822,45 @@ def test_preview_offer_cannot_cross_acquisition_boundary(replacement):
asyncio.run(run())
-@pytest.mark.parametrize("draft", [
- {}, {"project_name": " "}, {"project_name": "x" * 97},
- {"project_name": "invalid\nname"}, {"project_name": "Valid", "mount_type": "uav"},
- {"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
-])
+@pytest.mark.parametrize(
+ "draft",
+ [
+ {},
+ {"project_name": " "},
+ {"project_name": "x" * 97},
+ {"project_name": "invalid\nname"},
+ {"project_name": "Valid", "mount_type": "uav"},
+ {"project_name": "Valid", "mount_type": "handheld", "gnss_mode": "rtk"},
+ ],
+)
def test_invalid_start_draft_dispatches_no_workspace_or_project_command(draft):
async def run():
device = bridge()
item = project_sensor(state(), "node-test")
command = {
- "operation_id": "op_" + "b" * 32, "action_id": "start",
+ "operation_id": "op_" + "b" * 32,
+ "action_id": "start",
"session": {"device_id": item["id"], "session_id": "session-test"},
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
- "parameters": {"operator_confirmed": True, "control_generation": 1,
- "acquisition_id": None, **draft},
+ "parameters": {
+ "operator_confirmed": True,
+ "control_generation": 1,
+ "acquisition_id": None,
+ **draft,
+ },
}
with pytest.raises(ValueError):
await NodeK1Sensor(device, None).execute(command, "node-test")
assert all(action == "state.read" for action, _ in device.facade.actions)
+
asyncio.run(run())
def test_recheck_uses_only_exact_admitted_durable_bridge_target():
current = state()
decision = {
- "allowed": True, "requires_live_gatt_validation": False,
+ "allowed": True,
+ "requires_live_gatt_validation": False,
"required_transport_ref": current["selected_device_id"],
"required_connection_mode": "bridge",
}
@@ -684,16 +870,25 @@ def test_recheck_uses_only_exact_admitted_durable_bridge_target():
assert result["device_id"] == current["selected_device_id"]
assert result["expected_mode_revision"] == current["desired_connection_mode_revision"]
assert "source" not in verification_parameters(
- current, "synthetic-operation", requested_device_id="other-device",
+ current,
+ "synthetic-operation",
+ requested_device_id="other-device",
)
- for patch in [{"allowed": False}, {"requires_live_gatt_validation": True},
- {"required_connection_mode": "quick-connect"},
- {"required_transport_ref": "other"}]:
+ for patch in [
+ {"allowed": False},
+ {"required_connection_mode": "quick-connect"},
+ {"required_transport_ref": "other"},
+ ]:
decision.update(patch)
- assert "source" not in verification_parameters(current, "synthetic-operation")
- decision.update(allowed=True, requires_live_gatt_validation=False,
- required_transport_ref=current["selected_device_id"],
- required_connection_mode="bridge")
+ assert "source" not in verification_parameters(
+ current, "synthetic-operation", requested_device_id=current["selected_device_id"]
+ )
+ decision.update(
+ allowed=True,
+ requires_live_gatt_validation=False,
+ required_transport_ref=current["selected_device_id"],
+ required_connection_mode="bridge",
+ )
@pytest.mark.parametrize("requires_gatt", [False, True])
@@ -701,23 +896,340 @@ def test_enrollment_verify_and_detail_share_durable_target_admission(requires_ga
async def run():
device = bridge()
current = device.facade.current
- current["connection_policy"] = {"actions": {"observe-configured-device-network": {
- "allowed": True, "requires_live_gatt_validation": requires_gatt,
- "required_connection_mode": "bridge",
- "required_transport_ref": current["selected_device_id"],
- }}}
+ current["connection_policy"] = {
+ "actions": {
+ "observe-configured-device-network": {
+ "allowed": True,
+ "requires_live_gatt_validation": requires_gatt,
+ "required_connection_mode": "bridge",
+ "required_transport_ref": current["selected_device_id"],
+ }
+ }
+ }
command = {
- "operation_id": "op_" + "d" * 32, "action": "verify", "runtime_id": "runtime-one",
+ "operation_id": "op_" + "d" * 32,
+ "action": "verify",
+ "runtime_id": "runtime-one",
"deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
- "parameters": {"device_id": current["selected_device_id"],
- "discovery_generation": 1, "mode_revision": 0},
+ "parameters": {
+ "device_id": current["selected_device_id"],
+ "discovery_generation": 1,
+ "mode_revision": 0,
+ },
}
await device.execute(command)
actions = [(a, p) for a, p in device.facade.actions if a != "state.read"]
assert len(actions) == 1 and actions[0][0] == "connection.verify"
payload = actions[0][1]
- assert (payload.get("source") == "durable-configured-state") is not requires_gatt
+ assert payload["source"] == "durable-configured-state"
assert payload["device_id"] == current["selected_device_id"]
- assert payload["expected_discovery_generation"] == 1
+ assert "expected_discovery_generation" not in payload
assert "password" not in payload
+
asyncio.run(run())
+
+
+def test_explicit_fresh_selection_uses_current_scan_when_policy_admits_it():
+ current = state()
+ current['connection_policy'] = {'actions': {
+ 'observe-configured-device-network': {'allowed': True,
+ 'required_transport_ref': current['selected_device_id'],
+ 'required_connection_mode': 'bridge'},
+ 'observe-fresh-device-network': {'allowed': True},
+ }}
+ args = {'requested_device_id': current['selected_device_id']}
+ assert 'source' not in verification_parameters(current, 'synthetic-operation', **args)
+ durable = 'durable-configured-state'
+ assert verification_parameters(current, 'synthetic-operation')['source'] == durable
+ current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = False
+ assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
+ current['connection_policy']['actions']['observe-fresh-device-network']['allowed'] = True
+ current['devices'] = []
+ assert verification_parameters(current, 'synthetic-operation', **args)['source'] == durable
+
+
+def test_preview_blueprint_uses_canonical_live_timeline_without_device_commands(monkeypatch):
+ import base64
+
+ from k1link.viewer.recorded import recorded_blueprint
+ from k1link.viewer.rerun_bridge import RerunSceneSettings
+
+ import k1link.device_plugins.xgrids_k1.node_sensor as module
+ calls = []
+ original = module.recorded_blueprint_rrd
+ def record(*args, **kwargs):
+ calls.append(kwargs)
+ return original(*args, **kwargs)
+ monkeypatch.setattr(module, "recorded_blueprint_rrd", record)
+
+ async def run():
+ device = bridge()
+ item = project_sensor(device.facade.current, "node-test")
+ sensor = NodeK1Sensor(device, None)
+ command = {
+ "operation_id": "op_" + "c" * 32,
+ "action_id": "details",
+ "session": {"device_id": item["id"], "session_id": "session-test"},
+ "parameters": {
+ "preview_blueprint": {
+ "recording_id": "synthetic-recording",
+ "owner": "b" * 32,
+ "view": "plan",
+ "follow_trajectory": True,
+ "host_playback": True,
+ "settings": {"accumulation_seconds": 240, "show_grid": False},
+ "eye": {"position": [1, 2, 3], "lookTarget": [0, 0, 0], "eyeUp": [0, 0, 1]},
+ }
+ },
+ }
+ result = await sensor.execute(command, "node-test")
+ assert base64.b64decode(result["rrd"]).startswith(b"RRF2")
+ assert calls[-1]["follow_trajectory"] is True
+ assert calls[-1]["initialize_playback"] is False
+ assert calls[-1]["eye_position"] == (1, 2, 3)
+ command["parameters"]["preview_blueprint"]["follow_trajectory"] = "true"
+ with pytest.raises(ValueError, match="follow"):
+ await sensor.execute(command, "node-test")
+ command["parameters"]["preview_blueprint"]["release"] = True
+ assert await sensor.execute(command, "node-test") == {"released": True}
+ assert all(action == "state.read" for action, _ in device.facade.actions)
+
+ asyncio.run(run())
+ blueprint = recorded_blueprint(
+ RerunSceneSettings(accumulation_seconds=240, show_grid=False),
+ timeline="stream_time",
+ plan_view=True,
+ )
+ spatial = blueprint.root_container.contents[0]
+ ranges = spatial.visualizer_overrides["/world/points"][-1].ranges.as_arrow_array().to_pylist()
+ assert ranges == [{"timeline": "stream_time", "range": {"start": -240_000_000_000, "end": 0}}]
+ assert spatial.properties["LineGrid3D"].visible.as_arrow_array().to_pylist() == [False]
+
+
+def cold_recovery_state():
+ current = state()
+ current.update(
+ selected_device_id=None,
+ devices=[],
+ ble_discovery_generation=0,
+ device_session=None,
+ active_connection_mode=None,
+ connection_lifecycle={
+ "connection_ready": False,
+ "ready_to_start": False,
+ "allowed_actions": ["observe-configured-device-network"],
+ },
+ )
+ current["connection_policy"] = {
+ "actions": {
+ "observe-configured-device-network": {
+ "allowed": True,
+ "requires_live_gatt_validation": False,
+ "required_transport_ref": "AA:BB:CC:DD:EE:FF",
+ "required_connection_mode": "bridge",
+ "target_source": "durable-configured-state",
+ }
+ }
+ }
+ current["active_acquisition_recovery_checkpoint"] = {
+ "status": "active",
+ "state": "active",
+ "gap_open": False,
+ "restart_rehydration_phase": "inactive",
+ "reason_code": None,
+ "private_lineage": "must-not-cross-node-projection",
+ }
+ return current
+
+
+@pytest.mark.parametrize("requires_gatt", [False, True])
+def test_cold_board_restart_verifies_saved_target_without_discovery_or_physical_command(
+ requires_gatt,
+):
+ device = bridge()
+ device.facade.current = cold_recovery_state()
+ device.facade.current["connection_policy"]["actions"]["observe-configured-device-network"][
+ "requires_live_gatt_validation"
+ ] = requires_gatt
+ checkpoint = copy.deepcopy(device.facade.current["active_acquisition_recovery_checkpoint"])
+ identifier = "op_" + "e" * 32
+
+ async def run():
+ before = await device.state()
+ assert before["connected"] is False
+ assert before["candidates"] == []
+ assert before["selected_device_id"] is None
+ assert before["reconnect_target"]["device_id"] == "AA:BB:CC:DD:EE:FF"
+ assert before["acquisition_recovery"]["state"] == "active"
+ assert "private_lineage" not in before["acquisition_recovery"]
+ assert device.facade.actions == [("state.read", {})]
+ device.facade.actions.clear()
+ await device.execute(
+ {
+ "operation_id": identifier,
+ "runtime_id": "runtime-one",
+ "action": "verify",
+ "deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
+ "parameters": {
+ "device_id": before["reconnect_target"]["device_id"],
+ "discovery_generation": 0,
+ "mode_revision": 0,
+ },
+ }
+ )
+
+ asyncio.run(run())
+ assert [action for action, _ in device.facade.actions] == ["state.read", "connection.verify"]
+ payload = device.facade.actions[-1][1]
+ assert payload["source"] == "durable-configured-state"
+ assert payload["device_id"] == "AA:BB:CC:DD:EE:FF"
+ assert payload["expected_snapshot_runtime_id"] == "runtime-one"
+ assert "password" not in payload and "ssid" not in payload
+ assert device.facade.current["active_acquisition_recovery_checkpoint"] == checkpoint
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ "foreign-target",
+ "denied-policy",
+ "other-mode",
+ "stale-generation",
+ "stale-runtime",
+ "provision",
+ ],
+)
+def test_saved_recovery_never_authorizes_foreign_stale_or_mutating_action(change):
+ device = bridge()
+ device.facade.current = cold_recovery_state()
+ parameters = {"device_id": "AA:BB:CC:DD:EE:FF", "discovery_generation": 0, "mode_revision": 0}
+ action, runtime = "verify", "runtime-one"
+ policy = device.facade.current["connection_policy"]["actions"][
+ "observe-configured-device-network"
+ ]
+ if change == "foreign-target":
+ parameters["device_id"] = "other-device"
+ if change == "denied-policy":
+ policy["allowed"] = False
+ if change == "other-mode":
+ policy["required_connection_mode"] = "quick-connect"
+ if change == "stale-generation":
+ parameters["discovery_generation"] = 1
+ if change == "stale-runtime":
+ runtime = "previous-runtime"
+ if change == "provision":
+ action = "connect"
+ with pytest.raises(ValueError):
+ asyncio.run(
+ device.execute(
+ {
+ "operation_id": "op_" + "f" * 32,
+ "runtime_id": runtime,
+ "action": action,
+ "deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
+ "parameters": parameters,
+ }
+ )
+ )
+ assert device.facade.actions == [("state.read", {})]
+
+
+def test_verification_failure_survives_polling_but_not_a_new_runtime():
+ current = cold_recovery_state()
+ current["operations"] = [
+ {
+ "operation_id": "op-" + str(__import__("uuid").UUID(int=123)),
+ "action": "connection.verify",
+ "status": "failed",
+ "context": {"snapshot_runtime_id": "runtime-one"},
+ "error": {
+ "code": "connection-verify-device-not-rediscovered",
+ "message": "private-detail",
+ },
+ }
+ ]
+ projected = NodeBridge.project(current)
+ assert projected["verification"]["error_code"] == "connection-verify-device-not-rediscovered"
+ assert projected["connected"] is False
+ assert projected["acquisition_recovery"]["state"] == "active"
+ assert "private-detail" not in json.dumps(projected)
+ assert "must-not-cross-node-projection" not in json.dumps(projected)
+ current["snapshot_runtime_id"] = "new-runtime"
+ assert NodeBridge.project(current)["verification"] is None
+
+
+@pytest.mark.parametrize("committed", [True, False])
+def test_onboard_reset_uses_real_facade_without_old_monitor_or_adapter_lock(committed):
+ calls = []
+
+ class Service:
+ def require_snapshot_runtime_id(self, expected):
+ assert expected == "runtime-one"
+
+ def bind_runtime_event_loop(self, _loop):
+ pytest.fail("local reset must not bind the old connection monitor")
+
+ def select_connection_mode(self, request):
+ calls.append(request.model_dump())
+ value = state()
+ if committed:
+ value["desired_connection_mode_revision"] = 1
+ value["connection_scenario_reset"] = {
+ "reset_id": request.reset_id,
+ "revision": 1,
+ "local_session_closed": True,
+ }
+ return value
+
+ async def run():
+ device = NodeBridge(Path.cwd(), service=Service())
+ command = {
+ "operation_id": "op_" + "d" * 32,
+ "runtime_id": "runtime-one",
+ "deadline_at": (datetime.now(UTC) + timedelta(seconds=60)).isoformat(),
+ "action": "reset",
+ "parameters": {"mode_revision": 0},
+ }
+ async with device.lock:
+ result = await asyncio.wait_for(device.execute(command), timeout=1)
+ assert result["command_result"]["status"] == ("succeeded" if committed else "failed")
+ assert result["can_reset"] is True
+
+ asyncio.run(run())
+ assert calls == [{
+ "connection_mode": "bridge", "expected_revision": 0,
+ "reset_scenario": True, "reset_id": plugin_operation_id("op_" + "d" * 32),
+ }]
+
+
+def test_reset_hides_previous_verify_even_after_scan_settles_reset_marker():
+ current = state()
+ current["connection_scenario_reset"] = {
+ "active": False,
+ "timing": {"completed_at_utc": "2026-11-01T12:00:00.500Z"},
+ }
+ old = {"operation_id": "op-old", "action": "connection.verify", "status": "failed",
+ "context": {"snapshot_runtime_id": "runtime-one"},
+ "accepted_at": "2026-11-01T11:59:59Z"}
+ current["operations"] = [old]
+ assert NodeBridge.project(current)["verification"] is None
+ current["operations"].append({**old, "operation_id": "op-new",
+ "accepted_at": "2026-11-01T12:00:01Z"})
+ assert NodeBridge.project(current)["verification"]["operation_id"] == "op-new"
+
+
+@pytest.mark.parametrize("age,connected,used,visible", [
+ (1, True, 99.0, True), (1, True, 0.0, True), (1, True, 100.0, True),
+ (6, True, 99.0, False), (-1, True, 99.0, False),
+ (1, False, 99.0, False), (1, True, float("nan"), False),
+ (1, True, 101.0, False), (1, True, True, False),
+])
+def test_storage_projection_uses_only_current_connected_status(age, connected, used, visible):
+ current = state()
+ current["connection_lifecycle"]["connection_ready"] = connected
+ current["application_control_session"]["transport"] = {"storage_status": {
+ "used_percent": used, "observed_at": (datetime.now(UTC)-timedelta(seconds=age)).isoformat(),
+ }}
+ result = project_sensor(current, "node-test")
+ assert (result["storage_status"] is not None) is visible
+ assert result["control"]["can_start"] is True # Display telemetry grants no authority.
diff --git a/tests/test_xgrids_acquisition_lifecycle.py b/tests/test_xgrids_acquisition_lifecycle.py
index 3ec4bf3b..abc70a77 100644
--- a/tests/test_xgrids_acquisition_lifecycle.py
+++ b/tests/test_xgrids_acquisition_lifecycle.py
@@ -11543,6 +11543,7 @@ class _ActualWorkerStopRaceExecutor:
observed: Callable[[], bool],
*,
reconciled_active_observed: Callable[[], bool] | None = None,
+ standby_work: Callable[[], None] | None = None,
) -> None:
deadline = time.monotonic() + 3.0
while not observed():
@@ -11550,6 +11551,8 @@ class _ActualWorkerStopRaceExecutor:
return None
if time.monotonic() >= deadline:
raise TimeoutError("actual worker checkpoint was not released")
+ if standby_work is not None:
+ standby_work()
threading.Event().wait(0.005)
return None
@@ -15472,6 +15475,62 @@ def test_post_start_refresh_timeout_wakes_existing_read_only_recovery(
assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
+@pytest.mark.parametrize("confirmed_start", [True, False])
+@pytest.mark.parametrize("brief_gap", [True, False])
+def test_returned_host_epoch_wakes_active_recovery_with_surviving_data_socket(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ brief_gap: bool,
+ confirmed_start: bool,
+) -> None:
+ service, runtime = service_with_fake_runtime(tmp_path)
+ control, physical = _install_composite_active_recovery_fixture(
+ service, runtime, monkeypatch, runtime_phase="live", camera_phase="streaming",
+ )
+ if not confirmed_start:
+ physical["requires_reconciliation"] = True
+ supervisor = service._connection_supervisor # noqa: SLF001
+ before = supervisor.snapshot()
+ if brief_gap:
+ supervisor.observe_host_path(HostPathProbeResult(
+ available=False, fingerprint=None, interface=None, source_ipv4=None,
+ route_class="unavailable", reason_code="host-route-unavailable",
+ ))
+ supervisor.observe_host_path(HostPathProbeResult(
+ available=True,
+ fingerprint=before.host_path.fingerprint if brief_gap else "same-lan-new-association",
+ interface=before.host_path.interface, source_ipv4=before.host_path.source_ipv4,
+ route_class=before.host_path.route_class,
+ kernel_route_fingerprint=before.host_path.kernel_route_fingerprint,
+ ))
+ assert supervisor.snapshot().host_path_negative_streak == 0
+ assert supervisor.snapshot().control_plane.reason_code == "host-path-epoch-changed"
+ starts = list(control.start_projects)
+ stops = control.stop_calls
+
+ state = service.state()
+ service.state()
+
+ if not confirmed_start:
+ assert runtime.recovery_requests == []
+ assert control.start_projects == starts
+ assert control.stop_calls == stops
+ assert runtime.stop_calls == 0
+ return
+ assert runtime.recovery_requests == [
+ ("host-path-epoch-changed", runtime.producer_generation),
+ ]
+ assert state["phase"] == "reconnecting"
+ assert state["connection_recovery"]["automatic_read_only_rebind"] is True
+ assert state["acquisition"]["state"] == "acquiring"
+ assert state["selected_device_id"] == "test-ble-transport"
+ assert control.state == "scanning"
+ assert control.start_projects == starts
+ assert control.stop_calls == stops
+ assert runtime.stop_calls == 0
+ assert service._physical_command_coordinator.snapshot() is physical # noqa: SLF001
+
+
def test_incident_host_route_streak_wakes_recovery_before_binding_retirement(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -34813,3 +34872,54 @@ def test_completed_acquisition_does_not_imply_control_loss(tmp_path, socket_open
{**control, "state": "failed"}, {"source_mode": "idle"},
)
assert not service._connection_supervisor.snapshot().authority.control_allowed # noqa: SLF001
+
+
+@pytest.mark.parametrize("writer_alive", [False, True])
+def test_fresh_start_recovers_only_terminated_evidence_writer_marker(
+ tmp_path: Path, writer_alive: bool,
+) -> None:
+ from k1link.sessions.active import ActiveSessionLease, ActiveSessionLeaseError
+
+ service, runtime = service_with_fake_runtime(tmp_path)
+ control = FakeInteractiveControlSession()
+ service._application_control_session = control # type: ignore[assignment] # noqa: SLF001
+ _seed_supervised_connection(service)
+ prepared = service.prepare_acquisition(
+ _prepare_request(
+ project_name="LEASE_RECOVERY",
+ host="192.168.1.20",
+ compatibility_attestation=ATTESTATION,
+ )
+ )
+ root = service.evidence_root
+ root.mkdir(parents=True, exist_ok=True)
+ interrupted = root / "20260813T120000Z_viewer_live"
+ interrupted.mkdir()
+ original_evidence = interrupted / "preserved.raw"
+ original_evidence.write_bytes(b"synthetic interrupted evidence")
+ owner = ActiveSessionLease.acquire(root, interrupted) if writer_alive else None
+ if owner is None:
+ (root / ".current_session").write_text(interrupted.name + "\n")
+ try:
+ request = _start_request(
+ acquisition_id=prepared["acquisition"]["acquisition_id"],
+ physical_acceptance=PHYSICAL_ACCEPTANCE,
+ )
+ if writer_alive:
+ with pytest.raises(ActiveSessionLeaseError):
+ service.start_acquisition(request)
+ assert runtime.start_calls == []
+ assert control.start_projects == []
+ assert (root / ".current_session").read_text().strip() == interrupted.name
+ else:
+ service.start_acquisition(request)
+ assert len(runtime.start_calls) == 1
+ assert control.start_projects == ["LEASE_RECOVERY"]
+ assert (root / ".current_session").read_text().strip() != interrupted.name
+ assert original_evidence.read_bytes() == b"synthetic interrupted evidence"
+ finally:
+ if owner is not None:
+ owner.release()
+ lease = service._acquisition_session_lease # noqa: SLF001
+ if lease is not None:
+ lease.release()
diff --git a/tests/test_xgrids_active_acquisition_checkpoint_integration.py b/tests/test_xgrids_active_acquisition_checkpoint_integration.py
index 154b31f5..581b1521 100644
--- a/tests/test_xgrids_active_acquisition_checkpoint_integration.py
+++ b/tests/test_xgrids_active_acquisition_checkpoint_integration.py
@@ -272,6 +272,11 @@ def _prepare_and_activate_checkpoint(
service._application_control_session.snapshot = lambda: { # type: ignore[method-assign]
"verified_control": _verified_control(connection)
}
+ # Camera admission now reads the control-only projection. Both projections
+ # must observe the same synthetic dialogue, including later epoch updates.
+ service._application_control_session.snapshot_control_only = ( # type: ignore[method-assign]
+ lambda: service._application_control_session.snapshot() # noqa: SLF001
+ )
service._observe_start_preparation_checkpoint( # noqa: SLF001
"prepared",
context,
@@ -317,9 +322,15 @@ def _prepare_and_activate_checkpoint(
service._observe_application_scanning_checkpoint() # noqa: SLF001
+@pytest.mark.parametrize("prior_rebind", [False, True])
+@pytest.mark.parametrize("standby_committed", [False, True])
+@pytest.mark.parametrize("changed_ip", [False, True])
def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
+ prior_rebind: bool,
+ standby_committed: bool,
+ changed_ip: bool,
) -> None:
"""Fresh READY after Apply settles the old START and its checkpoint.
@@ -340,28 +351,29 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
current = ledger.snapshot().record
assert current is not None
- active_rebind_connection = _connection(
- control_session_id="checkpoint-reset-active-rebind-control",
- host_path_epoch=2,
- producer_generation=2,
- )
- current = ledger.rebind_resolved_active(
- current.operation_id,
- reconciliation_id="checkpoint-reset-active-rebind",
- verified_binding=PhysicalCommandVerifiedBinding(
- verification_id="checkpoint-reset-active-rebind.device-info",
- identity=current.identity,
- connection=active_rebind_connection,
- device_info_message_sha256="2" * 64,
- verified_at_utc="2026-08-13T12:01:00.000Z",
- ),
- observation=_status(
- active_rebind_connection,
- "scanning",
- source="explicit-read-only-reconciliation",
- observed_at_utc="2026-08-13T12:01:01.000Z",
- ),
- )
+ if prior_rebind:
+ active_rebind_connection = _connection(
+ control_session_id="checkpoint-reset-active-rebind-control",
+ host_path_epoch=2,
+ producer_generation=2,
+ )
+ current = ledger.rebind_resolved_active(
+ current.operation_id,
+ reconciliation_id="checkpoint-reset-active-rebind",
+ verified_binding=PhysicalCommandVerifiedBinding(
+ verification_id="checkpoint-reset-active-rebind.device-info",
+ identity=current.identity,
+ connection=active_rebind_connection,
+ device_info_message_sha256="2" * 64,
+ verified_at_utc="2026-08-13T12:01:00.000Z",
+ ),
+ observation=_status(
+ active_rebind_connection,
+ "scanning",
+ source="explicit-read-only-reconciliation",
+ observed_at_utc="2026-08-13T12:01:01.000Z",
+ ),
+ )
for cycle in (1, 2):
retired = ledger.retire_unavailable_target(
retirement_id=f"checkpoint-reset-retirement-{cycle}",
@@ -379,7 +391,7 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
reason="reset-network-intent-read-only-settlement",
)
assert current.stage == "observing"
- assert current.reconciled_physical_state == "active"
+ assert current.reconciled_physical_state == ("active" if prior_rebind else None)
# The persisted ACTIVE checkpoint belongs to the process that owned the
# original receiver. The real failure was observed after a service
@@ -391,6 +403,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
host_path_epoch=4,
producer_generation=4,
)
+ if changed_ip:
+ ready_connection = replace(ready_connection, target_ipv4="192.168.68.51")
coordinator = service._physical_command_coordinator # noqa: SLF001
coordinator.application_response(
ApplicationMqttResponseEvidence(
@@ -435,6 +449,12 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
lambda: None,
)
+ if standby_committed:
+ # The physical READY fsync survived but the checkpoint commit did not.
+ coordinator.reconcile_resolved_active(reconciliation_id="checkpoint-reset-ready-verify.physical")
+ service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
+ trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error"
+ )
result = asyncio.run(
service._reconcile_physical_command_after_verify_owned( # noqa: SLF001
verify_operation_id="checkpoint-reset-ready-verify",
@@ -442,8 +462,8 @@ def test_repeated_reset_reopen_fresh_ready_ceases_old_active_checkpoint(
)
)
- assert result["performed"] is True
- assert result["resolution"] == "physical-standby-observed"
+ assert result["performed"] is (not standby_committed)
+ assert result["resolution"] == (None if standby_committed else "physical-standby-observed")
settled = ledger.snapshot().record
assert settled is not None
assert settled.stage == "resolved"
@@ -1899,6 +1919,67 @@ def test_chained_stop_facade_cessation_uses_real_ledger_ancestry(
assert checkpoint.cessation_physical_proof.operation_id == final_record.operation_id
assert checkpoint.cessation_physical_proof.ancestor_chain == ancestry
+ # A later snapshot may revisit an already durable cessation after a
+ # transient diagnostic failure. Clear only this acquisition's stale reason;
+ # never mutate its journal or hide a different acquisition/trust failure.
+ reason = "active-acquisition-recovery-checkpoint-cease-failed"
+ service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
+ request = dict(
+ expected_acquisition_id=ACQUISITION_ID,
+ expected_start_operation_id=START_OPERATION_ID,
+ evidence_session_id=EVIDENCE_SESSION_ID,
+ expected_stop_operation_id=FINAL_STOP_OPERATION_ID,
+ )
+ assert not service._cease_active_acquisition_checkpoint_from_physical_head( # noqa: SLF001
+ **{**request, "expected_acquisition_id": "other-acquisition"},
+ )
+ assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
+ assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
+ assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
+ assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
+ # Subsequent state polling runs after local receiver/evidence teardown.
+ # It must recognize the same durable terminal, not reintroduce cease-failed.
+ assert service._acquisition is not None # noqa: SLF001
+ service._acquisition = replace(service._acquisition, state="completed") # noqa: SLF001
+ service._acquisition_out_dir = None # noqa: SLF001
+ service._acquisition_stop_operation_id = FINAL_STOP_OPERATION_ID # noqa: SLF001
+ service._set_active_acquisition_checkpoint_reason(reason) # noqa: SLF001
+ for _ in range(2):
+ service._reconcile_acquisition( # noqa: SLF001
+ {"phase": "idle"}, {}, {"state": "completed"},
+ physical_command_proof=service._physical_command_coordinator.snapshot(), # noqa: SLF001
+ )
+ assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
+ assert service._acquisition.state == "completed" # noqa: SLF001
+ assert ActiveAcquisitionRecoveryCheckpointStore(tmp_path).snapshot().checkpoint == checkpoint
+ completed_acquisition = service._acquisition # noqa: SLF001
+ for acquisition_id, start_id in (
+ ("other-acquisition", START_OPERATION_ID),
+ (ACQUISITION_ID, "other-start"),
+ ):
+ service._acquisition = replace( # noqa: SLF001
+ completed_acquisition, acquisition_id=acquisition_id,
+ )
+ service._acquisition_start_operation_id = start_id # noqa: SLF001
+ service._reconcile_acquisition( # noqa: SLF001
+ {"phase": "idle"}, {}, {"state": "completed"},
+ )
+ assert service._active_acquisition_checkpoint_reason == reason # noqa: SLF001
+ service._acquisition = completed_acquisition # noqa: SLF001
+ service._acquisition_start_operation_id = None # noqa: SLF001
+ service._acquisition_stop_operation_id = None # noqa: SLF001
+ service._reconcile_acquisition( # noqa: SLF001
+ {"phase": "idle"}, {}, {"state": "completed"},
+ )
+ assert service._active_acquisition_checkpoint_reason is None # noqa: SLF001
+ service._mark_active_acquisition_checkpoint_untrusted( # noqa: SLF001
+ trust="unavailable", reason_code="active-acquisition-recovery-checkpoint-error",
+ )
+ assert service._cease_active_acquisition_checkpoint_from_physical_head(**request) # noqa: SLF001
+ assert service._active_acquisition_checkpoint_reason == ( # noqa: SLF001
+ "active-acquisition-recovery-checkpoint-error"
+ )
+
def test_restart_ceases_active_checkpoint_after_composite_ordinary_stop(
tmp_path: Path,
diff --git a/tests/test_xgrids_application_mqtt.py b/tests/test_xgrids_application_mqtt.py
index e091fc3d..08cbf6a5 100644
--- a/tests/test_xgrids_application_mqtt.py
+++ b/tests/test_xgrids_application_mqtt.py
@@ -1765,3 +1765,103 @@ def test_close_after_dispatch_precheck_prevents_queued_publish_after_gate_releas
assert fake.publish_calls == []
assert transport.snapshot().publish_attempts == 0
assert evidence.events == []
+
+
+def test_observed_advisory_does_not_break_existing_control_or_grant_start() -> None:
+ clock = FakeClock()
+ fake = FakeControlClient(clock=clock)
+ transport = ReviewedApplicationMqttTransport(
+ "192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
+ )
+ transport.open()
+ fake.events.extend([
+ ("message", (DEVICE_STATUS_TOPIC, _device_status(
+ SessionState.SCANNING, project_bound=True, init_ready=True))),
+ ("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
+ ])
+ transport.maintain_open_for(4.0)
+ assert transport.scan_initialization_complete(_binding()) is True
+ assert transport.pre_start_ready(_binding()) is False
+ assert transport.standby_complete(_binding()) is False
+ snapshot = transport.snapshot().as_dict()
+ assert snapshot["system_error_reports"] == 1
+ assert snapshot["latest_system_error_code"] == 0x12041002
+ assert snapshot["publish_attempts"] == 0
+ fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
+ SessionState.READY, project_bound=False, init_ready=False))))
+ transport.maintain_open_for(4.0)
+ assert transport.standby_complete(_binding()) is True
+ transport.validate_control_proof(_binding())
+ proof = transport.snapshot()
+ clock.now += 100.0
+ fake.events.append(("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))))
+ transport.maintain_open_for(1.0)
+ assert transport.snapshot().control_proof_revision == proof.control_proof_revision
+ with pytest.raises(ApplicationControlProofStale):
+ transport.validate_control_proof(_binding())
+ assert transport.snapshot().publish_attempts == 0
+ transport.close()
+
+
+@pytest.mark.parametrize("code", [0x32040133, 0x12041003, 0x22041002, 0])
+def test_unreviewed_or_fault_report_stays_blocking_after_advisory(code: int) -> None:
+ clock = FakeClock()
+ fake = FakeControlClient(clock=clock)
+ transport = ReviewedApplicationMqttTransport(
+ "192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
+ )
+ transport.open()
+ fake.events.extend([
+ ("message", (DEVICE_STATUS_TOPIC, _device_status(
+ SessionState.SCANNING, project_bound=True, init_ready=True))),
+ ("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, code)))),
+ ("message", (SYSTEM_ERROR_TOPIC, _bytes(15, _uint(1, 0x12041002)))),
+ ])
+ transport.maintain_open_for(4.0)
+ with pytest.raises(ApplicationControlDeviceFault):
+ transport.validate_bound_status(_binding())
+ assert transport.snapshot().as_dict()["publish_attempts"] == 0
+ transport.close()
+
+
+def test_storage_observation_requires_fresh_nonretained_bound_identity():
+ clock = FakeClock()
+ fake = FakeControlClient(clock=clock)
+ transport = ReviewedApplicationMqttTransport(
+ "192.168.1.20", client_factory=lambda: cast(mqtt.Client, fake), monotonic=clock,
+ )
+ transport.open()
+ payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
+ payload += _bytes(7, _uint(4, 1000) + _uint(5, 990))
+ fake.on_message(
+ fake, None, SimpleNamespace(topic=DEVICE_STATUS_TOPIC, payload=payload, retain=True)
+ )
+ assert transport.snapshot().storage_status is None
+ fake.events.append(("message", (DEVICE_STATUS_TOPIC, payload)))
+ transport.maintain_open_for(1.0)
+ assert transport.snapshot().storage_status is None
+ transport.validate_control_proof(_binding())
+ value = transport.snapshot().as_dict()["storage_status"]
+ assert value["used_percent"] == 99.0 and value["observed_at"]
+ value["used_percent"] = 0
+ assert transport.snapshot().storage_status["used_percent"] == 99.0
+ next_payload = _device_status(SessionState.READY, project_bound=False, init_ready=False)
+ next_payload += _bytes(7, _uint(4, 1000) + _uint(5, 980))
+ fake.events.append(("message", (DEVICE_STATUS_TOPIC, next_payload)))
+ transport.maintain_open_for(1.0)
+ # An idle session need not re-run command admission for each display update.
+ assert transport.snapshot().storage_status["used_percent"] == 98.0
+ # Keep protobuf framing valid by constructing the report with a new serial.
+ wrong_identity = (_bytes(1, _text(4, VENDOR_DEVICE_ID))
+ + _uint(2, MODELING_STATE_BASE + SessionState.READY)
+ + _text(3, "other-scanner") + _bytes(7, _uint(4, 1000) + _uint(5, 990)))
+ fake.events.append(("message", (DEVICE_STATUS_TOPIC, wrong_identity)))
+ transport.maintain_open_for(1.0)
+ assert transport.snapshot().storage_status is None
+ fake.events.append(("message", (DEVICE_STATUS_TOPIC, _device_status(
+ SessionState.READY, project_bound=False, init_ready=False))))
+ transport.maintain_open_for(1.0)
+ transport.validate_control_proof(_binding())
+ assert transport.snapshot().storage_status is None
+ assert transport.snapshot().publish_attempts == 0
+ transport.close()
diff --git a/tests/test_xgrids_application_session.py b/tests/test_xgrids_application_session.py
index e6eed33b..ed08dfc0 100644
--- a/tests/test_xgrids_application_session.py
+++ b/tests/test_xgrids_application_session.py
@@ -306,10 +306,13 @@ class FakeExecutor:
observed: Any,
*,
reconciled_active_observed: Any | None = None,
+ standby_work: Callable[[], None] | None = None,
) -> str | None:
self.records.append(f"wait:{event}")
deadline = time.monotonic() + 2.0
while not observed():
+ if standby_work is not None:
+ standby_work()
if (
reconciled_active_observed is not None
and reconciled_active_observed()
@@ -372,8 +375,12 @@ class FakeExecutor:
def maintain_post_stop_until_standby(self) -> None:
self.records.append("wait:device-standby")
- def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
+ def maintain_standby_until_next_acquisition(
+ self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
+ ) -> None:
while not requested():
+ if standby_work is not None:
+ standby_work()
if self.transport.state == "closed":
raise RuntimeError("test transport closed")
if not self.transport.proof_fresh:
diff --git a/tests/test_xgrids_compatibility_profile.py b/tests/test_xgrids_compatibility_profile.py
index a3bfc124..5a76b900 100644
--- a/tests/test_xgrids_compatibility_profile.py
+++ b/tests/test_xgrids_compatibility_profile.py
@@ -58,7 +58,10 @@ def test_xgrids_compatibility_profile_loads_exact_firmware_and_sources() -> None
"bridge": "direct-lan",
"direct-connect": "controller-hotspot",
"quick-connect": "device-ap",
+ "usb": "usb-ethernet",
}
+ assert LOADER.matches_target(profile, firmware="3.0.2", topology="usb-ethernet")
+ assert not LOADER.matches_target(profile, firmware="3.0.3", topology="usb-ethernet")
assert LOADER.matches_target(profile, firmware="3.0.2", topology="direct-lan")
assert LOADER.matches_target(profile, firmware="3.0.2", topology="device-ap")
assert LOADER.matches_target(
diff --git a/tests/test_xgrids_connection_scenario_reset.py b/tests/test_xgrids_connection_scenario_reset.py
index 86012033..83e0e7d3 100644
--- a/tests/test_xgrids_connection_scenario_reset.py
+++ b/tests/test_xgrids_connection_scenario_reset.py
@@ -351,10 +351,14 @@ def test_cold_scenario_reset_is_local_only_and_exact_retry_converges(
"network_write_performed": False,
"automatic_scan": False,
"operation_sequence": 0,
+ "timing": first["connection_scenario_reset"]["timing"],
}
assert first["devices"] == []
assert first["selected_device_id"] is None
assert first["connection_attempt"] is None
+ timing = first["connection_scenario_reset"]["timing"]
+ assert timing["completed_at_utc"]
+ assert all(value >= 0 for key, value in timing.items() if key.endswith("_ms"))
assert first["connection_scenario_reset_pending"] is None
assert service.state()["connection_scenario_reset_pending"] is None
assert first["connection_policy"]["actions"]["scan-ble"]["allowed"] is True
diff --git a/tests/test_xgrids_modeling_control_protocol.py b/tests/test_xgrids_modeling_control_protocol.py
index d8916197..a7a972fb 100644
--- a/tests/test_xgrids_modeling_control_protocol.py
+++ b/tests/test_xgrids_modeling_control_protocol.py
@@ -343,3 +343,25 @@ def test_state_machine_surfaces_faults_without_claiming_save() -> None:
)
assert unknown.phase is AcquisitionPhase.UNKNOWN
assert not unknown.durable_save_complete
+
+
+@pytest.mark.parametrize("system,expected", [
+ (_uint(4, 1001324032) + _uint(5, 991202816), 98.9892167094218),
+ (_uint(4, 1000), 0.0),
+ (_uint(4, 1000) + _uint(5, 1000), 100.0),
+ (b"", None),
+ (_uint(4, 0) + _uint(5, 20), None),
+ (_uint(4, 10) + _uint(5, 20), None),
+ (_uint(4, 10) + _uint(4, 20), None),
+ (_uint(4, 10) + _uint(5, (1 << 64) - 1), None),
+ (_bytes(4, b"wrong-wire"), None),
+ (b"\x20\x80", None),
+])
+def test_optional_storage_ratio_never_changes_modeling_state(system, expected):
+ result = decode_device_status_report(_device_status(SessionState.READY) + _bytes(7, system))
+ assert result.session_state is SessionState.READY
+ assert result.system_status_present
+ if expected is None:
+ assert result.storage_used_percent is None
+ else:
+ assert result.storage_used_percent == pytest.approx(expected, abs=0.0001)
diff --git a/tests/test_xgrids_physical_command_ledger.py b/tests/test_xgrids_physical_command_ledger.py
index dbff63ac..2c7c56eb 100644
--- a/tests/test_xgrids_physical_command_ledger.py
+++ b/tests/test_xgrids_physical_command_ledger.py
@@ -2878,6 +2878,95 @@ def test_repeated_resolved_start_retire_reopen_settles_fresh_ready_as_cessation(
assert settled.reconciliations[-1].original_attempt.operation_id == START_OPERATION
+@pytest.mark.parametrize("observed_state", ["ready", "scanning"])
+@pytest.mark.parametrize("reset_count", [1, 2])
+@pytest.mark.parametrize("proof_fault", [None, "retained", "identity", "old-session"])
+def test_first_successful_start_reset_reopens_without_prior_rebind(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ observed_state: str,
+ reset_count: int,
+ proof_fault: str | None,
+) -> None:
+ """The first reset has no prior reconciliation to supply an active state."""
+ ledger = _ledger(tmp_path, monkeypatch)
+ _prepare_start(ledger)
+ _complete_start(ledger)
+ original = ledger.snapshot().record
+ assert original is not None
+ current = original
+ for cycle in range(reset_count):
+ retired = ledger.retire_unavailable_target(
+ retirement_id=f"first-start-reset-{cycle}",
+ expected_operation_id=current.operation_id,
+ expected_revision=current.revision,
+ expected_transport_ref=current.connection.transport_ref,
+ reason="connection-scenario-reset-by-operator",
+ )
+ current = ledger.reopen_retired_reconciliation(
+ reopening_id=f"first-start-reopen-{cycle}",
+ expected_revision=retired.revision,
+ expected_retirement_id=f"first-start-reset-{cycle}",
+ expected_transport_ref=retired.connection.transport_ref,
+ expected_discovery_generation=40 + cycle,
+ reason="reset-network-intent-read-only-settlement",
+ )
+ assert current.stage == "observing"
+ assert current.reconciled_physical_state is None
+ assert current.reopened_resolved_start_requires_reconciliation
+ connection = _reconciliation_connection()
+ settle = (
+ ledger.observe_resolved_active_standby
+ if observed_state == "ready"
+ else ledger.rebind_resolved_active
+ )
+ binding = _verified_binding(connection=connection)
+ observation = _status(
+ observed_state,
+ connection=connection,
+ source="explicit-read-only-reconciliation",
+ observed_at="2026-08-07T09:34:00.000Z",
+ )
+ if proof_fault == "retained":
+ observation = replace(observation, mqtt_retained=True)
+ elif proof_fault == "identity":
+ binding = replace(binding, identity=replace(IDENTITY, device_serial_sha256="9" * 64))
+ elif proof_fault == "old-session":
+ binding = replace(binding, connection=original.connection)
+ if proof_fault is not None:
+ before = ledger.path.read_bytes()
+ with pytest.raises(PhysicalCommandTransitionError):
+ settle(
+ START_OPERATION,
+ reconciliation_id="first-reset-invalid-state",
+ verified_binding=binding,
+ observation=observation,
+ )
+ assert ledger.path.read_bytes() == before
+ return
+ settled = settle(
+ START_OPERATION,
+ reconciliation_id="first-reset-fresh-state",
+ verified_binding=binding,
+ observation=observation,
+ )
+ assert settled.stage == "resolved"
+ assert settled.resolution == "start-active-observed"
+ assert settled.original_command_outcome == "succeeded"
+ assert settled.reconciled_physical_state == (
+ "standby" if observed_state == "ready" else "active"
+ )
+ assert settled.reconciliations[-1].kind == (
+ "resolved-active-cessation" if observed_state == "ready" else "resolved-active-rebind"
+ )
+ assert settled.operator_retirements[0].original_attempt.as_dict() == (
+ settled.reconciliations[-1].original_attempt.as_dict()
+ )
+ assert settled.application_response == original.application_response
+ assert settled.payload_sha256 == original.payload_sha256
+ assert PhysicalCommandLedger(tmp_path / "repository", clock=_clock).snapshot().record == settled
+
+
def test_legacy_v1_unresolved_attempt_retires_atomically_into_strict_v2(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,