feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import './roverLogs.css';
|
||||
|
||||
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
|
||||
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
|
||||
const [local,setLocal]=useState({enabled:true,preview:true});
|
||||
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
|
||||
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
|
||||
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
<div className="rover-dev-options">
|
||||
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
|
||||
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
|
||||
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
|
||||
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
|
||||
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
|
||||
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
|
||||
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
|
||||
</SettingsCard>
|
||||
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './roverLogs.css';
|
||||
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
|
||||
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
|
||||
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
|
||||
return <>
|
||||
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
|
||||
<div className="rover-logs">
|
||||
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
|
||||
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
|
||||
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
|
||||
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
|
||||
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
|
||||
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>}
|
||||
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
|
||||
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
|
||||
</div>
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverState} from '../../core/fleet/useRoverControl';
|
||||
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
|
||||
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
|
||||
export function RoverTelemetry({state}:{state:RoverState}){
|
||||
export function roverTelemetryTable(state:RoverState){
|
||||
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
|
||||
const positions=drivePositions(profile?.layout??null);
|
||||
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
|
||||
@@ -9,17 +11,19 @@ export function RoverTelemetry({state}:{state:RoverState}){
|
||||
reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid),
|
||||
}));
|
||||
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
|
||||
return <div className="rover-telemetry">
|
||||
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{
|
||||
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined;
|
||||
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span>
|
||||
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div>
|
||||
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div>
|
||||
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div>
|
||||
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div>
|
||||
<div><dt>Контроллер</dt><dd>{number(v?.mos_temperature_c)} °C</dd></div>
|
||||
<div><dt>Ошибка VESC</dt><dd>{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}</dd></div></dl>
|
||||
</section>;
|
||||
})}
|
||||
</div>;
|
||||
const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
|
||||
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
|
||||
return {
|
||||
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
|
||||
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
|
||||
...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
|
||||
};
|
||||
}
|
||||
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
|
||||
const table=roverTelemetryTable(state);
|
||||
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
}
|
||||
|
||||
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
|
||||
|
||||
@@ -1,45 +1,63 @@
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
|
||||
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './rover.css';
|
||||
const Scene=lazy(()=>import('./editor/RoverScene'));
|
||||
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
|
||||
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
|
||||
|
||||
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
|
||||
export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
|
||||
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||
const focusAfterArm=useRef(false);
|
||||
useEffect(()=>{
|
||||
if(open||!focusAfterArm.current)return;
|
||||
focusAfterArm.current=false;
|
||||
// Window restores its opener on close. Transfer input after that cleanup,
|
||||
// once only, without taking focus back from another window or dialog.
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[open,active]);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
|
||||
useEffect(()=>{if(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||
useEffect(()=>{if(!active)stop();},[active,stop]);
|
||||
useEffect(()=>{
|
||||
if(!c.ready||!active||open||editing||!stage.current)return;
|
||||
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
|
||||
const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
|
||||
const binding=bindRoverHoldInput(scope,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop,trace:(event,data)=>roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,event,data)});
|
||||
input.current=binding;c.setInputGuard(binding.valid);
|
||||
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
|
||||
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
|
||||
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
|
||||
const preparing=c.pending||(c.armed&&!c.ready);
|
||||
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
|
||||
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||
const preparing=c.recovering||c.pending||(c.armed&&!c.ready);
|
||||
const duty=c.controlMode!=='rpm';
|
||||
const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits);
|
||||
const currentDescription=limits.length?limits.map(d=>`${d.label}: до ${d.current_limits!.motor_a.toLocaleString('ru-RU',{maximumFractionDigits:2})} А`).join('; ')+'. Выбранный предел ограничивает тягу; настройки VESC сохраняются.':'Предел тяги. Каждый мотор также ограничен своей конфигурацией VESC.';
|
||||
const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000;
|
||||
const observing=observation??roverObservationStatus(c.state,c.connection);
|
||||
const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null);
|
||||
const tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||
const running=c.armed||c.pending||c.recovering;
|
||||
return <>
|
||||
{createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
|
||||
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
{createPortal(<><IconButton label={running?"Остановить управление":"Включить управление"} aria-pressed={running||open} onClick={running?stop:showSettings}><Icon name={running?'stop':'play'}/></IconButton><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
|
||||
{createPortal(<><StatusBadge variant="indicator" tone={editing?'neutral':tone} pulse={!editing&&(preparing||observing.pulse)} aria-label={editing?'Редактирование сцены':status}/><h3 className="rover-view__title" title={status}>{editing?'Редактирование сцены':status}</h3></>,header.statusTarget)}
|
||||
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
|
||||
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
|
||||
{c.ready&&!editing&&<div className="rover-view__controls">
|
||||
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
|
||||
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
|
||||
@@ -51,20 +69,17 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
|
||||
</div>
|
||||
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
|
||||
</div>}
|
||||
{!editing&&<div className="rover-view__authority">
|
||||
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(e.target.value)}))}/>
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={settings.maxErpm} onChange={e=>setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/>
|
||||
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/>
|
||||
{availability&&<StatusBadge tone="warning">{availability}</StatusBadge>}
|
||||
<p>Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!confirmed||!c.canArm||!(settings.currentA>=.5&&settings.currentA<=30&&settings.maxErpm>=300&&settings.maxErpm<=3000)} loading={c.pending}
|
||||
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
|
||||
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
|
||||
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
|
||||
</div></Window>
|
||||
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
|
||||
</>;
|
||||
|
||||
@@ -20,7 +20,7 @@ export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:s
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
|
||||
</LoadingRegion>
|
||||
{editing&&<>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
|
||||
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
|
||||
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
|
||||
</>}
|
||||
|
||||
@@ -2,19 +2,11 @@
|
||||
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
|
||||
.rover-view .rover-view__scene { position:absolute; inset:0; }
|
||||
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
|
||||
.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); }
|
||||
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
|
||||
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; }
|
||||
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
|
||||
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
|
||||
.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; }
|
||||
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
|
||||
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
|
||||
@container (max-width: 380px) {
|
||||
.rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
|
||||
}
|
||||
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
|
||||
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||
.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); }
|
||||
.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); }
|
||||
.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); }
|
||||
.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; }
|
||||
.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
|
||||
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
|
||||
.rover-logs__entries {flex:1;min-height:0;overflow:auto;}
|
||||
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
|
||||
|
||||
.rover-dev-options {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
|
||||
.rover-dev-options .nodedc-settings-card__body {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
|
||||
|
||||
.rover-logs__actions {display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
@@ -38,6 +38,10 @@ export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|
|
||||
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
|
||||
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
|
||||
};
|
||||
if(layout.arrangement==='auto' && !Object.keys(layout.splits).length && ids.includes('telemetry') && ids.length>=3){
|
||||
const other=ids.filter(id=>id!=='telemetry');
|
||||
return {axis:'x',ratio:65,first:build(other.slice(0,-1))!,second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:other.at(-1)!}}};
|
||||
}
|
||||
return build(ids);
|
||||
}
|
||||
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import {sameConfiguration} from './configurationEquality';
|
||||
|
||||
const queues=new Map<string,Promise<unknown>>();
|
||||
/** A pending save survives unmount. The next mount reads only after its ACK. */
|
||||
export function observationSerial<T>(key:string,work:()=>Promise<T>):Promise<T>{
|
||||
const previous=queues.get(key)??Promise.resolve();
|
||||
const next=previous.catch(()=>{}).then(work);queues.set(key,next);
|
||||
void next.finally(()=>{if(queues.get(key)===next)queues.delete(key);}).catch(()=>{});
|
||||
return next;
|
||||
}
|
||||
const object=(v:unknown):v is Record<string,unknown>=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
||||
/** Three-way merge: unrelated fields survive; arrays and conflicting leaves are atomic. */
|
||||
export function mergeObservation<T>(base:T,local:T,remote:T):{value:T;conflicts:string[]}{
|
||||
const conflicts:string[]=[];
|
||||
function merge(b:unknown,l:unknown,r:unknown,path:string):unknown{
|
||||
if(sameConfiguration(l,b))return r;
|
||||
if(sameConfiguration(r,b)||sameConfiguration(l,r))return l;
|
||||
if(object(b)&&object(l)&&object(r)){
|
||||
const result:Record<string,unknown>={};
|
||||
for(const key of new Set([...Object.keys(b),...Object.keys(l),...Object.keys(r)])){
|
||||
const value=merge(b[key],l[key],r[key],path?path+'.'+key:key);
|
||||
if(value!==undefined)result[key]=value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
conflicts.push(path);return l;
|
||||
}
|
||||
return {value:merge(base,local,remote,'') as T,conflicts};
|
||||
}
|
||||
export interface ObservationReceipt<T>{revision:number;document:T|null;writable:boolean}
|
||||
export async function saveObservation<T>(revision:number,base:T,local:T,read:()=>Promise<ObservationReceipt<T>>,write:(revision:number,value:T)=>Promise<ObservationReceipt<T>>,normalize:(value:T|null)=>T){
|
||||
let payload=local;
|
||||
for(let attempt=0;attempt<2;attempt++){
|
||||
try{return {receipt:await write(revision,payload),document:payload};}
|
||||
catch(error){
|
||||
// Read after any failed ACK, including timeout. Identity/equality can prove
|
||||
// an already committed write without retrying it or incrementing revision.
|
||||
const latest=await read();if(!latest.writable)throw error;
|
||||
const remote=normalize(latest.document);
|
||||
if(sameConfiguration(remote,payload))return {receipt:latest,document:remote};
|
||||
const merged=mergeObservation(base,payload,remote);
|
||||
if(merged.conflicts.length)throw Error('Раскладка изменена в другом окне. Черновик сохранён: можно загрузить бортовую версию или применить свой черновик.');
|
||||
if(attempt===1)throw error;
|
||||
revision=latest.revision;base=remote;payload=merged.value;
|
||||
}
|
||||
}
|
||||
throw Error('Подтверждение сохранения не получено.');
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Opt-in bounded queues on the operator host. Never awaited by motor transport. */
|
||||
type Row=Record<string,unknown>;
|
||||
export class BrowserEvidence {
|
||||
id:string|null=null;rows:Row[]=[];busy=false;dropped=0;
|
||||
constructor(readonly url:string,readonly local=false){}
|
||||
set(id:string|null){if(this.id!==id){this.rows=[];this.dropped=0;this.id=id;}}
|
||||
record(event:string,data:Row={}){
|
||||
if(!this.id)return;
|
||||
const row={event,browser_ms:performance.now(),...data};
|
||||
if(JSON.stringify(row).length>2048){this.dropped++;return;}
|
||||
if(this.rows.length>=256){this.rows.shift();this.dropped++;}
|
||||
this.rows.push(row);
|
||||
}
|
||||
async flush(){
|
||||
if(this.busy||!this.id||!this.rows.length)return;
|
||||
const id=this.id,rows=this.rows.splice(0,32);this.busy=true;
|
||||
try{const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(2000),keepalive:true});
|
||||
if(!r.ok)throw Error('trace');
|
||||
if(this.local&&(await r.json()).accepted!==true&&id===this.id)this.set(null);
|
||||
}
|
||||
catch{if(id===this.id){const pending=[...rows,...this.rows];this.dropped+=Math.max(0,pending.length-256);this.rows=pending.slice(-256);}}
|
||||
finally{this.busy=false;}
|
||||
}
|
||||
}
|
||||
const sessions=new Map<string,{remote:BrowserEvidence;local:BrowserEvidence;preview:boolean}>();
|
||||
export function roverDevEvent(url:string,event:string,data:Row={}){try{const pair=sessions.get(url);pair?.remote.record(event,data);pair?.local.record(event,data);}catch{/* No change to input authority. */}}
|
||||
/** Camera metrics never enter the optional WAN recorder. */
|
||||
export function roverPreviewEvidence(url:string,sample:Row){try{const pair=sessions.get(url);if(pair?.preview)pair.local.record('preview',{sample});}catch{/* No preview/control side effect. */}}
|
||||
export function connectRoverEvidence(url:string){
|
||||
const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true};sessions.set(url,pair);
|
||||
const timer=setInterval(()=>{for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush();}},250);
|
||||
return {set(id:string|null,localID:string|null=null,preview=true){pair.preview=preview;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});},
|
||||
async flush(){for(const e of [pair.remote,pair.local])for(let n=0;n<9&&e.rows.length;n++){if(e.busy)await new Promise(r=>setTimeout(r,25));else await e.flush();}},
|
||||
close(){clearInterval(timer);for(const e of [pair.remote,pair.local])void e.flush();if(sessions.get(url)===pair)sessions.delete(url);}};
|
||||
}
|
||||
|
||||
export function roverEvidenceForeground(){try{return typeof document!=='undefined'&&!document.hidden&&document.hasFocus();}catch{return false;}}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
/** Opening a view reads state; only a new failure produces an event toast. */
|
||||
export class RoverFaultNotice {
|
||||
private baseline=false;
|
||||
private key='';
|
||||
private message='';
|
||||
update(value:RoverState,ownedSession:string|null):{show?:string;clear?:string}{
|
||||
if(!value.fresh)return {};
|
||||
const s=value.snapshot,message=s.state==='fault'?s.message??'':'';
|
||||
const key=message?JSON.stringify([s.instance,s.session_id,message]):'';
|
||||
const changed=key!==this.key;
|
||||
const show=changed&&message&&(this.baseline||!!ownedSession)?message:undefined;
|
||||
const clear=changed&&this.message?this.message:undefined;
|
||||
this.baseline=true;this.key=key;this.message=message;
|
||||
return {show,clear};
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,53 @@
|
||||
import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput';
|
||||
|
||||
// The network heartbeat is not evidence that a physical key is still held.
|
||||
// Allow the initial OS repeat delay, then require continuing keyboard evidence.
|
||||
export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300;
|
||||
// Key state is keydown/keyup, independent of OS autorepeat (which may
|
||||
// stop for the remaining key after releasing the last key in a chord).
|
||||
// Focus/visibility revoke input; Core and Node independently expire heartbeat.
|
||||
export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
trace?:(event:string,data:Record<string,unknown>)=>void;
|
||||
held:(keys:Set<string>)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void;
|
||||
},now:()=>number=()=>performance.now()){
|
||||
}){
|
||||
const doc=scope.ownerDocument,win=doc.defaultView!;
|
||||
const keyboard=new Set<string>(),pointers=new Map<number,string>();
|
||||
let deadline=0,closed=false,suspended=false;
|
||||
const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());};
|
||||
const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();};
|
||||
const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();};
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement);
|
||||
let closed=false,suspended=false;
|
||||
const trace=(event:string,data:Record<string,unknown>={})=>{try{callbacks.trace?.(event,{mode,held:[...keyboard,...pointers.values()],...data});}catch{}};
|
||||
const clear=()=>{keyboard.clear();pointers.clear();callbacks.held(new Set());};
|
||||
const pause=(reason:unknown="contextmenu")=>{if(closed||suspended)return;trace("pause",{reason:typeof reason==="string"?reason:"contextmenu"});suspended=true;clear();callbacks.pause();};
|
||||
const stop=()=>{if(closed)return;trace("stop",{reason:"operator_or_pagehide"});closed=true;clear();callbacks.stop();};
|
||||
// Armed authority belongs to the visible observation center, not one canvas.
|
||||
// Modal focus returns to its header Play button; browser chrome can return it
|
||||
// to body. Neither should require a canvas click before a NEW physical press.
|
||||
const editable='input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role=dialog],[role=listbox],[role=menu]';
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()
|
||||
&&(scope.contains(doc.activeElement)||doc.activeElement===doc.body)
|
||||
&&!doc.activeElement?.closest(editable)&&!doc.querySelector('[role=dialog],[role=listbox],[role=menu]');
|
||||
const valid=()=>{
|
||||
if(closed)return false;
|
||||
if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;}
|
||||
if(!focused()){pause("focus_lost");return false;}
|
||||
return true;
|
||||
};
|
||||
const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));};
|
||||
const down=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed)return;
|
||||
if(keysFor(mode).includes(e.code)||e.code==='Space'||e.code==='Escape')trace('key_down',{code:e.code,repeat:e.repeat});
|
||||
if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;}
|
||||
if(e.altKey||e.ctrlKey||e.metaKey){pause();return;}
|
||||
if(!keysFor(mode).includes(e.code)||!valid())return;
|
||||
if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;}
|
||||
if((e.target as HTMLElement)?.closest(editable)){pause();return;}
|
||||
// A repeat delivered after focus returns cannot become a fresh press.
|
||||
if(e.repeat&&!keyboard.has(e.code))return;
|
||||
e.preventDefault();suspended=false;keyboard.add(e.code);
|
||||
deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish();
|
||||
publish();
|
||||
};
|
||||
const up=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed||!keyboard.delete(e.code))return;
|
||||
e.preventDefault();if(!keyboard.size)deadline=0;publish();
|
||||
trace("key_up",{code:e.code});e.preventDefault();publish();
|
||||
};
|
||||
const blur=(e:Event)=>{if(e.target===win)pause();};
|
||||
const blur=(e:Event)=>{if(e.target===win)pause("window_blur");};
|
||||
const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();};
|
||||
const focusIn=()=>{if(!focused())pause();};
|
||||
const hidden=()=>{if(doc.hidden)pause();};
|
||||
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();};
|
||||
const hidden=()=>{if(doc.hidden)pause("page_hidden");};
|
||||
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause("outside_pointer");};
|
||||
const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();};
|
||||
const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();};
|
||||
win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true);
|
||||
@@ -50,11 +59,11 @@ export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
const timer=win.setInterval(valid,50);
|
||||
return {
|
||||
valid,
|
||||
pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}},
|
||||
pointerDown(id:number,code:string){if(valid()){trace("pointer_down",{code});suspended=false;pointers.set(id,code);publish();}},
|
||||
pointerUp(id:number){if(!closed&&pointers.delete(id))publish();},
|
||||
pointerCancel(id:number){if(pointers.has(id))pause();},
|
||||
pointerCancel(id:number){if(pointers.has(id)){trace("pointer_cancel");pause("pointer_cancel");}},
|
||||
dispose(){
|
||||
closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
|
||||
trace("lifecycle",{reason:"input_disposed"});closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
|
||||
win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true);
|
||||
win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop);
|
||||
doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true);
|
||||
|
||||
@@ -8,13 +8,25 @@ export function keyDemand(mode:RoverMode,held:ReadonlySet<string>):Demand {
|
||||
const scale=Math.max(1,Math.abs(forward)+Math.abs(turn));
|
||||
return {left:(forward+turn)/scale,right:(forward-turn)/scale};
|
||||
}
|
||||
export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''};
|
||||
export const defaultRoverSettings={version:3,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,throttlePercent:10,model:''};
|
||||
export function roverSettings(value:unknown):typeof defaultRoverSettings {
|
||||
const v=value as Partial<typeof defaultRoverSettings>|null;
|
||||
return {...defaultRoverSettings,...(v?.version===1?{
|
||||
return {...defaultRoverSettings,...(v?.version===1||v?.version===2||v?.version===3?{
|
||||
mode:v.mode==='tank'?'tank':'arcade',
|
||||
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30,
|
||||
// Legacy forms persisted an empty field as 0, then clamped it to .5.
|
||||
// Repair that legacy floor once; v3 keeps an explicitly chosen .5 A.
|
||||
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)&&v.currentA>=.5&&!(v.version!==3&&v.currentA===.5)?v.currentA:30,
|
||||
maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000,
|
||||
// ERPM has no trustworthy conversion to throttle. Migrate at 10%, never
|
||||
// reinterpret an old saved number as a percentage or full throttle.
|
||||
throttlePercent:v.version!==1&&typeof v.throttlePercent==='number'&&Number.isFinite(v.throttlePercent)?Math.max(1,Math.min(100,v.throttlePercent)):10,
|
||||
model:v.model==='dcd006-v020'?v.model:'',
|
||||
}:{} )};
|
||||
}
|
||||
|
||||
export const roverNumberInput=(value:string)=>value.trim()===''?Number.NaN:Number(value);
|
||||
export function persistableRoverSettings(v:typeof defaultRoverSettings){
|
||||
return Number.isFinite(v.currentA)&&v.currentA>=.5
|
||||
&&Number.isFinite(v.throttlePercent)&&v.throttlePercent>=1&&v.throttlePercent<=100
|
||||
&&Number.isFinite(v.maxErpm)&&v.maxErpm>=300&&v.maxErpm<=3000;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Stream the complete onboard snapshot to the operator's chosen file. */
|
||||
import {transferRoverLog} from './roverLogTransfer';
|
||||
type SaveWindow=Window&{showSaveFilePicker?:(options:unknown)=>Promise<FileSystemFileHandle>};
|
||||
export async function saveRoverLog(url:string,name:string){
|
||||
const picker=(window as SaveWindow).showSaveFilePicker;
|
||||
if(!picker){
|
||||
// Native download remains a streaming fallback; the browser owns its save UI.
|
||||
const a=document.createElement('a');a.href=url+'/diagnostics/export';a.download=name;a.click();return;
|
||||
}
|
||||
const handle=await picker.call(window,{suggestedName:name,types:[{description:'Лог сессии JSONL',accept:{'application/x-ndjson':['.jsonl']}}]});
|
||||
const writable=await handle.createWritable();
|
||||
try{
|
||||
await transferRoverLog(url,data=>writable.write(data));
|
||||
await writable.close();
|
||||
}catch(error){await writable.abort().catch(()=>{});throw error;}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/** Bounded transfer of an immutable onboard snapshot over the existing HTTP API. */
|
||||
export type LogCursor={capture_id:string;total_bytes:number;snapshot:string;offset:number};
|
||||
const MAX_LINE=100*1024;
|
||||
const failure=()=>new Error('Не удалось проверить файл с борта. Повторите сохранение.');
|
||||
|
||||
export async function readLogBlocks(response:Response,cursor:LogCursor|undefined,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>,confirmed:(value:LogCursor)=>void){
|
||||
if(!response.body)throw failure();
|
||||
const reader=response.body.getReader(),decoder=new TextDecoder('utf-8',{fatal:true});
|
||||
let pending='',complete=false;
|
||||
try{
|
||||
while(true){
|
||||
const {done,value}=await reader.read();
|
||||
if(done){if(pending||!complete)throw failure();return;}
|
||||
// Split before decoding so even an unexpectedly large HTTP read cannot create
|
||||
// an unbounded accumulated string. Only a single export block is retained.
|
||||
for(let start=0;start<value.length;start+=8192){
|
||||
pending+=decoder.decode(value.subarray(start,start+8192),{stream:true});
|
||||
let end:number;
|
||||
while((end=pending.indexOf('\n'))>=0){
|
||||
if(end>MAX_LINE||complete)throw failure();
|
||||
const row=JSON.parse(pending.slice(0,end));pending=pending.slice(end+1);
|
||||
if(!/^[a-f0-9]{32}$/.test(row.capture_id)||!/^[a-f0-9]{64}$/.test(row.snapshot)||!/^[a-f0-9]{64}$/.test(row.sha256)
|
||||
||![row.offset,row.next,row.total_bytes].every(Number.isSafeInteger)
|
||||
||row.offset<0||row.next<row.offset||row.next>row.total_bytes
|
||||
||typeof row.data!=='string'||row.data.length>87384)throw failure();
|
||||
if(cursor?(row.capture_id!==cursor.capture_id||row.snapshot!==cursor.snapshot||row.total_bytes!==cursor.total_bytes||row.offset!==cursor.offset):row.offset!==0)throw failure();
|
||||
const raw=Uint8Array.from(atob(row.data),c=>c.charCodeAt(0));
|
||||
if(raw.length>65536||raw.length!==row.next-row.offset||(!raw.length&&row.next!==row.total_bytes))throw failure();
|
||||
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',raw)),n=>n.toString(16).padStart(2,'0')).join('');
|
||||
if(digest!==row.sha256)throw failure();
|
||||
await write(raw);
|
||||
cursor={capture_id:row.capture_id,total_bytes:row.total_bytes,snapshot:row.snapshot,offset:row.next};
|
||||
confirmed(cursor);complete=cursor.offset===cursor.total_bytes;
|
||||
}
|
||||
if(pending.length>MAX_LINE)throw failure();
|
||||
}
|
||||
}
|
||||
}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
|
||||
}
|
||||
|
||||
export async function transferRoverLog(url:string,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>){
|
||||
let cursor:LogCursor|undefined;
|
||||
for(let attempt=0;attempt<4;attempt++){
|
||||
const params=new URLSearchParams({format:'chunks'});
|
||||
if(cursor)for(const [key,value] of Object.entries(cursor))params.set(key,String(value));
|
||||
const controller=new AbortController();
|
||||
let timer:ReturnType<typeof setTimeout>;
|
||||
const reset=()=>{clearTimeout(timer);timer=setTimeout(()=>controller.abort(),130000);};
|
||||
reset();
|
||||
try{
|
||||
const response=await fetch(url+'/diagnostics/export?'+params,{signal:controller.signal});
|
||||
if(!response.ok)throw new Error('Не удалось получить файл с борта. Проверьте связь и повторите сохранение.');
|
||||
await readLogBlocks(response,cursor,write,value=>{cursor=value;reset();});
|
||||
return;
|
||||
}catch(error){
|
||||
if(attempt===3)throw error;
|
||||
// No session-duration limit. Retry only a failed download, retaining the
|
||||
// exact snapshot and the last verified, successfully written offset.
|
||||
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
|
||||
}finally{clearTimeout(timer!);controller.abort();}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type {RoverConnection} from './roverTransport';
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
export interface RoverObservationStatus {label:string|null;pulse:boolean}
|
||||
/** Presentation only. A fresh driver snapshot owns its attachment lifecycle;
|
||||
* inventory and elapsed UI time cannot establish readiness or motor authority. */
|
||||
export function roverObservationStatus(state:RoverState,connection:RoverConnection):RoverObservationStatus{
|
||||
const pending=(label:string)=>({label,pulse:true});
|
||||
if(connection==='connecting')return pending('Подключение к Mission Core');
|
||||
if(connection!=='connected')return pending('Восстановление связи с Mission Core');
|
||||
if(!state.fresh)return pending('Ожидание телеметрии с борта');
|
||||
const snapshot=state.snapshot;
|
||||
if(!snapshot.supported)return {label:'Служба управления на борту недоступна',pulse:false};
|
||||
if(snapshot.message||snapshot.state==='fault')return {label:null,pulse:false};
|
||||
const readings=snapshot.devices??[],expected=Object.values(snapshot.profile?.bindings??{});
|
||||
const missing=expected.filter(b=>!readings.some(d=>d.id===b.device_id&&d.uuid===b.uuid));
|
||||
const initializing=snapshot.observation?.initializing_devices??[];
|
||||
if(initializing.length&&(missing.length?missing.every(b=>initializing.includes(b.device_id)):!expected.length&&!readings.length))return pending('Инициализация VESC');
|
||||
if(missing.length||!readings.length||readings.some(d=>!Number.isFinite(d.age_ms)||d.age_ms<0||d.age_ms>=1000))return pending('Ожидание свежих показаний VESC');
|
||||
return {label:null,pulse:false};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Bounded local diagnostic download. No request to the board or motion API. */
|
||||
export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise<void>=async()=>{}){
|
||||
if(!/^[a-f0-9]{32}$/.test(id))throw Error('Запись изменилась.');
|
||||
await beforeSnapshot();
|
||||
const response=await fetch(url+'/diagnostics/local/export?capture_id='+id,{cache:'no-store',signal:AbortSignal.timeout(5000)});
|
||||
if(!response.ok)throw Error('Не удалось выгрузить замер компьютера. Запись сохранена в Core.');
|
||||
const blob=await response.blob();if(blob.size>4*1024*1024)throw Error('Размер замера превышает допустимый.');
|
||||
// The bounded snapshot uses the browser's normal download flow, including fullscreen.
|
||||
const href=URL.createObjectURL(blob),a=document.createElement('a');
|
||||
try{a.href=href;a.download=`rover-operator-${id}.jsonl`;document.body.append(a);a.click();}
|
||||
finally{a.remove();setTimeout(()=>URL.revokeObjectURL(href),1000);}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty'}
|
||||
const MAX_RETRY_BACKOFF=3;
|
||||
const STABLE_CONNECTION_MS=30000;
|
||||
const MAX_READY_OBSERVATION_GAP_MS=1000;
|
||||
const profileKey=(s:RoverState['snapshot'])=>JSON.stringify(s.profile??null);
|
||||
const motorKey=(s:RoverState['snapshot'])=>(s.devices??[]).map(d=>d.uuid+'@'+(d.session_id??'')).sort().join(':');
|
||||
|
||||
// Reacquire a NEW neutral lease after transport loss. Never revive an expired
|
||||
// lease or remember motion. Explicit Stop, hardware faults and RC takeover end
|
||||
// the operator's request; navigation/reload never persists it.
|
||||
export class RoverRecovery {
|
||||
private request:{settings:RoverArmSettings;instance:string;profile:string;motors:string;previousSession:string|null|undefined}|null=null;
|
||||
private pendingSession:string|null=null;
|
||||
private quietSince:number|null=null;
|
||||
private retryAt=0;
|
||||
private attempts=0;
|
||||
private readySince:number|null=null;
|
||||
private lastReadyAt:number|null=null;
|
||||
private retiredSession:string|null=null;
|
||||
waiting=false;
|
||||
remember(settings:RoverArmSettings,value:RoverState){
|
||||
this.clear();
|
||||
if(value.fresh&&value.snapshot.instance&&value.snapshot.devices?.length&&value.snapshot.devices.every(d=>d.session_id))this.request={settings:{...settings},instance:value.snapshot.instance,profile:profileKey(value.snapshot),motors:motorKey(value.snapshot),previousSession:value.snapshot.session_id};
|
||||
}
|
||||
clear(){this.request=null;this.waiting=false;this.quietSince=null;this.attempts=0;this.retryAt=0;this.retiredSession=null;this.pendingSession=null;this.readySince=null;this.lastReadyAt=null;}
|
||||
started(session:string){if(!this.waiting)this.pendingSession=session;}
|
||||
previousStatus(value:RoverState,ownedSession:string|null){
|
||||
// An explicit new arm acknowledges the previous terminal session. Core may
|
||||
// still expose that snapshot until the board receives the new neutral lease.
|
||||
return !!this.request&&!!ownedSession&&ownedSession===this.pendingSession&&!this.waiting
|
||||
&&value.fresh&&value.controlling&&value.snapshot.session_id===this.request.previousSession
|
||||
&&value.snapshot.session_id!==ownedSession&&['fault','stopped','receiver','observing'].includes(value.snapshot.state??'');
|
||||
}
|
||||
connected(now:number){
|
||||
this.waiting=false;this.quietSince=null;this.pendingSession=null;
|
||||
// One ready snapshot is not a recovered link. Require continuous fresh
|
||||
// observations before forgiving repeated automatic rearm attempts.
|
||||
if(this.lastReadyAt===null||now<this.lastReadyAt||now-this.lastReadyAt>MAX_READY_OBSERVATION_GAP_MS)this.readySince=now;
|
||||
this.lastReadyAt=now;this.readySince??=now;
|
||||
if(now-this.readySince>=STABLE_CONNECTION_MS){this.attempts=0;this.retryAt=0;}
|
||||
}
|
||||
interrupt(now:number,session:string|null){
|
||||
if(!this.request)return false;
|
||||
this.readySince=null;this.lastReadyAt=null;
|
||||
if(!this.waiting){this.retryAt=Math.max(this.retryAt,now+500);this.quietSince=null;}
|
||||
this.retiredSession=session??this.retiredSession;this.waiting=true;this.pendingSession=null;return true;
|
||||
}
|
||||
blocker(value:RoverState,ownedSession:string|null=null){
|
||||
if(!this.request||!value.fresh)return null;
|
||||
const s=value.snapshot;
|
||||
if(s.instance!==this.request.instance)return 'Борт перезапустился. Проверьте состояние и включите управление.';
|
||||
if(motorKey(s)!==this.request.motors)return 'Подключение VESC изменилось. Проверьте состояние и включите управление.';
|
||||
if(profileKey(s)!==this.request.profile)return 'Назначение моторов изменилось. Проверьте настройки управления.';
|
||||
if(s.supported!==true||(this.request.settings.mode==='duty'&&!s.control_modes?.includes('duty')))return 'Режим управления на борту изменился.';
|
||||
if(s.session_id===ownedSession)this.pendingSession=null;
|
||||
if(this.previousStatus(value,ownedSession))return null;
|
||||
const ended=s.last_stop;
|
||||
if(ended?.state==='fault'&&(ended.session_id===ownedSession||ended.session_id===this.retiredSession))return ended.message||'Предыдущий сеанс завершился с ошибкой. Включите управление заново.';
|
||||
// Stopping is an interlock, not a terminal cancellation. The board may need
|
||||
// fresh passive samples to verify release. next() still requires confirmed
|
||||
// stopped state; a hardware fault (including historical fault) still blocks.
|
||||
if(s.state==='fault'||(s.release_confirmed===false&&s.state!=='stopping'))return s.message||'Борт сообщил об ошибке. Проверьте состояние перед включением.';
|
||||
if(s.state==='receiver')return 'Управление передано пульту.';
|
||||
if(this.waiting&&value.controlling&&s.session_id&&s.session_id!==this.retiredSession&&s.session_id!==ownedSession)return 'Управление включено в другом окне.';
|
||||
return null;
|
||||
}
|
||||
next(value:RoverState,now:number,focused:boolean):RoverArmSettings|null{
|
||||
if(!this.waiting||!this.request)return null;
|
||||
if(this.blocker(value)){this.clear();return null;}
|
||||
const s=value.snapshot,devices=s.devices??[];
|
||||
const quiet=value.fresh&&!value.controlling&&s.state==='stopped'&&s.release_confirmed===true
|
||||
&&motorKey(s)===this.request.motors&&devices.length>0&&devices.every(d=>Number.isFinite(d.age_ms)&&d.age_ms>=0&&d.age_ms<=500
|
||||
&&Number.isFinite(d.values.erpm)&&Math.abs(d.values.erpm)<60&&d.values.fault_code===0);
|
||||
if(!focused||!quiet){this.quietSince=null;return null;}
|
||||
this.quietSince??=now;
|
||||
if(now-this.quietSince<500||now<this.retryAt)return null;
|
||||
// Transport loss retains the operator request; only retry rate is bounded.
|
||||
// Saturate the exponent so a long outage cannot grow an attempt counter.
|
||||
this.retryAt=now+1000*2**this.attempts;this.attempts=Math.min(this.attempts+1,MAX_RETRY_BACKOFF);this.quietSince=null;
|
||||
return {...this.request.settings};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Bounded, volatile engineering evidence. Never participates in control decisions. */
|
||||
export class RoverTiming {
|
||||
private lastTick:number|null=null;
|
||||
private events:Record<string,string|number|boolean>[]=[];
|
||||
private started=performance.now();
|
||||
private tickGap=0;
|
||||
private requestMS=0;
|
||||
private samples=0;
|
||||
private staleSamples=0;
|
||||
private hadFresh=false;
|
||||
view(fresh:boolean){this.samples++;if(fresh)this.hadFresh=true;else if(this.hadFresh)this.staleSamples++;this.publish();}
|
||||
private event(value:Record<string,string|number|boolean>){
|
||||
this.events.push({at_ms:Math.round(performance.now()-this.started),...value});this.events=this.events.slice(-16);
|
||||
}
|
||||
tick(active:boolean){
|
||||
const now=performance.now();this.tickGap=this.lastTick===null?0:Math.round(now-this.lastTick);this.lastTick=now;
|
||||
if(this.tickGap>=200)this.event({kind:'heartbeat-gap',gap_ms:this.tickGap,active,hidden:document.hidden,focused:document.hasFocus()});
|
||||
this.publish();
|
||||
}
|
||||
request(kind:'view'|'arm'|'command',started:number,outcome:'ok'|'http'|'transport',url?:string){
|
||||
this.requestMS=Math.round(performance.now()-started);
|
||||
let network:Record<string,number>={};
|
||||
try{if(url&&typeof performance.getEntriesByName==='function'){
|
||||
const entry=performance.getEntriesByName(new URL(url,window.location.href).href,'resource').at(-1) as PerformanceResourceTiming|undefined;
|
||||
if(entry&&entry.startTime>=started-1&&entry.requestStart>0)network={browser_wait_ms:Math.round(entry.requestStart-entry.fetchStart),response_wait_ms:Math.round(entry.responseStart-entry.requestStart),body_ms:Math.round(entry.responseEnd-entry.responseStart)};
|
||||
}}catch{/* Diagnostics cannot interfere with a command. */}
|
||||
if(this.requestMS>=200||outcome!=='ok')this.event({kind,outcome,duration_ms:this.requestMS,hidden:document.hidden,focused:document.hasFocus(),...network});
|
||||
this.publish();
|
||||
}
|
||||
private publish(){
|
||||
// One replaceable DOM diagnostic record; no telemetry archive or product control.
|
||||
if(document.documentElement)document.documentElement.dataset.roverTiming=JSON.stringify({sampled_at_ms:Math.round(performance.now()),tick_gap_ms:this.tickGap,request_ms:this.requestMS,state_samples:this.samples,stale_after_fresh:this.staleSamples,events:this.events});
|
||||
}
|
||||
clear(){this.lastTick=null;this.events=[];this.samples=0;this.staleSamples=0;this.hadFresh=false;this.started=performance.now();if(document.documentElement)delete document.documentElement.dataset.roverTiming;}
|
||||
}
|
||||
export const roverTiming=new RoverTiming();
|
||||
@@ -0,0 +1,107 @@
|
||||
import {roverDevEvent,roverEvidenceForeground} from './roverDevEvents';
|
||||
/** Separate socket from HTTP asset/SSE queues. No queued or replayed commands. */
|
||||
export class RoverHttpError extends Error {constructor(message:string,readonly status:number){super(message);}}
|
||||
export type RoverConnection='connecting'|'connected'|'reconnecting'|'closed';
|
||||
type Pending={resolve:(value:any)=>void;reject:(reason:Error)=>void;timer:ReturnType<typeof setTimeout>};
|
||||
export class RoverTransport {
|
||||
private socket:WebSocket|null=null;
|
||||
private latest:unknown;
|
||||
private seen=-Infinity;
|
||||
private clock=0;
|
||||
private clockAt=0;
|
||||
private next=0;
|
||||
private socketID='';
|
||||
private lastSent:number|null=null;
|
||||
private pending=new Map<number,Pending>();
|
||||
private waiting=new Set<Pending>();
|
||||
private retry:ReturnType<typeof setTimeout>|undefined;
|
||||
private closed=false;
|
||||
private watchdog:ReturnType<typeof setTimeout>|undefined;
|
||||
private failures=0;
|
||||
private received=false;
|
||||
connection():RoverConnection{return this.closed?'closed':performance.now()-this.seen<600?'connected':this.received||this.failures>0?'reconnecting':'connecting';}
|
||||
private touch(socket:WebSocket){
|
||||
clearTimeout(this.watchdog);
|
||||
this.watchdog=setTimeout(()=>this.disconnect(socket,"watchdog"),1500);
|
||||
}
|
||||
private disconnect(socket:WebSocket,reason:string){
|
||||
if(this.socket!==socket)return;
|
||||
roverDevEvent(this.url,"transport",{reason,ready_state:socket.readyState,buffered_bytes:socket.bufferedAmount,pending:this.pending.size});
|
||||
this.socket=null;this.seen=-Infinity;clearTimeout(this.watchdog);this.fail();
|
||||
// Retire locally even when the browser never emits a close event.
|
||||
socket.onopen=socket.onmessage=socket.onclose=socket.onerror=null;socket.close();
|
||||
if(!this.closed)this.retry=setTimeout(()=>this.connect(),Math.min(250*2**Math.min(this.failures++,4),4000));
|
||||
}
|
||||
constructor(private url:string,private create:(url:string)=>WebSocket=url=>new WebSocket(url)){this.connect();}
|
||||
private connect(){
|
||||
if(this.closed)return;
|
||||
const url=new URL(this.url+'-channel',window.location.href);url.protocol=url.protocol==='https:'?'wss:':'ws:';
|
||||
const socket=this.create(url.href);this.socket=socket;this.socketID='';this.lastSent=null;
|
||||
// A browser handshake owns no motion authority. Do not repeatedly cancel a
|
||||
// cold connection with the live-state deadline before it can open. Once open,
|
||||
// the original watchdog and all sample/command deadlines still apply.
|
||||
clearTimeout(this.watchdog);
|
||||
this.watchdog=setTimeout(()=>this.disconnect(socket,'connect_timeout'),10000);
|
||||
socket.onopen=()=>{if(this.socket===socket)this.touch(socket);};
|
||||
if(socket.readyState===1)this.touch(socket);
|
||||
socket.onmessage=event=>{
|
||||
if(this.socket!==socket)return;
|
||||
try{const value=JSON.parse(event.data);
|
||||
if(typeof value.socket_id==='string')this.socketID=value.socket_id;
|
||||
if(value.type==='reply')roverDevEvent(this.url,'transport',{reason:'reply_received',request_id:value.id,socket_id:this.socketID,clock_ms:value.clock_ms,outcome:String(value.status??200)});
|
||||
if(value.type==='state'&&Number.isFinite(value.clock_ms)){
|
||||
this.received=true;this.latest=value.value;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
|
||||
for(const p of this.waiting){clearTimeout(p.timer);p.resolve(this.latest);}this.waiting.clear();
|
||||
}else if(value.type==='reply'){
|
||||
const p=this.pending.get(value.id);if(!p)return;this.pending.delete(value.id);clearTimeout(p.timer);
|
||||
if(value.state&&Number.isFinite(value.clock_ms)){
|
||||
this.latest=value.state;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
|
||||
for(const waiter of this.waiting){clearTimeout(waiter.timer);waiter.resolve(this.latest);}this.waiting.clear();
|
||||
}
|
||||
if(value.error)roverDevEvent(this.url,'transport',{reason:'reply_rejected',outcome:String(value.status??409)});
|
||||
if(value.error)p.reject(new RoverHttpError(value.error,value.status??409));else p.resolve(value.value);
|
||||
}
|
||||
}catch{/* Invalid frames never acknowledge a request. */}
|
||||
};
|
||||
socket.onclose=event=>{roverDevEvent(this.url,"transport",{reason:"close",close_code:event?.code});this.disconnect(socket,"close");};
|
||||
socket.onerror=()=>this.disconnect(socket,"error");
|
||||
}
|
||||
private fail(){
|
||||
for(const p of [...this.pending.values(),...this.waiting]){clearTimeout(p.timer);p.reject(new Error('Канал управления недоступен.'));}
|
||||
this.pending.clear();this.waiting.clear();
|
||||
}
|
||||
view():Promise<unknown>{
|
||||
if(this.closed)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
if(performance.now()-this.seen<600)return Promise.resolve(this.latest);
|
||||
return new Promise((resolve,reject)=>{const p:Pending={resolve,reject,timer:setTimeout(()=>{this.waiting.delete(p);reject(new Error('Нет свежих данных с борта.'));},1000)};this.waiting.add(p);});
|
||||
}
|
||||
command(action:'arm'|'command'|'hold',body:unknown):Promise<unknown>{
|
||||
const socket=this.socket,now=performance.now();
|
||||
if(!socket||socket.readyState!==1||socket.bufferedAmount>4096||now-this.seen>=600||this.pending.size>=4)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
const id=++this.next;
|
||||
return new Promise((resolve,reject)=>{
|
||||
this.pending.set(id,{resolve,reject,timer:setTimeout(()=>{this.pending.delete(id);roverDevEvent(this.url,'transport',{reason:'ack_timeout',action,request_id:id,socket_id:this.socketID});reject(new Error('Команда не подтверждена.'));},350)});
|
||||
try{
|
||||
const expires=this.clock+(now-this.clockAt)+400;
|
||||
const fields=body&&typeof body==='object'?body as Record<string,unknown>:{};
|
||||
roverDevEvent(this.url,'request',{reason:'socket_send',request_id:id,socket_id:this.socketID,action,
|
||||
session_id:fields.session_id,sequence:fields.sequence,expires_ms:expires,state_age_ms:now-this.seen,
|
||||
gap_ms:this.lastSent===null?0:now-this.lastSent,foreground:roverEvidenceForeground()});
|
||||
socket.send(JSON.stringify({id,action,body,expires_ms:expires}));this.lastSent=now;
|
||||
}
|
||||
catch{const p=this.pending.get(id);if(p){clearTimeout(p.timer);this.pending.delete(id);}reject(new Error('Канал управления недоступен.'));}
|
||||
});
|
||||
}
|
||||
close(){this.closed=true;clearTimeout(this.retry);clearTimeout(this.watchdog);const socket=this.socket;this.socket=null;this.seen=-Infinity;this.fail();socket?.close();}
|
||||
}
|
||||
const clients=new Map<string,{transport:RoverTransport;users:number}>();
|
||||
export function retainRoverTransport(url:string){
|
||||
let entry=clients.get(url);if(!entry){entry={transport:new RoverTransport(url),users:0};clients.set(url,entry);}entry.users++;
|
||||
return()=>{if(--entry!.users===0){entry!.transport.close();clients.delete(url);}};
|
||||
}
|
||||
export function roverRequest<T>(url:string,body?:unknown):Promise<T>{
|
||||
const action=url.endsWith('/arm')?'arm':url.endsWith('/hold')?'hold':'command',base=body?url.slice(0,url.lastIndexOf('/')):url,client=clients.get(base);
|
||||
if(!client)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
return (body?client.transport.command(action,body):client.transport.view()) as Promise<T>;
|
||||
}
|
||||
export function roverConnection(url:string):RoverConnection{return clients.get(url)?.transport.connection()??'closed';}
|
||||
@@ -1,17 +1,23 @@
|
||||
import type {SensorInventory, SensorTransport} from '../../../../../packages/sensor-ui/src/contracts';
|
||||
import type {SensorInventory, SensorTransport, SensorLiveFrame} from '../../../../../packages/sensor-ui/src/contracts';
|
||||
import {fleetRequest} from './useFleet';
|
||||
import {roverPreviewEvidence} from './roverDevEvents';
|
||||
|
||||
export function createFleetSensorTransport(vehicleID:string):SensorTransport {
|
||||
const path=`/${encodeURIComponent(vehicleID)}/devices`;
|
||||
const inventory=(fleet:{items:{id:string;connectivity:string;enrollment:string;sensor_state:SensorInventory}[]})=>{
|
||||
const inventory=(fleet:{items:{id:string;core_endpoint?:string;connectivity:string;enrollment:string;inventory_fresh?:boolean;sensor_state:SensorInventory}[]})=>{
|
||||
const value=fleet.items.find(v=>v.id===vehicleID);
|
||||
if(!value)throw new Error('Аппарат не найден.');
|
||||
return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'};
|
||||
return {...value.sensor_state,items:value.sensor_state.items.map(item=>({...item,transport_generation:value.core_endpoint})),fresh:value.connectivity==='online'&&value.enrollment==='paired'&&value.inventory_fresh!==false};
|
||||
};
|
||||
return {
|
||||
previewEvidence:sample=>roverPreviewEvidence(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,sample),
|
||||
liveTelemetry:async signal=>{
|
||||
const value=await fleetRequest<{fresh:boolean;snapshot:Omit<SensorLiveFrame,'fresh'>}>(`/${encodeURIComponent(vehicleID)}/rover`,'GET',undefined,1200,signal);
|
||||
return {...value.snapshot,fresh:value.fresh};
|
||||
},
|
||||
configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)},
|
||||
enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)},
|
||||
inventory:async()=>inventory(await fleetRequest()),
|
||||
inventory:async signal=>inventory(await fleetRequest('','GET',undefined,12000,signal)),
|
||||
subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},
|
||||
submit:value=>fleetRequest(`${path}/operations`,'POST',value),
|
||||
operation:id=>fleetRequest(`${path}/operations/${encodeURIComponent(id)}`),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export type NetworkProvider='tailscale'|'wireguard';
|
||||
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
|
||||
export interface BoardNetworkView {
|
||||
profiles:SharedNetworkProfile[];available:boolean;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
|
||||
operation:{id:string;state:string;error?:string}|null;
|
||||
}
|
||||
export function useBoardNetwork(vehicleId:string){
|
||||
const [value,setValue]=useState<BoardNetworkView|null>(null),[provider,setProvider]=useState<NetworkProvider>('tailscale'),[profileId,setProfileId]=useState('');
|
||||
const [error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const revision=useRef<number|null>(null);
|
||||
const accept=useCallback((next:BoardNetworkView)=>{
|
||||
setValue(next);
|
||||
if(next.node&&revision.current!==next.node.revision){revision.current=next.node.revision;setProvider(next.node.provider);setProfileId(next.node.server_id||'');}
|
||||
},[]);
|
||||
const refresh=useCallback(async()=>{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`);accept(next);return next;},[vehicleId,accept]);
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{try{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`,'GET',undefined,12000,controller.signal);if(active)accept(next);}catch(e){if(active){setError(e instanceof Error?e.message:'Состояние подключения недоступно.');setValue(current=>current?{...current,available:false}:null);}}finally{if(active)timer=setTimeout(poll,2000);}};
|
||||
revision.current=null;void poll();return()=>{active=false;controller.abort();clearTimeout(timer);};
|
||||
},[vehicleId,accept]);
|
||||
const importing=async(file:File)=>{if(busy)return;setBusy(true);setError('');try{
|
||||
if(file.size>16384)throw Error('Выберите файл подключения, созданный установщиком VPS.');
|
||||
const item=await fleetRequest<SharedNetworkProfile>('/network-profiles/import','POST',{document:await file.text()},240000);
|
||||
await refresh();setProvider('wireguard');setProfileId(item.id);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Файл не удалось импортировать.');}finally{setBusy(false);}};
|
||||
const applying=value?.operation?.state==='applying'||value?.operation?.state==='rolling_back';
|
||||
const dirty=Boolean(value?.node&&(provider!==value.node.provider||(provider==='wireguard'&&profileId!==value.node.server_id)));
|
||||
const save=async()=>{if(!value?.node||busy||applying)return;setBusy(true);setError('');try{
|
||||
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
|
||||
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
|
||||
}
|
||||
@@ -16,11 +16,11 @@ export interface FleetPreview {
|
||||
preview_id: string; node_id: string; name: string; host: BoardHost;
|
||||
endpoint: string; expires_at: number;
|
||||
}
|
||||
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000): Promise<T> {
|
||||
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000, signal?:AbortSignal): Promise<T> {
|
||||
const response = await fetch(`/api/v1/fleet${path}`, {
|
||||
method, credentials: "same-origin", cache: "no-store",
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs),
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
@@ -1,79 +1,139 @@
|
||||
import {roverDevEvent} from './roverDevEvents';
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import type {Demand} from './roverInput';
|
||||
import {RoverRecovery,type RoverArmSettings} from './roverRecovery';
|
||||
import {RoverFaultNotice} from './roverFaultNotice';
|
||||
import {roverTiming} from './roverTiming';
|
||||
import {retainRoverTransport,roverRequest,roverConnection,RoverHttpError,type RoverConnection} from './roverTransport';
|
||||
|
||||
export interface RoverReading {
|
||||
id:string;uuid:string;slot:string|null;label:string;age_ms:number;
|
||||
id:string;uuid:string;session_id?:string;slot:string|null;label:string;age_ms:number;
|
||||
current_limits?:{motor_a:number;brake_a:number}|null;
|
||||
values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number};
|
||||
}
|
||||
export interface RoverState {
|
||||
fresh:boolean;controlling:boolean;
|
||||
snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[];
|
||||
snapshot:{supported?:boolean;control_modes?:string[];instance?:string;state?:string;session_id?:string|null;message?:string|null;release_confirmed?:boolean|null;devices?:RoverReading[];
|
||||
observation?:{initializing_devices:string[]};
|
||||
last_stop?:{session_id:string;state:string;message:string|null;recovered_at?:string};
|
||||
profile?:{layout:null|'1x1'|'2x2';bindings:Record<string,{device_id:string;uuid:string}>}};
|
||||
}
|
||||
// Generate fresh intent at the command channel cadence. Keepalive frames do
|
||||
// not renew the original 400 ms deadline; duplicating a 100 ms-old sample
|
||||
// wastes half of the 50 ms carrier opportunities during a network burst.
|
||||
const INTENT_INTERVAL_MS=50;
|
||||
const empty:RoverState={fresh:false,controlling:false,snapshot:{}};
|
||||
async function request<T>(url:string,body?:unknown,keepalive=false):Promise<T>{
|
||||
const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined,
|
||||
body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive});
|
||||
const result=await response.json();
|
||||
if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.');
|
||||
const retryable=(e:unknown)=>!(e instanceof RoverHttpError)||e.status>=500||[408,429].includes(e.status)||['Управление завершено. Включите его заново.','Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.'].includes(e.message);
|
||||
async function request<T>(url:string,body?:unknown,_keepalive=false):Promise<T>{
|
||||
const started=performance.now(),kind=url.endsWith('/arm')?'arm':body?'command':'view';let outcome:'ok'|'http'|'transport'='transport';
|
||||
try{
|
||||
const result=await roverRequest<T>(url,body);
|
||||
outcome='ok';
|
||||
return result;
|
||||
}catch(e){if(e instanceof RoverHttpError)outcome='http';throw e;}finally{roverTiming.request(kind,started,outcome);if(body)roverDevEvent(url.slice(0,url.lastIndexOf('/')),'request',{action:kind,outcome,elapsed_ms:performance.now()-started});}
|
||||
}
|
||||
export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<RoverState>(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const [connecting,setConnecting]=useState(true),armPending=useRef(false);
|
||||
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(false),generation=useRef(0);
|
||||
const [connection,setConnection]=useState<RoverConnection>('connecting'),armPending=useRef(false);
|
||||
const [recovering,setRecovering]=useState(false),recovery=useRef(new RoverRecovery()),latest=useRef<RoverState>(empty);
|
||||
const [controlMode,setControlMode]=useState<'unknown'|'rpm'|'duty'>('unknown');
|
||||
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(new Set<string>()),acknowledged=useRef(0),generation=useRef(0);
|
||||
const holding=useRef<string|null>(null);
|
||||
const inputGuard=useRef<(()=>boolean)|null>(null);
|
||||
const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]);
|
||||
const stop=useCallback(()=>{
|
||||
generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
|
||||
const retire=useCallback(()=>{
|
||||
holding.current=null;generation.current++;armPending.current=false;const id=session.current;session.current=null;sending.current.clear();inputGuard.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
|
||||
if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{});
|
||||
},[url]);
|
||||
const stop=useCallback(()=>{recovery.current.clear();setRecovering(false);retire();},[retire]);
|
||||
const interrupt=useCallback((reason:string)=>{
|
||||
roverDevEvent(url,"lifecycle",{reason,action:"interrupt",session_id:session.current});
|
||||
const resume=recovery.current.interrupt(performance.now(),session.current);retire();setRecovering(resume);setError(resume?null:reason);
|
||||
},[retire]);
|
||||
const send=useCallback(async()=>{
|
||||
roverTiming.tick(session.current!==null);
|
||||
const id=session.current;if(!id)return;
|
||||
// Check on every heartbeat, even when a previous request is still pending.
|
||||
const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.();
|
||||
if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0};
|
||||
if(sending.current)return;
|
||||
sending.current=true;
|
||||
try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});}
|
||||
catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}}
|
||||
finally{sending.current=false;}
|
||||
},[url,stop]);
|
||||
const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]);
|
||||
const foreground=!document.hidden&&document.hasFocus();
|
||||
const inputValid=inputGuard.current?.()??false;
|
||||
roverDevEvent(url,"heartbeat",{session_id:id,sequence:seq.current,foreground,input_valid:inputValid,pending:sending.current.size,...demand.current});
|
||||
if(!foreground||!inputValid)demand.current={left:0,right:0};
|
||||
// A hidden renderer cannot provide a reliable heartbeat. Hand only neutral
|
||||
// readiness to the native Core owner socket; it can never renew movement.
|
||||
if(!foreground&&holding.current===id)return;
|
||||
// A delayed HTTP acknowledgement must not delay the next fresh intent.
|
||||
// Bound concurrent requests; keep no queue and never renew remembered input.
|
||||
if(sending.current.size>=4)return;
|
||||
const sequence=++seq.current,key=`${id}:${sequence}`;sending.current.add(key);
|
||||
const hold=!foreground;holding.current=hold?id:null;
|
||||
try{await request(url+(hold?'/hold':'/command'),hold?{session_id:id,sequence}:{session_id:id,sequence,...demand.current,stop:false});
|
||||
if(session.current===id)acknowledged.current=Math.max(acknowledged.current,sequence);
|
||||
}catch(e){if(session.current===id&&sequence>acknowledged.current&&sequence===seq.current){const reason=e instanceof Error?e.message:'Команда не подтверждена.';
|
||||
if(hold&&retryable(e)){holding.current=null;return;} // A delayed JS ack is not a lost board; poll verifies the lease.
|
||||
if(retryable(e))interrupt(reason);else{stop();setError(reason);}}}
|
||||
finally{sending.current.delete(key);}
|
||||
},[url,stop,interrupt]);
|
||||
const setDemand=useCallback((next:Demand)=>{roverDevEvent(url,"demand",next);demand.current=next;void send();},[send]);
|
||||
const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]);
|
||||
const arm=useCallback(async(currentA:number,maxErpm:number)=>{
|
||||
if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
const start=useCallback(async({currentA,speed,mode}:RoverArmSettings)=>{
|
||||
if(document.hidden||!document.hasFocus()||session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
try{
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm});
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})});
|
||||
if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;}
|
||||
// Retire every read started before this acknowledgement, including reads
|
||||
// begun while POST /arm was pending. They describe the previous authority.
|
||||
generation.current++;armPending.current=false;setPending(false);
|
||||
seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send();
|
||||
seq.current=0;acknowledged.current=0;demand.current={left:0,right:0};session.current=result.session_id;recovery.current.started(result.session_id);setArmed(true);void send();
|
||||
return true;
|
||||
}catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;}
|
||||
}catch(e){if(g===generation.current){const reason=e instanceof Error?e.message:'Не удалось включить управление.';
|
||||
if(retryable(e)){interrupt(reason);return recovery.current.waiting;}stop();setError(reason);
|
||||
}return false;}
|
||||
finally{if(g===generation.current){armPending.current=false;setPending(false);}}
|
||||
},[url,send]);
|
||||
},[url,send,interrupt,stop]);
|
||||
const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm')=>{
|
||||
if(session.current||armPending.current||recovery.current.waiting)return Promise.resolve(false);
|
||||
const settings={currentA,speed,mode};recovery.current.remember(settings,latest.current);return start(settings);
|
||||
},[start]);
|
||||
useEffect(()=>{
|
||||
if(!visible){stop();setState(empty);setConnecting(false);return;}
|
||||
let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true);
|
||||
if(!visible){stop();setState(empty);setError(null);setConnection('closed');return;}
|
||||
const releaseTransport=retainRoverTransport(url);
|
||||
let alive=true,busy=false;const notices=new RoverFaultNotice();setError(null);setConnection(roverConnection(url));setControlMode('unknown');
|
||||
const recover=(value:RoverState,focused:boolean)=>{
|
||||
if(session.current||armPending.current)return;
|
||||
const settings=recovery.current.next(value,performance.now(),focused);
|
||||
if(settings)void start(settings);
|
||||
};
|
||||
const poll=async()=>{
|
||||
if(busy)return;busy=true;const before=generation.current;
|
||||
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){setState(value);
|
||||
setConnecting(!value.fresh&&performance.now()-started<2000);
|
||||
if(session.current&&(!value.fresh||!value.controlling)){stop();}
|
||||
const fault=value.snapshot.state==='fault'?value.snapshot.message??'':'';
|
||||
if(fault&&lastFault!==fault){lastFault=fault;setError(fault);}
|
||||
}}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;}
|
||||
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){roverTiming.view(value.fresh);setState(value);latest.current=value;
|
||||
setConnection(roverConnection(url));
|
||||
// Telemetry absence is not a declaration of an old RPM-only driver.
|
||||
if(value.fresh&&value.snapshot.supported)setControlMode(value.snapshot.control_modes?.includes('duty')?'duty':'rpm');
|
||||
const ownedSession=session.current;
|
||||
const previousStatus=armPending.current||recovery.current.previousStatus(value,ownedSession);
|
||||
const blocker=armPending.current?null:recovery.current.blocker(value,session.current);
|
||||
if(blocker){stop();setError(blocker);}
|
||||
else if(session.current&&(!value.fresh||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){
|
||||
const reason=value.snapshot.message||(!value.fresh?'Управление прервано: нет свежих данных с борта.':value.snapshot.state==='receiver'?'Управление передано пульту.':'Управление прервано: борт перестал подтверждать команды. Повторите включение.');
|
||||
interrupt(reason);
|
||||
}
|
||||
if(session.current&&value.fresh&&value.snapshot.session_id===session.current&&['ready','driving'].includes(value.snapshot.state??'')){
|
||||
recovery.current.connected(performance.now());setRecovering(false);
|
||||
}
|
||||
recover(value,!document.hidden&&document.hasFocus());
|
||||
if(!previousStatus){const notice=notices.update(value,ownedSession);if(notice.show)setError(notice.show);else if(notice.clear)setError(current=>current===notice.clear?null:current);}
|
||||
}}catch{if(alive&&before===generation.current){setState(empty);latest.current=empty;setConnection(roverConnection(url));if(session.current)interrupt('Управление прервано: не удалось проверить связь с бортом.');recover(empty,false);}}finally{busy=false;}
|
||||
};
|
||||
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100);
|
||||
const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();};
|
||||
window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();};
|
||||
},[url,visible,stop,send,pauseInput]);
|
||||
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),INTENT_INTERVAL_MS);
|
||||
const blur=()=>pauseInput();
|
||||
const foreground=()=>{if(document.hidden||!document.hasFocus())return;void poll();void send();};
|
||||
const hidden=()=>{if(document.hidden)pauseInput();else foreground();};
|
||||
window.addEventListener('blur',blur);window.addEventListener('focus',foreground);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('focus',foreground);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();releaseTransport();roverTiming.clear();};
|
||||
},[url,visible,stop,send,pauseInput,start,interrupt]);
|
||||
const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
|
||||
const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
const canArm=!recovering&&state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connection,connecting:connection==='connecting',controlMode,recovering,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
}
|
||||
export type RoverController=ReturnType<typeof useRoverControl>;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {connectRoverEvidence,roverDevEvent} from './roverDevEvents';
|
||||
import {saveRoverLog} from './roverLogSave';
|
||||
import {saveOperatorCapture} from './roverOperatorCapture';
|
||||
export type LocalCaptureOptions={enabled:boolean;preview:boolean};
|
||||
export type DevOptions={live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;live_kbps:number;core_kbps:number};
|
||||
export const localDevOptions:DevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};
|
||||
export type DevRow={record_sequence:number;source:string;event:string;at_utc:string;record?:DevRow;[key:string]:unknown};
|
||||
export type DevState={local_capture?:{id:string|null;active:boolean;preview?:boolean;dropped?:number;sequence?:number};options?:DevOptions;options_supported?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[];
|
||||
node?:{active?:boolean;transport_error?:string;storage?:{file?:string;closed:boolean;written:number;dropped:number;error?:string}}};
|
||||
const empty:DevState={id:null,active:false,closing:false,sequence:0,frames:[]};
|
||||
export function useRoverDiagnostics(vehicleID:string){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<DevState>(empty),[rows,setRows]=useState<DevRow[]>([]);
|
||||
const [pending,setPending]=useState(false),[saving,setSaving]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const savedLocal=useRef<string|null>(null);
|
||||
const evidence=useRef<ReturnType<typeof connectRoverEvidence>|null>(null),latest=useRef(empty);
|
||||
const accept=useCallback((value:DevState)=>{
|
||||
const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false);
|
||||
const failure=value.node?.storage?.error;
|
||||
if(failure&&(previous.id!==value.id||previous.node?.storage?.error!==failure))
|
||||
setError(failure==='CaptureInterrupted'?'DEV-запись прервана перезапуском борта. Сохранившийся файл оставлен на борту. Можно начать новую запись.':failure==='CaptureNotFound'?'Предыдущая DEV-запись на борту не найдена. Можно начать новую запись.':`Запись остановлена: ${failure}. Файл может быть неполным.`);
|
||||
setRows(rows=>[...(previous.id===value.id?rows:[]),...value.frames.filter(r=>previous.id!==value.id||r.record_sequence>previous.sequence)].slice(-200));
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
let alive=true,busy=false;latest.current=empty;setState(empty);setRows([]);
|
||||
const client=connectRoverEvidence(url);evidence.current=client;
|
||||
const poll=async()=>{if(busy)return;busy=true;const started=performance.now();try{
|
||||
const r=await fetch(url+'/diagnostics?after='+latest.current.sequence,{cache:'no-store',signal:AbortSignal.timeout(3000)});
|
||||
if(!r.ok)throw Error();const value:DevState=await r.json();
|
||||
if(performance.now()-started>=200)roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'slow',elapsed_ms:performance.now()-started});if(alive){accept(value);setError(current=>current==='Нет связи с Mission Core. Файл остаётся на борту.'?null:current);}
|
||||
}catch{roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'transport',elapsed_ms:performance.now()-started});if(alive&&latest.current.active)setError('Нет связи с Mission Core. Файл остаётся на борту.');}finally{busy=false;}};
|
||||
void poll();const timer=setInterval(()=>void poll(),500);
|
||||
return()=>{alive=false;clearInterval(timer);client.close();evidence.current=null;};
|
||||
},[url,accept]);
|
||||
const toggle=useCallback(async(options?:DevOptions,local?:LocalCaptureOptions)=>{
|
||||
if(pending||latest.current.closing)return false;
|
||||
setPending(true);setError(null);
|
||||
try{
|
||||
const enabled=!latest.current.active;if(!enabled)await evidence.current?.flush();
|
||||
const previousID=latest.current.local_capture?.id;
|
||||
if(enabled&&local?.enabled&&previousID&&savedLocal.current!==previousID)throw Error("Сначала сохраните предыдущий замер компьютера в окне логов.");
|
||||
const r=await fetch(url+'/diagnostics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(enabled?{enabled,options:options??localDevOptions,...(local?{local_options:{...local,previous_id:previousID??null}}:{})}:{enabled})});
|
||||
const value=await r.json();if(!r.ok)throw Error(value.detail??'Не удалось переключить DEV.');accept(value);return enabled;
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось переключить DEV.');return false;}finally{setPending(false);}
|
||||
},[url,pending,accept]);
|
||||
const save=useCallback(async()=>{
|
||||
if(saving)return;setSaving(true);setError(null);
|
||||
try{await saveRoverLog(url,latest.current.node?.storage?.file?.split('/').pop()??`rover-${latest.current.id}.jsonl`);}
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
const saveLocal=useCallback(async()=>{
|
||||
const id=latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null);
|
||||
try{await saveOperatorCapture(url,id,async()=>{await evidence.current?.flush();});if(latest.current.local_capture?.id===id&&!latest.current.local_capture.active)savedLocal.current=id;}
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить замер.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
return {state,rows,pending,saving,error,toggle,save,saveLocal,clearError:()=>setError(null)};
|
||||
}
|
||||
export type RoverDiagnostics=ReturnType<typeof useRoverDiagnostics>;
|
||||
@@ -4,56 +4,105 @@ import type {ObservationLayout} from './observationLayout';
|
||||
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
|
||||
import {fleetRequest} from './useFleet';
|
||||
import {sameConfiguration} from './configurationEquality';
|
||||
import {observationSerial,mergeObservation,saveObservation} from './observationSync';
|
||||
|
||||
interface Document {layouts:ObservationPresets;cameras:Record<string,CameraPresentation>}
|
||||
interface Receipt {schema:'missioncore.rover-configuration/v1';revision:number;document:Document|null;draft?:Document|null;source:'onboard'|'mirror';writable:boolean;available:boolean}
|
||||
interface Draft {revision:number;document:Document}
|
||||
interface Draft {revision:number;document:Document;base?:Document}
|
||||
export function useVehicleObservation(vehicleID:string) {
|
||||
const draftKey=`missioncore.observation.draft.v1:${vehicleID}`;
|
||||
const stored=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
|
||||
const initial=():Document=>({layouts:decodeObservationPresets(null,stored(`missioncore.observation.v1:${vehicleID}`)),cameras:{}});
|
||||
const [recovery,setRecovery]=useState<Document|null>(null);
|
||||
const [connectionError,setConnectionError]=useState<string|null>(null);
|
||||
const [document,setDocument]=useState(initial),[ready,setReady]=useState(false),[error,setError]=useState<string|null>(null),[edit,setEdit]=useState(0),[pending,setPending]=useState(false),[errorDismissed,setErrorDismissed]=useState(false);
|
||||
const state=useRef({document,edit:0,saved:0,revision:0,ready:false});
|
||||
const state=useRef({document,base:document,edit:0,saved:0,revision:0,ready:false});
|
||||
const mounted=useRef(true),writes=useRef(Promise.resolve());
|
||||
const path=`/${encodeURIComponent(vehicleID)}/observation-configuration`;
|
||||
const normalize=(value:Document):Document=>({...value,layouts:decodeObservationPresets(value.layouts)});
|
||||
const remember=()=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:state.current.revision,document:state.current.document}));}catch{/* The board acknowledgement remains the durable save. */}};
|
||||
const normalize=(value:Document|null):Document=>value?({...value,layouts:decodeObservationPresets(value.layouts)}):initial();
|
||||
const remember=(current=state.current)=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:current.revision,document:current.document,base:current.base}));}catch{/* The board acknowledgement remains the durable save. */}};
|
||||
const flush=()=>{
|
||||
const current=state.current;
|
||||
const write=async()=>{
|
||||
const current=state.current;if(!current.ready||current.saved===current.edit)return;
|
||||
if(!current.ready||current.saved===current.edit)return;
|
||||
const version=current.edit,payload=current.document;
|
||||
if(mounted.current)setPending(true);
|
||||
if((mounted.current&&state.current===current))setPending(true);
|
||||
try {
|
||||
const receipt=await fleetRequest<Receipt>(path,'PUT',{expected_revision:current.revision,document:payload},20000);
|
||||
current.revision=receipt.revision;current.saved=version;
|
||||
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember();
|
||||
if(mounted.current)setError(null);
|
||||
}catch(cause){if(mounted.current){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
|
||||
finally{if(mounted.current)setPending(current.saved!==current.edit);}
|
||||
const saved=await saveObservation(current.revision,current.base,payload,
|
||||
()=>fleetRequest<Receipt>(path),(revision,document)=>fleetRequest<Receipt>(path,'PUT',{expected_revision:revision,document},20000),normalize);
|
||||
current.revision=saved.receipt.revision;current.base=saved.document;current.saved=version;
|
||||
// Preserve edits made while the request was pending, plus unrelated changes
|
||||
// which were merged from the board. Conflicting new edits remain local.
|
||||
current.document=mergeObservation(payload,current.document,saved.document).value;
|
||||
if((mounted.current&&state.current===current))setDocument(current.document);
|
||||
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember(current);
|
||||
if((mounted.current&&state.current===current))setError(null);
|
||||
}catch(cause){if((mounted.current&&state.current===current)){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
|
||||
finally{if((mounted.current&&state.current===current))setPending(current.saved!==current.edit);}
|
||||
};
|
||||
writes.current=writes.current.then(write,write);return writes.current;
|
||||
writes.current=observationSerial(vehicleID,write);return writes.current;
|
||||
};
|
||||
useEffect(()=>{
|
||||
mounted.current=true;let active=true;
|
||||
fleetRequest<Receipt>(path).then(receipt=>{
|
||||
mounted.current=true;let active=true,timer:ReturnType<typeof setTimeout>|undefined,wasWritable=false;
|
||||
const empty=initial();state.current={document:empty,base:empty,edit:0,saved:0,revision:0,ready:false};
|
||||
setReady(false);setError(null);setConnectionError(null);setErrorDismissed(false);setRecovery(null);
|
||||
const refresh=async()=>{
|
||||
let retrySave=false;
|
||||
try{await observationSerial(vehicleID,async()=>{
|
||||
if(!active)return;
|
||||
const saved=receipt.document?normalize(receipt.document):initial();
|
||||
const receipt=await fleetRequest<Receipt>(path);
|
||||
if(!active)return;
|
||||
setConnectionError(receipt.writable?null:'Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
|
||||
const recovered=receipt.writable&&!wasWritable;wasWritable=receipt.writable;
|
||||
const current=state.current;
|
||||
if(current.ready){
|
||||
// Availability is rechecked independently of edits. A mirror cannot roll
|
||||
// back the acknowledged board version or overwrite an unsaved local draft.
|
||||
if(!receipt.writable||receipt.revision<current.revision)return;
|
||||
const remote=normalize(receipt.document),merged=mergeObservation(current.base,current.document,remote);
|
||||
if(merged.conflicts.length)return;
|
||||
current.document=merged.value;current.base=remote;current.revision=receipt.revision;
|
||||
if(sameConfiguration(current.document,remote)){
|
||||
// A timed-out save may already be committed on the board. Its fresh
|
||||
// read-back settles both the draft and the old acknowledgement error.
|
||||
if(current.saved!==current.edit)setError(null);
|
||||
current.saved=current.edit;try{localStorage.removeItem(draftKey);}catch{}
|
||||
}else remember(current);
|
||||
setDocument(current.document);setPending(current.saved!==current.edit);
|
||||
retrySave=recovered&¤t.saved!==current.edit;
|
||||
return;
|
||||
}
|
||||
const saved=normalize(receipt.document);
|
||||
const draft=stored(draftKey) as Draft|null;
|
||||
const candidate=draft?.document??(!receipt.document?receipt.draft:null);
|
||||
const same=candidate&&sameConfiguration(candidate,receipt.document);
|
||||
const dirty=!!candidate&&!same;
|
||||
const value=dirty?normalize(candidate):saved;
|
||||
const revision=draft&&dirty?draft.revision:receipt.revision;
|
||||
state.current={document:value,edit:dirty?1:0,saved:0,revision,ready:true};
|
||||
let value=candidate?normalize(candidate):saved;
|
||||
let dirty=!!candidate&&!sameConfiguration(value,saved);
|
||||
if(dirty&&draft&&draft.revision!==receipt.revision){
|
||||
const merge=draft.base?mergeObservation(normalize(draft.base),value,saved):null;
|
||||
if(merge&&!merge.conflicts.length){value=merge.value;dirty=!sameConfiguration(value,saved);}
|
||||
else {
|
||||
// Legacy drafts lack a merge ancestor. Keep a recoverable copy and open
|
||||
// the latest board version instead of endlessly replaying a stale revision.
|
||||
try{localStorage.setItem(draftKey+':recovery',JSON.stringify(value));}catch{}
|
||||
setRecovery(value);value=saved;dirty=false;
|
||||
}
|
||||
}
|
||||
if(!dirty){try{localStorage.removeItem(draftKey);}catch{}}
|
||||
const retained=stored(draftKey+':recovery');if(retained)setRecovery(normalize(retained));
|
||||
state.current={document:value,base:saved,edit:dirty?1:0,saved:0,revision:receipt.revision,ready:true};
|
||||
setDocument(value);setReady(true);setEdit(dirty?1:0);setPending(dirty);
|
||||
if(!receipt.writable)setError('Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
|
||||
}).catch(cause=>{if(active)setError(cause instanceof Error?cause.message:'Настройки недоступны.');});
|
||||
return()=>{active=false;mounted.current=false;void flush();};
|
||||
});
|
||||
if(active&&retrySave)void flush();
|
||||
}catch(cause){if(active){wasWritable=false;setConnectionError(cause instanceof Error?cause.message:'Настройки недоступны.');}}
|
||||
finally{if(active)timer=setTimeout(()=>void refresh(),5000);}
|
||||
};
|
||||
void refresh();
|
||||
return()=>{active=false;clearTimeout(timer);mounted.current=false;void flush();};
|
||||
},[vehicleID]);
|
||||
useEffect(()=>{if(!ready||edit===0)return;const timer=setTimeout(()=>void flush(),350);return()=>clearTimeout(timer);},[edit,ready]);
|
||||
const update=(change:(value:Document)=>Document)=>{
|
||||
if(!state.current.ready)return;
|
||||
const current=state.current;current.document=change(current.document);current.edit++;remember();
|
||||
const current=state.current;const next=change(current.document);if(sameConfiguration(next,current.document))return;current.document=next;current.edit++;remember();
|
||||
setDocument(current.document);setEdit(current.edit);setPending(true);
|
||||
};
|
||||
const changeLayouts=(change:(value:ObservationPresets)=>ObservationPresets)=>{
|
||||
@@ -61,22 +110,32 @@ export function useVehicleObservation(vehicleID:string) {
|
||||
catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
|
||||
};
|
||||
const reload=async()=>{
|
||||
const current=state.current;
|
||||
if(state.current.saved!==state.current.edit){const copy=state.current.document;setRecovery(copy);try{localStorage.setItem(draftKey+':recovery',JSON.stringify(copy));}catch{}}
|
||||
await writes.current;
|
||||
try{
|
||||
const receipt=await fleetRequest<Receipt>(path);
|
||||
const receipt=await observationSerial(vehicleID,()=>fleetRequest<Receipt>(path));
|
||||
if(!mounted.current||state.current!==current)return false;
|
||||
if(!receipt.writable)throw Error('Не удалось получить актуальную конфигурацию с борта. Черновик сохранён.');
|
||||
const value=receipt.document?normalize(receipt.document):initial();
|
||||
state.current={document:value,edit:0,saved:0,revision:receipt.revision,ready:true};
|
||||
state.current={document:value,base:value,edit:0,saved:0,revision:receipt.revision,ready:true};
|
||||
setDocument(value);setReady(true);setEdit(0);setPending(false);setError(null);
|
||||
try{localStorage.removeItem(draftKey);}catch{}
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');}
|
||||
return true;
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');return false;}
|
||||
};
|
||||
const setLayout=(value:SetStateAction<ObservationLayout>)=>changeLayouts(current=>({...current,layout:typeof value==='function'?value(current.layout):value}));
|
||||
return {...document.layouts,ready,pending,cameras:document.cameras,setLayout,
|
||||
const restore=async()=>{
|
||||
const retained=recovery??state.current.document;
|
||||
if(!await reload())return;
|
||||
update(()=>retained);setRecovery(null);
|
||||
try{localStorage.removeItem(draftKey+':recovery');}catch{}
|
||||
};
|
||||
return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout,
|
||||
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
|
||||
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
|
||||
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
|
||||
rename:(id:string,name:string)=>changeLayouts(current=>renameObservationPreset(current,id,name)),
|
||||
remove:(id:string)=>changeLayouts(current=>removeObservationPreset(current,id)),
|
||||
error,toastError:errorDismissed?null:error,clearError:()=>setErrorDismissed(true),retry:flush,reload};
|
||||
error:error??connectionError,toastError:errorDismissed?null:error??connectionError,clearError:()=>setErrorDismissed(true),retry:flush,reload};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import {useRef} from 'react';
|
||||
import {Button,Icon,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {useBoardNetwork,type NetworkProvider} from '../../core/fleet/useBoardNetwork';
|
||||
import {InstallerCard} from './equipment/InstallerCard';
|
||||
export function BoardNetworkSettings({network}:{network:ReturnType<typeof useBoardNetwork>}){
|
||||
const input=useRef<HTMLInputElement>(null);
|
||||
const {value,provider,profileId,busy,applying,error}=network;
|
||||
const current=value?.node;
|
||||
const selected=value?.profiles.find(p=>p.id===profileId);
|
||||
const progress=value?.operation?.state;
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
return <div className="fleet-form">
|
||||
<SettingsCard title="Связь с Core" description="Профиль связи этого бортового компьютера с Mission Core. Вычислительный Worker сохраняет своё подключение." actions={<StatusBadge tone={applying?'warning':value?.available?'success':'neutral'}>{label}</StatusBadge>}>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:<>
|
||||
<Select label="Общий профиль VPS" value={profileId} options={[{value:'',label:'Выберите профиль'},...(value?.profiles??[]).filter(p=>p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/>
|
||||
{selected&&<StatusBadge tone={selected.state==='ready'?'success':'warning'}>{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}</StatusBadge>}
|
||||
<p>Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.</p>
|
||||
</>}
|
||||
{!value?.available&&<p>Для изменения настроек нужен доступный БК с актуальной версией Node.</p>}
|
||||
{(error||value?.operation?.error||current?.error)&&<StatusBadge tone="danger">{error||value?.operation?.error||current?.error}</StatusBadge>}
|
||||
</SettingsCard>
|
||||
{provider==='wireguard'&&<>
|
||||
<SettingsCard title="Подключить VPS" description="Если сервер уже подготовлен, загрузите полученный на нём файл подключения. Для нового сервера сначала скачайте и запустите установщик.">
|
||||
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(file)void network.importing(file);}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy||applying} loading={busy} onClick={()=>input.current?.click()}>Загрузить файл подключения</Button>
|
||||
</SettingsCard>
|
||||
<InstallerCard kind="vps-wireguard"/>
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user