diff --git a/apps/control-station/src/core/fleet/boardUplink.ts b/apps/control-station/src/core/fleet/boardUplink.ts new file mode 100644 index 00000000..488ec590 --- /dev/null +++ b/apps/control-station/src/core/fleet/boardUplink.ts @@ -0,0 +1,38 @@ +export interface UplinkCandidate {id:string;label:string;interface:string;kind:'wifi'|'ethernet';verified:boolean;available?:boolean;active?:boolean} +export interface BoardUplinkView { + path_verified?:boolean;available:boolean;reason:string;revision:string;runtime:string;current_id:string;candidates:UplinkCandidate[]; + operation:{id:string;phase:string;message:string}|null; + fallback?:{enabled:boolean;revision:number;operation_id:string}|null; + fallback_operation?:{id:string;phase:string;message:string}|null; +} +export const uplinkPending=(value:BoardUplinkView|null)=>['queued','applying','verifying','rolling_back','recovering','unknown','rollback_failed'].includes(value?.operation?.phase||''); +export const fallbackPending=(value:BoardUplinkView|null)=>value?.fallback_operation?.phase==='queued'; +export const canSetFallback=(value:BoardUplinkView|null)=>Boolean(value?.available&&value.path_verified&&value.fallback&&!uplinkPending(value)&&!fallbackPending(value)); +export const canSelectUplink=(value:BoardUplinkView|null,target:string)=>Boolean(value?.available&&!uplinkPending(value)&&!fallbackPending(value)&&value.current_id&&(target!==value.current_id||value.path_verified===false)&&value.candidates.some(c=>c.id===target&&(c.available||c.verified))); +export const uplinkOptions=(value:BoardUplinkView|null)=>(value?.candidates??[]).map(c=>({value:c.id,label:`${c.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${c.label}`,description:`${c.interface}${c.id===value?.current_id?' · Текущее':''}${!c.verified?(c.active?' · Интернет не подтверждён':' · Не подключено'):''}`,disabled:!(c.available||c.verified)})); +export const uplinkStatusMessage=(value:BoardUplinkView|null)=>{ + if(!value)return ''; + if(!value.available)return value.reason; + if(uplinkPending(value))return value.operation?.message||'Проверяем подключение.'; + const op=value.operation; + if(op?.phase==='applied'||op?.phase==='rolled_back'){ + if(!value.path_verified)return 'Текущий путь к Core не подтверждён.'; + const result=op.phase==='applied'?'Подключение выбрано.':'Возвращено прежнее подключение.'; + return `${result} ${value.path_verified?'Путь к Core подтверждён.':'Текущий путь к Core не подтверждён.'}`; + } + return op?.message||''; +}; +// Follow observed state unless the operator is deliberately choosing an alternative. +export const uplinkReceipt=(value:BoardUplinkView|null)=>value?.operation?`${value.operation.id}:${value.operation.phase}`:''; +export const reconcileUplinkSelection=(selected:string,previousCurrent:string,next:BoardUplinkView,previousReceipt='')=>{ + const settled=Boolean(next.operation&&!uplinkPending(next)&&uplinkReceipt(next)!==previousReceipt); + return settled||selected===previousCurrent||!next.candidates.some(c=>c.id===selected&&(c.available||c.verified))?next.current_id:selected; +}; + +export const uplinkCurrentLabel=(value:BoardUplinkView|null)=>{ + if(!value?.available)return value?.reason||'Получаем состояние сети с борта.'; + if(uplinkPending(value))return 'Текущее подключение: проверяется.'; + const current=value.candidates.find(c=>c.id===value.current_id); + if(!current)return 'Основное подключение не определено.'; + return `Текущее подключение: ${current.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${current.label}${value.path_verified?'':' · путь к Core не подтверждён'}.`; +}; diff --git a/apps/control-station/src/core/fleet/useBoardUplink.ts b/apps/control-station/src/core/fleet/useBoardUplink.ts new file mode 100644 index 00000000..e355e588 --- /dev/null +++ b/apps/control-station/src/core/fleet/useBoardUplink.ts @@ -0,0 +1,43 @@ +import {useEffect,useRef,useState} from 'react'; +import {fleetRequest} from './useFleet'; +import {canSelectUplink,canSetFallback,fallbackPending,uplinkPending,uplinkReceipt,reconcileUplinkSelection,type BoardUplinkView} from './boardUplink'; + +export function useBoardUplink(vehicleId:string){ + const [value,setValue]=useState(null),[target,setTarget]=useState(''),[error,setError]=useState(''),[loadError,setLoadError]=useState(''),[busy,setBusy]=useState(false); + const selected=useRef(''),previousCurrent=useRef(''),previousReceipt=useRef(''),generation=useRef(0); + useEffect(()=>{const epoch=++generation.current;let live=true;let timer:ReturnType;const abort=new AbortController(); + selected.current='';previousCurrent.current='';previousReceipt.current='';setTarget('');setValue(null);setError('');setLoadError('');setBusy(false); + const poll=async()=>{try{ + const next=await fleetRequest(`/${encodeURIComponent(vehicleId)}/uplink`,'GET',undefined,12000,abort.signal); + if(!live||generation.current!==epoch)return; + setValue(next);setLoadError(''); + const choice=reconcileUplinkSelection(selected.current,previousCurrent.current,next,previousReceipt.current); + previousReceipt.current=uplinkReceipt(next); + previousCurrent.current=next.current_id;selected.current=choice;setTarget(choice); + }catch(e){if(live){setValue(old=>old?{...old,available:false}:null);setLoadError(e instanceof Error?e.message:'Нет сведений о подключении.');}} + finally{if(live)timer=setTimeout(poll,2000);}}; + void poll();return()=>{live=false;abort.abort();clearTimeout(timer);}; + },[vehicleId]); + const choose=(id:string)=>{selected.current=id;setTarget(id);setError('');}; + const connect=async()=>{ + if(busy||!value||!canSelectUplink(value,target))return; + const epoch=generation.current;setBusy(true);setError(''); + try{ + const operation=await fleetRequest>(`/${encodeURIComponent(vehicleId)}/uplink`,'POST',{target,revision:value.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')}); + if(generation.current===epoch)setValue(old=>old?{...old,operation}:old); + }catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Нет подтверждения команды. Проверьте состояние подключения.');} + finally{if(generation.current===epoch)setBusy(false);} + }; + const setFallback=async(enabled:boolean)=>{ + if(busy||!canSetFallback(value)||!value?.fallback)return; + const epoch=generation.current;setBusy(true);setError(''); + try{ + const operation=await fleetRequest>(`/${encodeURIComponent(vehicleId)}/uplink/fallback`,'PATCH',{enabled,revision:value.fallback.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')}); + if(generation.current===epoch)setValue(old=>old?{...old,fallback_operation:operation}:old); + }catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Настройка не сохранена.');} + finally{if(generation.current===epoch)setBusy(false);} + }; + return {value,target,choose,error:error||loadError,busy,connect,setFallback, + fallbackPending:fallbackPending(value),canSetFallback:!busy&&canSetFallback(value), + pending:uplinkPending(value),canConnect:!busy&&canSelectUplink(value,target)}; +} diff --git a/apps/control-station/src/workspaces/fleet/BoardComputer.tsx b/apps/control-station/src/workspaces/fleet/BoardComputer.tsx index 4685423d..90f1dbb7 100644 --- a/apps/control-station/src/workspaces/fleet/BoardComputer.tsx +++ b/apps/control-station/src/workspaces/fleet/BoardComputer.tsx @@ -23,7 +23,7 @@ export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicl identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}} sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'},{id:'interfaces',label:'Сеть',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose} footer={{section==='network'&&}}> - {section==='network'?:section==='interfaces'?: + {section==='network'?:section==='interfaces'?:
{boardStatus(vehicle,enabled)} {vehicle.notice&&{vehicle.notice}}
Идентификатор БК
{vehicle.node_id}
Последняя связь
{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}
diff --git a/apps/control-station/src/workspaces/fleet/BoardNetworkStatus.tsx b/apps/control-station/src/workspaces/fleet/BoardNetworkStatus.tsx index 9d495688..61464e2c 100644 --- a/apps/control-station/src/workspaces/fleet/BoardNetworkStatus.tsx +++ b/apps/control-station/src/workspaces/fleet/BoardNetworkStatus.tsx @@ -1,4 +1,5 @@ import {memo} from 'react'; +import {BoardUplinkControl} from './BoardUplinkControl'; import {Description,SettingsCard,StatusBadge} from '@nodedc/ui-react'; import type {BoardNetworkStatusValue} from '../../core/fleet/boardNetworkStatus'; @@ -15,10 +16,11 @@ const NetworkCard=memo(function NetworkCard(link:BoardNetworkStatusValue['links'
; }); -export function BoardNetworkStatus({status}:{status:BoardNetworkStatusValue}) { +export function BoardNetworkStatus({status,vehicleId}:{status:BoardNetworkStatusValue;vehicleId:string}) { const {links,readable,live,collectedAt}=status; return
- Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений. Изменение сети здесь недоступно. + + Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений. {live?'Связь с бортом установлена':'Связь с бортом не подтверждена'} Данные борта на {collectedAt&&Number.isFinite(Date.parse(collectedAt))?new Date(collectedAt).toLocaleString('ru-RU'):'ещё не получен'}. {!links.length?: diff --git a/apps/control-station/src/workspaces/fleet/BoardUplinkControl.tsx b/apps/control-station/src/workspaces/fleet/BoardUplinkControl.tsx new file mode 100644 index 00000000..f6e5e7c7 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/BoardUplinkControl.tsx @@ -0,0 +1,23 @@ +import {Button,Description,Select,SettingsCard,Switch} from '@nodedc/ui-react'; +import {useBoardUplink} from '../../core/fleet/useBoardUplink'; +import {uplinkOptions,uplinkStatusMessage,uplinkCurrentLabel} from '../../core/fleet/boardUplink'; +import './boardUplink.css'; + +export function BoardUplinkControl({vehicleId}:{vehicleId:string}){ + const state=useBoardUplink(vehicleId); + const {value,target,busy,pending,error}=state; + const message=error||uplinkStatusMessage(value); + return +
+