feat(k1): add USB networking, device management and acquisition recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:57 +03:00
parent 14c3c7c2b6
commit 038337783f
78 changed files with 4612 additions and 384 deletions
@@ -1,7 +1,7 @@
import {useEffect,useRef,useState} from 'react';
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import {ActivityIndicator,Button,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import type {SensorEnrollmentProps} from '@mission-core/sensor-sdk';
import {bridgeFormValid,enroll,enrollmentAllowed,connectionAttempt,enrollmentNotice,enrollmentBluetoothFailure,mergeEnrollmentState,enrollmentProof,enrollmentProofCurrent,type EnrollmentProof,type EnrollmentState} from './enrollment';
import {bridgeFormValid,enroll,enrollmentAllowed,connectionAttempt,enrollmentNotice,enrollmentRecoveryNotice,enrollmentBluetoothFailure,mergeEnrollmentState,enrollmentProof,enrollmentProofCurrent,type EnrollmentProof,type EnrollmentState} from './enrollment';
import {K1WifiPasswordField} from '../components/K1WifiPasswordField';
import {revealEnrollment} from './revealEnrollment';
@@ -21,7 +21,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
const [reveal,setReveal]=useState({target:'',revision:0});
const content=useRef<HTMLDivElement>(null);
const lifetime=useRef<AbortController|null>(null);
const running=useRef(false);
const running=useRef<AbortController|null>(null);
useEffect(()=>{
const controller=new AbortController();
@@ -41,11 +41,11 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
}
}
void observe();
return()=>{controller.abort();if(timer)clearTimeout(timer);};
return()=>{controller.abort();running.current?.abort();if(timer)clearTimeout(timer);};
},[transport]);
const attempt=connectionAttempt(state);
const waiting=attempt?.status==='accepted'||attempt?.status==='running';
const waiting=attempt?.status==='accepted'||attempt?.status==='running'||state?.verification?.status==='accepted'||state?.verification?.status==='running';
const notice=state&&(!state.available||state.fresh===false||attempt?.attempt_id!==dismissedAttempt)?enrollmentNotice(state):'';
const bluetoothFailure=!!notice&&enrollmentBluetoothFailure(state);
useEffect(()=>{
@@ -70,15 +70,19 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
return()=>cancelAnimationFrame(frame);
},[reveal]);
async function run(action:'scan'|'networks'|'connect'|'verify'){
if(!state||busy||running.current)return;
running.current=true;
const signal=lifetime.current?.signal;
async function run(action:'scan'|'networks'|'connect'|'verify'|'reset',savedTarget=false){
if(!state||(action==='reset'?busy==='reset'||!enrollmentAllowed(state,'reset'):!!busy||!!running.current))return;
// Supersede only the old UI observer. The canonical reset owns device-runtime cleanup.
running.current?.abort();
const controller=new AbortController();running.current=controller;
const signal=controller.signal;
setBusy(action);setError('');
if(action!=='networks')setVerified(null);
if(action==='scan')setScanned(false);
const parameters=action==='connect'||action==='verify'?{
device_id:device,discovery_generation:state.discovery_generation,mode_revision:state.mode_revision,
const target=savedTarget?state.reconnect_target?.device_id:device;
if(savedTarget&&!target){running.current=null;setBusy('');return;}
const parameters=action==='reset'?{mode_revision:state.mode_revision}:action==='connect'||action==='verify'?{
device_id:target,discovery_generation:state.discovery_generation,mode_revision:state.mode_revision,
...(action==='connect'?{ssid,password}:{}),
}:{};
if(action==='connect')setPassword('');
@@ -89,12 +93,13 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
if(signal?.aborted)return;
onChange();
setState(current=>mergeEnrollmentState(current,{...result,node_id:state.node_id,name:state.name}));
if(action==='reset'){setDevice('');setPassword('');setSSID('');setNetworks([]);setNetwork('manual');setScanned(false);setNeedsScan(false);setDismissedAttempt('');show('');}
if(action==='scan'){
setDevice('');setScanned(true);setNeedsScan(false);
setDismissedAttempt(connectionAttempt(result)?.attempt_id??'');show('devices');
}
if(action==='networks'){setNetworks(result.networks??[]);show('networks');}
if(action==='connect'||action==='verify'){setVerified(enrollmentProof(result,device));setDismissedAttempt('');}
if(action==='connect'||action==='verify'){const proof=enrollmentProof(result,target??'');setVerified(proof);if(proof)setDevice(proof.device);setDismissedAttempt('');}
if(action==='connect'&&enrollmentBluetoothFailure(result)){
setNeedsScan(true);setDevice('');
}
@@ -102,8 +107,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
}catch(cause){
if(!signal?.aborted)setError(cause instanceof Error?cause.message:'Не удалось выполнить действие K1.');
}finally{
running.current=false;
if(!signal?.aborted)setBusy('');
if(running.current===controller){running.current=null;if(!signal.aborted)setBusy('');}
}
}
@@ -117,6 +121,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
}
return renderWindow({busy:pending,
headerActions:state?.can_reset?<IconButton label="Сбросить подключение" title={enrollmentAllowed(state,'reset')?'Сбросить текущую попытку подключения':'Для сброса подключения обновите поддержку K1 на БК'} disabled={!enrollmentAllowed(state,'reset')||busy==='opening'} loading={busy==='reset'} onClick={()=>void run('reset')}><Icon name="refresh"/></IconButton>:undefined,
actions:confirmed?<Button variant="primary" tone="neutral" width="full" disabled={pending}
aria-busy={busy==='opening'} icon={busy==='opening'?<ActivityIndicator size="compact"/>:undefined}
onClick={()=>void configure()}>Настроить устройство</Button>:undefined,
@@ -128,6 +133,11 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
</SettingsCard>
{busy!=='loading'&&!ready?<SettingsCard align="center" title="Служба подключения устройств на БК недоступна"
description="Проверьте связь с бортовым компьютером и работу приложения на нём."/>:ready&&<>
{state?.reconnect_target&&!confirmed&&<SettingsCard title="Сохранённое подключение K1"
description={enrollmentRecoveryNotice(state)} actions={
<Button disabled={pending||!enrollmentAllowed(state,'verify')} aria-busy={busy==='verify'}
icon={busy==='verify'?<ActivityIndicator size="compact"/>:undefined}
onClick={()=>void run('verify',true)}>{busy==='verify'?'Проверяем состояние':'Переподключиться'}</Button>}/>}
<SettingsCard eyebrow="Шаг 01" title="Bluetooth" description="Найдите K1 рядом с бортовым компьютером и выберите его из списка." actions={
<Button disabled={pending||!enrollmentAllowed(state,'scan')} aria-busy={busy==='scan'}
icon={busy==='scan'?<ActivityIndicator size="compact"/>:undefined}
@@ -166,7 +176,7 @@ export function DeviceEnrollmentWindow({transport,onChange,onComplete,renderWind
{notice&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
</SettingsCard></div>}
</>}
{notice&&!selected&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
{notice&&!selected&&!state?.reconnect_target&&!bluetoothFailure&&<div data-enrollment-reveal="result" role="status"><SettingsCard align="center" title={notice}/></div>}
<ToastStack items={error?[{id:'enrollment-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</div>,
});
@@ -5,15 +5,15 @@ import {K1SpatialSession, k1SpatialPhasePresentation} from '../components/K1Spat
import {deviceTelemetry} from '../spatialSessionModel';
import type {AcquisitionState} from '../spatialSessionModel';
import {useEffect,useRef,useState} from 'react';
import {ActivityIndicator,Button,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {perform,type Sensor,type SensorTransport} from './runtime';
import {ActivityIndicator,Button,Description,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {perform} from './runtime';
import {K1LiveView} from './K1LiveView';
import type {RerunHostFactory} from '@mission-core/sensor-sdk';
import type {SensorDetailProps} from '@mission-core/sensor-sdk';
import {K1SceneWindows,type SceneTool} from './K1SceneWindows';
import {useK1SceneSettings} from './useK1SceneSettings';
import {k1ConnectionNotice,k1ManualState,k1Status} from './presentation';
import {k1ConnectionNotice,k1ManualState,k1Status,k1StorageStatus} from './presentation';
export function K1Detail({device,transport,enabled,back,refresh,failure,createRerunHost,reconnect}:{device:Sensor;transport:SensorTransport;enabled:boolean;back:()=>void;refresh:()=>Promise<void>;failure:(error:unknown)=>void;createRerunHost?:RerunHostFactory;reconnect?:()=>void}){
export function K1Detail({hideBack=false,maintenanceBlocked=false,device,transport,enabled,back,backLabel='К устройствам',refresh,failure,createRerunHost,reconnect,previewEnabled=true,sceneProfile}:SensorDetailProps&{hideBack?:boolean;maintenanceBlocked?:boolean}){
const [busy,setBusy]=useState(''),[tool,setTool]=useState<SceneTool|null>(null),[operationError,setOperationError]=useState('');
const [projectName,setProjectName]=useState(''),[projectNameTouched,setProjectNameTouched]=useState(false);
const [mountType,setMountType]=useState<MountType>(SUPPORTED_MOUNT_TYPE),[gnssMode,setGnssMode]=useState<GnssMode>(SUPPORTED_GNSS_MODE);
@@ -21,18 +21,18 @@ export function K1Detail({device,transport,enabled,back,refresh,failure,createRe
const [sceneOpen,setSceneOpen]=useState(['preparing','starting','streaming','stopping'].includes(device.snapshot.acquisition));
const acquisitionId=device.control?.acquisition_id;
useEffect(()=>{if(acquisitionId&&['preparing','starting','streaming','stopping'].includes(device.snapshot.acquisition))setSceneOpen(true);},[acquisitionId]);
const scene=useK1SceneSettings(device,transport,failure);
const scene=useK1SceneSettings(device,transport,failure,sceneProfile);
const running=useRef(false);
const failedAction=useRef('');
const streaming=device.snapshot.acquisition==='streaming';
const manual=k1ManualState(device,enabled),status=k1Status(device,enabled);
const manual=k1ManualState(device,enabled),status=k1Status(device,enabled),storage=k1StorageStatus(device,enabled);
const pending=busy||(['preparing','starting'].includes(device.snapshot.acquisition)?'start':device.snapshot.acquisition==='stopping'?'stop':'');
async function act(action:'start'|'stop'|'verify'){
if(running.current||!enabled)return;
if(running.current||!enabled||(action==='start'&&maintenanceBlocked))return;
if(action==='start'){setProjectNameTouched(true);if(project.error)return;setSceneOpen(true);}
running.current=true;setBusy(action);failedAction.current='';setOperationError('');failure(null);
try{await perform(transport,device,action,action==='verify'?{}:{operator_confirmed:true,control_generation:device.control?.generation,acquisition_id:device.control?.acquisition_id??null,...(action==='start'?{project_name:project.value,mount_type:mountType,gnss_mode:gnssMode}:{})});await refresh();}
catch{failedAction.current=action;setOperationError(action==='start'?'Результат запуска пока не подтверждён.':action==='stop'?'Результат остановки пока не подтверждён.':'Не удалось подтвердить связь с K1. Проверьте питание сканера; если связь не восстановится, откройте подключение устройства и найдите K1 заново.');await refresh().catch(()=>{});}
catch{failedAction.current=action;setOperationError(action==='start'?'Результат запуска пока не подтверждён.':action==='stop'?'Результат остановки пока не подтверждён.':k1ConnectionNotice(device,enabled));await refresh().catch(()=>{});}
finally{running.current=false;setBusy('');}
}
const confirmed=(failedAction.current==='start'&&streaming)||(failedAction.current==='stop'&&device.control?.phase==='completed')||(failedAction.current==='verify'&&manual.connected);
@@ -43,22 +43,23 @@ export function K1Detail({device,transport,enabled,back,refresh,failure,createRe
{manual.showStop&&<Button size="compact" disabled={!manual.connected||!!pending||(!streaming&&!device.control?.can_stop)} aria-busy={pending==='stop'} icon={pending==='stop'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('stop')}><span className="xgrids-k1-spatial-controls__action-label">{pending==='stop'?'Остановка устройства…':'Остановить устройство и запись'}</span></Button>}
</K1SpatialSession>;
return <div className="sensor-content">
<div className="sensor-actions sensor-inventory-toolbar"><Button onClick={back}>К устройствам</Button><StatusBadge tone={status.tone}>{status.label}</StatusBadge></div>
<div className="sensor-actions sensor-inventory-toolbar">{!hideBack&&<Button onClick={back}>{backLabel}</Button>}<StatusBadge tone={status.tone}>{status.label}</StatusBadge></div>
<StatusBadge tone={storage.tone}>{storage.label}</StatusBadge>
<SettingsCard title={device.name} description="Ручной запуск камеры и лидара на бортовом компьютере. Исходные данные записи сохраняются на БК."
actions={manual.connected&&<IconButton label="Настройки устройства" disabled={!!pending} onClick={()=>setTool('display')}><Icon name="settings"/></IconButton>}>
actions={manual.connected&&previewEnabled&&<IconButton label="Настройки устройства" disabled={!!pending} onClick={()=>setTool('display')}><Icon name="settings"/></IconButton>}>
{manual.connected&&!manual.showStop&&<K1AcquisitionFields mountType={mountType} setMountType={setMountType} gnssMode={gnssMode} setGnssMode={setGnssMode}
projectName={projectName} setProjectName={setProjectName} projectNameTouched={projectNameTouched} setProjectNameTouched={setProjectNameTouched} disabled={!!pending}/>}
{manual.connected&&(!manual.showStop||pending==='start')&&<Button variant="primary" tone="neutral" disabled={!!pending||!manual.canStart||!!project.error} aria-busy={pending==='start'}
{manual.connected&&(!manual.showStop||pending==='start')&&<Button variant="primary" tone="neutral" disabled={maintenanceBlocked||!!pending||!manual.canStart||!!project.error} aria-busy={pending==='start'}
icon={pending==='start'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('start')}>{pending==='start'?'Запускаем устройство':'Инициировать запуск'}</Button>}
{manual.showStop&&pending!=='start'&&<Button disabled={!manual.connected||!!pending||(!streaming&&!device.control?.can_stop)} aria-busy={pending==='stop'}
icon={pending==='stop'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('stop')}>{pending==='stop'?'Останавливаем устройство':'Остановить устройство'}</Button>}
{!manual.connected&&device.control?.can_verify&&<Button disabled={!enabled||!!pending} aria-busy={pending==='verify'} icon={pending==='verify'?<ActivityIndicator size="compact"/>:undefined} onClick={()=>void act('verify')}>Проверить состояние K1</Button>}
{!manual.connected&&<p role="status">{summary}</p>}
{!manual.connected&&reconnect&&!manual.active&&<Button disabled={!enabled||!!pending} onClick={reconnect}>Подключить устройство</Button>}
{manual.connected&&!confirmed&&operationError&&<p role="status">{operationError}</p>}
{!manual.connected&&<Description role="status">{summary}</Description>}
{!manual.connected&&reconnect&&!manual.active&&<Button disabled={!enabled||!!pending} onClick={reconnect}>{device.connection_mode==='usb'?'Подключить по Wi-Fi':'Подключить устройство'}</Button>}
{manual.connected&&!confirmed&&operationError&&<Description role="status">{operationError}</Description>}
</SettingsCard>
{manual.connected&&<K1SceneWindows tool={tool} close={()=>setTool(null)} scene={scene} connected={enabled}/>}
{!sceneOpen&&manual.showStop&&<Button onClick={()=>setSceneOpen(true)}>Открыть пространственную сцену</Button>}
{sceneOpen&&createRerunHost&&<K1LiveView device={device} transport={transport} createRerunHost={createRerunHost} enabled={enabled&&streaming} scene={scene} openTool={setTool} close={()=>setSceneOpen(false)} sessionControls={sessionControls}/>}
{previewEnabled&&!sceneOpen&&manual.showStop&&<Button onClick={()=>setSceneOpen(true)}>Открыть пространственную сцену</Button>}
{previewEnabled&&sceneOpen&&createRerunHost&&<K1LiveView device={device} transport={transport} createRerunHost={createRerunHost} enabled={enabled&&streaming} scene={scene} openTool={setTool} close={()=>setSceneOpen(false)} sessionControls={sessionControls}/>}
</div>;
}
@@ -1,3 +1,5 @@
import {useMemo} from 'react';
import {observationRerun} from './observationRerun';
import type {ReactNode} from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { ApplicationPanel, Icon, IconButton, StatusBadge } from '@nodedc/ui-react';
@@ -22,7 +24,9 @@ export function K1LiveView({ device, transport, createRerunHost, enabled, scene,
const [generation, setGeneration] = useState(0), [status, setStatus] = useState<PreviewStatus>(pendingPreview);
const attempts = useRef(0);
const report = useCallback((value: PreviewStatus) => { setStatus(value); }, []);
useK1Preview(device, transport, createRerunHost, spatial, video, report, generation, enabled);
const current=useRef({device,transport,settings:scene.draft,view:'3d'});current.current={device,transport,settings:scene.draft,view:'3d'};
const host=useMemo(()=>observationRerun(createRerunHost,()=>current.current),[createRerunHost]);
useK1Preview(device, transport, host, spatial, video, report, generation, enabled,scene.draft);
useEffect(() => {
if (!status.retry || !enabled)
return;
@@ -68,7 +72,7 @@ export function K1LiveView({ device, transport, createRerunHost, enabled, scene,
<div><span>Точек</span><strong>{status.presented?status.points.toLocaleString('ru-RU'):'—'}</strong></div>
<div><span>До публикации</span><strong>{status.presented&&device.frames?.mqtt_to_publish_ms!=null?device.frames.mqtt_to_publish_ms.toFixed(1):'—'}<small> мс</small></strong></div>
</>}
timeline={!focusedAny&&<ObservationTimeline active={status.presented} sourceCount={visible.size} mode="live-only" accumulationSeconds={scene.draft.accumulationSeconds} onAccumulationChange={accumulationSeconds=>scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
timeline={!focusedAny&&<ObservationTimeline active={status.presented} sourceCount={visible.size} mode="live-only" accumulationMaxSeconds={scene.draft.accumulationMaxSeconds} accumulationSeconds={scene.draft.accumulationSeconds} onAccumulationChange={accumulationSeconds=>scene.stage({accumulationSeconds})} onAccumulationCommit={scene.flush} className="scene-timeline"/>}
media={<FloatingMediaWindow title="K1 · камера справа" subtitle="Видеоканал, опубликованный активным устройством" boundsRef={viewport} rect={cameraRect} maximized={cameraMaximized} active={cameraMaximized} hidden={focused||!visible.has('camera')} onRectChange={setCameraRect} onMaximizedChange={setCameraMaximized} onActivate={()=>{}} onClose={()=>{setCameraMaximized(false);setVisible(current=>{const next=new Set(current);next.delete('camera');return next;});}}
status={<span className="floating-observation-window__status">{status.cameraPresented?'Эфир':'Ожидание'}</span>}
footer={<span className="floating-observation-window__footer"><span>Бортовой компьютер</span><span>Эфир без буфера</span></span>}>
@@ -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; }
@@ -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<string[]>([]);
const [confirmation,setConfirmation]=useState<Confirmation|null>(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 <div className="sensor-content">
<SettingsCard title="Режим USB" description={m.info?`Текущий режим: ${m.info.usb_mode==='storage'?'USB-накопитель':'канал управления (USB Ethernet)'}.`:'Режим устройства ещё не подтверждён.'}>
<div className="k1-management-mode">
<Select label="Режим USB" variant="split" value={mode} onChange={setMode} disabled={!m.canManage}
options={[{value:'data',label:'Канал управления (USB Ethernet)'},{value:'storage',label:'USB-накопитель'}]}/>
<Button disabled={!m.canManage||mode===m.info?.usb_mode||(mode==='storage'&&!m.canSwitchToStorage)} onClick={()=>setConfirmation({operation:mode==='storage'?'usb-storage':'usb-data',title:'Изменить режим USB?',description:mode==='storage'?'В режиме USB-накопителя сканирование недоступно. Для новой съёмки верните канал управления.':'K1 вернётся в режим канала управления по USB Ethernet.'})}>Инициализировать режим</Button>
</div>
{!m.canSwitchToStorage&&<Description>Режим USB-накопителя отключает канал управления по USB. Для переключения и возврата подключите K1 через Bridge. Список проектов доступен без смены режима.</Description>}
<Button disabled={!m.ready||!!m.busy} onClick={()=>void m.run('info')}>Обновить состояние</Button>
</SettingsCard>
{storage?<SettingsCard title={label} description="Проекты на самом сканере. Список и удаление — через канал управления, без перехода в режим USB-накопителя.">
<div className="sensor-actions">
<Checker label="Выбрать все" checked={!!projects.length&&selected.length===projects.length} disabled={!m.canManage||!projects.length} onChange={checked=>setSelected(checked?projects.map(p=>p.id):[])}/>
<Button disabled={!m.canManage} onClick={()=>void m.run('projects')}>Обновить список</Button>
<Button disabled={!m.canManage||!selected.length} onClick={()=>askDelete(projects.filter(p=>selected.includes(p.id)))}>Удалить выбранное</Button>
</div>
<ResourceList>{projects.map(project=><li key={project.id}><ResourceRow title={<Checker label={project.name} checked={selected.includes(project.id)} disabled={!m.canManage} onChange={checked=>setSelected(values=>checked?[...values,project.id]:values.filter(id=>id!==project.id))}/>}
actions={<IconButton label={`Удалить ${project.name}`} disabled={!m.canManage} onClick={()=>askDelete([project])}><Icon name="trash"/></IconButton>}/></li>)}</ResourceList>
{m.catalog&&!projects.length&&<Description>На K1 нет проектов.</Description>}
{!m.catalog&&!m.busy&&<Description>Обновите список проектов.</Description>}
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'format-storage',title:'Очистить диск K1?',description:'Все данные основного хранилища K1 будут удалены форматированием. Это действие нельзя отменить.'})}>Очистить диск</Button>
</SettingsCard>:<SettingsCard title="Питание устройства">
<div className="sensor-actions">
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'reboot',title:'Перезагрузить K1?',description:'Связь со сканером временно прервётся. Бортовой компьютер останется включённым.'})}>Перезагрузить устройство</Button>
<Button disabled={!m.canManage} onClick={()=>setConfirmation({operation:'power-off',title:'Выключить K1?',description:'Для следующего включения потребуется кнопка питания на сканере. Бортовой компьютер останется включённым.'})}>Выключить устройство</Button>
</div>
</SettingsCard>}
{!m.ready&&<Description role="status">Обслуживание доступно при подтверждённом подключении и после завершения съёмки K1.</Description>}
{m.busy&&<Description role="status"><ActivityIndicator size="compact"/> Ожидаем ответ K1…</Description>}
{m.message&&<Description role="status">{m.message}</Description>}
<ConfirmationModal open={!!confirmation} title={confirmation?.title??''} description={confirmation?.description??''}
danger={confirmation?.operation==='delete-projects'||confirmation?.operation==='format-storage'} onClose={()=>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');}}/>
</div>;
}
@@ -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<HTMLDivElement>(null),plan=useRef<HTMLDivElement>(null),video=useRef<HTMLVideoElement>(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<HTMLDivElement>(null),viewport=useRef<HTMLDivElement>(null),video=useRef<HTMLVideoElement>(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(<div className="observation-source">
<ObservationHeader targets={view} live={live} label={live?'Прямой эфир':points?status.lidar:status.camera}>{status.retry&&<IconButton label="Повторить подключение K1" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton>}</ObservationHeader>
<div className="observation-source__media">{points?<div className="observation-rerun" ref={view.id==='plan'?plan:spatial}/>:<video ref={video} autoPlay muted playsInline aria-label={`${device.name} Cam Right`} data-live={live}/>}</div>
</div>,view.target,view.id);})}</>;
const native=useK1Preview(device,transport,host,spatial,video,report,generation,props.enabled,scene.draft);
const playback=useLiveRerunPlayback(native,device.control?.acquisition_id??device.snapshot.context.session_id);
useEffect(()=>{if(!status.retry)return;const timer=setTimeout(()=>setGeneration(v=>v+1),5000);return()=>clearTimeout(timer);},[status.retry,generation]);
const configure=()=>props.configure?.(view.id);
return <div className="observation-source k1-observation-scene" data-k1-history={JSON.stringify(playback.state)}>
<ObservationHeader targets={view} live={status.presented} waiting={!status.presented} label={status.lidar}><K1ObservationAction device={device} fresh={props.enabled&&props.fresh!==false} configure={configure} stop={props.stop} pending={props.pending}/><IconButton label="Следовать за K1" aria-pressed={scene.draft.followTrajectory??false} onClick={()=>scene.commit({followTrajectory:!scene.draft.followTrajectory})}><Icon name="target"/></IconButton></ObservationHeader>
<SpatialScene viewportRef={viewport}
renderer={<><div className="rerun-viewport" data-status={status.hasScene?'ready':'loading'}><div className="rerun-viewport__canvas" data-presented={status.hasScene?'true':'false'} ref={spatial}/></div>
{!status.hasScene&&<EmptySpatialStage settings={scene.draft} title="Ожидаем данные K1" detail="Пространственная сцена появится после получения облака точек."/>}</>}
status={{tone:status.presented?'success':'warning',pulse:!status.presented,label:status.presented?'Визуализатор готов':status.lidar}}
overlays={range&&status.hasScene?<div className="scene-height-slice"><RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??range.min,ceiling??range.max]} min={range.min} max={range.max} step="any"
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
onChange={value=>{const next=heightSlice(value,[range.min,range.max]);scene.commit({heightFloor:next.floor,heightCeiling:next.ceiling});}}/></div>:null}
timeline={<ObservationTimeline className="scene-timeline" active={status.presented} sourceCount={1} mode="buffered" seekable={!!playback.state.rangeNs}
rangeNs={playback.state.rangeNs} currentNs={playback.state.currentNs} playing={playback.state.playing} followingLive={playback.state.live}
onSeek={playback.seek} onPlayingChange={playback.setPlaying} onJumpToEnd={playback.jumpToLive}
accumulationSeconds={scene.draft.accumulationSeconds} accumulationMaxSeconds={scene.draft.accumulationMaxSeconds} onAccumulationChange={value=>scene.stage({accumulationSeconds:value})} onAccumulationCommit={scene.flush}/> }
metrics={<><div><span>КАДР/С</span><strong>{status.presented?(device.frames?.pcl_fps??0).toFixed(1):'—'}</strong></div><div><span>Точек</span><strong>{status.presented?status.points.toLocaleString('ru-RU'):'—'}</strong></div></>}
/>
</div>;
}
function CameraPane({view,...props}:ActiveProps&{view:SensorObservationProps['views'][number]}){
const video=useRef<HTMLVideoElement>(null),[generation,setGeneration]=useState(0);
const status=useK1CameraPreview(props.device,props.transport,video,props.enabled,generation);
return <div className="observation-source"><ObservationHeader targets={view} live={status.cameraPresented} label={status.camera}><K1ObservationAction device={props.device} fresh={props.enabled&&props.fresh!==false} configure={()=>props.configure?.(view.id)} stop={props.stop} pending={props.pending}/><IconButton label="Обновить изображение K1" onClick={()=>setGeneration(v=>v+1)}><Icon name="refresh"/></IconButton></ObservationHeader>
<div className="observation-source__media k1-camera-content"><video ref={video} autoPlay muted playsInline aria-label={`${props.device.name} Cam Right`} style={{visibility:status.cameraPresented?'visible':'hidden'}}/>
</div>
{!status.cameraPresented&&<p className="observation-source__notice" role="status">{status.camera}</p>}</div>;
}
function ActiveK1Observation(props:ActiveProps){return <>{props.views.map(view=>createPortal(view.id==='camera'?<CameraPane {...props} view={view}/>:<PointPane {...props} view={view}/>,view.target,view.id))}</>;}
export function K1Observation(props:SensorObservationProps){
if(!props.enabled||props.device.snapshot.acquisition!=='streaming')return <>{props.views.map(view=>createPortal(<div className="observation-source"><ObservationHeader targets={view} live={false} label={props.enabled?'Просмотр остановлен':'Нет связи с источником'}/><p className="observation-source__notice">Начните приём данных в конфигураторе K1.</p></div>,view.target,view.id))}</>;
return <ActiveK1Observation {...props}/>;
const [pending,setPending]=useState(false),[error,setError]=useState('');
const stopping=useRef(false);
const stop=async()=>{
if(stopping.current||!props.enabled||props.fresh===false||!props.device.control?.can_stop)return;
stopping.current=true;setPending(true);setError('');
try{await perform(props.transport,props.device,'stop',{operator_confirmed:true,control_generation:props.device.control?.generation,acquisition_id:props.device.control?.acquisition_id??null});}
catch{setError('Остановка K1 пока не подтверждена. Проверьте состояние устройства.');}
finally{stopping.current=false;setPending(false);}
};
const toast=<ToastStack items={error?[{id:'k1-observation-stop',tone:'error',title:error}]:[]} onDismiss={()=>setError('')}/>;
const fresh=props.enabled&&props.fresh!==false,manual=k1ManualState(props.device,fresh);
const label=!manual.connected?'Нет связи с K1':props.device.snapshot.acquisition==='stopping'?'Завершение сканирования':manual.active?'Подготовка сканирования':manual.canStart?'Готов к сканированию':'Подключён';
// A link gap pauses the existing preview hook; it must not destroy that
// acquisition's native recording, accumulated geometry or resume cursor.
if(props.device.snapshot.acquisition!=='streaming')return <>{toast}{props.views.map(view=>createPortal(<div className="observation-source">
<ObservationHeader targets={view} live={false} waiting={manual.active} label={label}><K1ObservationAction device={props.device} fresh={fresh} configure={()=>props.configure?.(view.id)} stop={()=>void stop()} pending={pending}/></ObservationHeader>
<div className="observation-source__notice"><Description>{manual.connected?(manual.active?'Состояние сканирования доступно в управлении K1.':'Активируйте устройство кнопкой Play в шапке вьюпорта.'):k1ConnectionNotice(props.device,props.fresh!==false)}</Description>
{!manual.connected&&!manual.active&&props.reconnect&&<Button onClick={props.reconnect}>Подключить K1</Button>}
</div>
</div>,view.target,view.id))}</>;
return <>{toast}<ActiveK1Observation {...props} stop={()=>void stop()} pending={pending}/></>;
}
@@ -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 <IconButton label="Остановить сканирование K1" loading={pending||device.snapshot.acquisition==='stopping'}
disabled={!manual.connected||!device.control?.can_stop||!stop} onClick={stop}><Icon name="stop"/></IconButton>;
if(!configure)return null;
return <IconButton label="Начать сканирование K1" disabled={!manual.canStart} onClick={configure}><Icon name="play"/></IconButton>;
}
@@ -10,7 +10,13 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
connected: boolean;
}) {
const title = tool === 'source' ? 'Визуальный движок' : tool === 'layers' ? 'Слои сцены' : 'Отображение';
return <Window open={tool !== null} title={title} placement="end" draggable closeOnBackdrop={false} closeOnEscape={false} lockBodyScroll={false} trapFocus={false} className={`scene-tool-window scene-tool-window--${tool === 'source' ? 'source' : tool === 'layers' ? 'layers' : 'display'}`} onClose={() => { scene.flush(); close(); }}>
return <Window open={tool !== null} title={title} placement="center" closeOnBackdrop={false} className={`scene-tool-window scene-tool-window--${tool === 'source' ? 'source' : tool === 'layers' ? 'layers' : 'display'}`} onClose={() => { scene.flush(); close(); }}>
<K1SceneControls tool={tool} scene={scene} connected={connected}/>
</Window>;
}
export function K1SceneControls({tool,scene,connected}:{tool:SceneTool|null;scene:K1SceneState;connected:boolean}) {
return <>
{tool === 'display' && <SceneDisplayControls displayDraft={scene.draft} stageDisplayPatch={scene.stage} commitDisplayPatch={scene.commit} flushDisplaySettings={scene.flush}/>}
{tool === 'layers' && <SceneLayerControls sceneSettings={scene.draft} pending={scene.pending} applyScenePatch={scene.commit}/>}
{tool === 'source' && <Inspector defaultOpen={['connection']} singleOpen sections={[{ id: 'connection', label: 'Подключение', description: 'Живые данные с бортового компьютера', content: <div className="inspector-control-stack">
@@ -19,5 +25,5 @@ export function K1SceneWindows({ tool, close, scene, connected }: {
<ControlRow label="Режим">Живой просмотр</ControlRow>
<p className="scene-window-note">Потоки открываются автоматически после запуска устройства. Запись сохраняется на бортовом компьютере.</p>
</div> }]}/>}
</Window>;
</>;
}
@@ -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 <FeatureSettingsWindow open title={`Настройки · ${props.device.name}`}
identity={{title:props.device.name,subtitle:props.device.connection_label,avatarLabel:'K1'}}
sections={[
{id:'connection',label:'Текущее подключение',icon:'network'},
{id:'storage',label:'Локальное хранилище',icon:'folder'},
{id:'layers',label:'Слои',icon:'layers',disabled:!connected},
{id:'display',label:'Отображение',icon:'sliders',disabled:!connected},
]} activeSection={section} onSectionChange={value=>{scene.flush();setSection(value);}} onClose={close}>
<div hidden={section!=='connection'} className={section==='connection'?'sensor-content':undefined}><K1Detail {...props} hideBack previewEnabled={false} back={close}
maintenanceBlocked={!!management.busy||management.info?.usb_mode==='storage'}/>
{section==='connection'&&<K1ManagementControls management={management}/>}</div>
{section==='storage'&&<K1ManagementControls management={management} storage/>}
{(section==='layers'||section==='display')&&<K1SceneControls tool={section} scene={scene} connected={connected}/>}
</FeatureSettingsWindow>;
}
@@ -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;
}
@@ -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)); }
@@ -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();};
}
@@ -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<HTMLDivElement|null>):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<LiveRerunViewer['open_channel']>|null=null,secondaryBlueprint:ReturnType<LiveRerunViewer['open_channel']>|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<typeof viewer.open_channel>|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()<retryAt)return applied?id:null;
busy=true;recording=id;timing.requests++;timing.started_ms=Math.round(performance.now()-began);report();
const eye=applied?viewer.get_camera_eye?.():null;
void perform<{rrd:string}>(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<typeof viewer.start>)=>{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(()=>{});}}};
};
}
@@ -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`}]},
};
@@ -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'};
}
@@ -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; },
@@ -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');
}
@@ -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<HTMLVideoElement|null>,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<typeof setInterval>|undefined,ice:ReturnType<typeof setTimeout>|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<void>((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;
}
@@ -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<ManagementResult|null>(null),[catalog,setCatalog]=useState<ManagementResult|null>(null);
const [busy,setBusy]=useState<ManagementOperation|null>(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<ManagementResult>(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<typeof useK1Management>;
@@ -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<HTMLDivElement | null>, video: RefObject<HTMLVideoElement | null>, onStatus: (value: PreviewStatus) => void, generation = 0, enabled = true) {
export function useK1Preview(device: Sensor, transport: SensorTransport, createRerunHost: RerunHostFactory, spatial: RefObject<HTMLDivElement | null>, video: RefObject<HTMLVideoElement | null>, 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<PreviewStatus>(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<string,number>}>({at:performance.now(),stages:{}});
const stamp = (name:string) => { startup.current.stages[name] ??= Math.round(performance.now()-startup.current.at); };
const [native, setNative] = useState<LiveRerunViewer | null>(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<string,number>={};
const mark=(name:string)=>{stages[name]??=Math.round(performance.now()-startedAt);};
let keepalive: ReturnType<typeof setInterval> | undefined, follow: ReturnType<typeof setInterval> | undefined, iceTimeout: ReturnType<typeof setTimeout> | undefined;
let status = { ...pendingPreview, hasScene: view.hasScene };
const update = (patch: Partial<PreviewStatus>) => { 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<string, unknown>; 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<string,unknown>={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<void>((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;
}
@@ -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<string, unknown> = {}): 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<SceneSettings>) => { 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) {
+1 -1
View File
@@ -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",
@@ -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",
+1
View File
@@ -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"] },
+8
View File
@@ -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():
@@ -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"
}
]
},