Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03d44d0fb1 | ||
|
|
21f46ac38a | ||
|
|
67ae1f4d77 | ||
|
|
031e01a99b | ||
|
|
f3a7592d90 | ||
|
|
d684eb7e05 | ||
|
|
b6efae3272 | ||
|
|
fb33a6d45c | ||
|
|
0fb117fe7b | ||
|
|
e2cf3078b6 | ||
|
|
f3640026cf | ||
|
|
bd5873ef34 | ||
|
|
aecae4a986 | ||
|
|
ee7576b7b4 | ||
|
|
e2b0d839eb | ||
|
|
d2ec9e95b1 | ||
|
|
8283f9ba85 | ||
|
|
db3b1d7b67 | ||
|
|
a993eda6b8 |
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -152,6 +152,7 @@ export default function App() {
|
|||||||
contentExpanded: true,
|
contentExpanded: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const [navigationRevision, setNavigationRevision] = useState(0);
|
||||||
const [activeRoot, setActiveRoot] = useState<RootId | null>(
|
const [activeRoot, setActiveRoot] = useState<RootId | null>(
|
||||||
polygonDatasetRoute.active ? "data" : null,
|
polygonDatasetRoute.active ? "data" : null,
|
||||||
);
|
);
|
||||||
@@ -159,6 +160,7 @@ export default function App() {
|
|||||||
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
|
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
|
||||||
const [sourceUrl, setSourceUrl] = useState("");
|
const [sourceUrl, setSourceUrl] = useState("");
|
||||||
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
|
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
|
||||||
|
const [workspaceHeaderTitleHost, setWorkspaceHeaderTitleHost] = useState<HTMLSpanElement | null>(null);
|
||||||
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
|
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
|
||||||
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
|
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
|
||||||
const [replayTransitioning, setReplayTransitioning] = useState(false);
|
const [replayTransitioning, setReplayTransitioning] = useState(false);
|
||||||
@@ -457,6 +459,17 @@ export default function App() {
|
|||||||
workspace.openView(viewId);
|
workspace.openView(viewId);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Explicit menu navigation always returns to that workspace's entry screen.
|
||||||
|
const openNavigationView = (viewId: string) => {
|
||||||
|
if (!workspaceById(viewId)) return;
|
||||||
|
setNavigationRevision(value => value + 1);
|
||||||
|
sessionOverview.close();
|
||||||
|
setSourceWindowOpen(false);
|
||||||
|
setDisplayWindowOpen(false);
|
||||||
|
setLayerInspectorOpen(false);
|
||||||
|
openView(viewId);
|
||||||
|
};
|
||||||
|
|
||||||
const openSource = () => {
|
const openSource = () => {
|
||||||
if (!sceneWorkspaceActive) return;
|
if (!sceneWorkspaceActive) return;
|
||||||
setSourceDraft(sourceUrl);
|
setSourceDraft(sourceUrl);
|
||||||
@@ -645,11 +658,8 @@ export default function App() {
|
|||||||
return () => window.clearTimeout(timer);
|
return () => window.clearTimeout(timer);
|
||||||
}, [layoutSaveNotice]);
|
}, [layoutSaveNotice]);
|
||||||
|
|
||||||
const [fleetCreateRequest, setFleetCreateRequest] = useState(0);
|
|
||||||
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
|
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
|
||||||
const onAddVehicle = useCallback(() => setFleetCreateRequest(value => value + 1), []);
|
|
||||||
const contentActions = useApplicationPanelActions({
|
const contentActions = useApplicationPanelActions({
|
||||||
onAddVehicle,
|
|
||||||
definition: activeDefinition,
|
definition: activeDefinition,
|
||||||
refreshRuntime: runtime.refresh,
|
refreshRuntime: runtime.refresh,
|
||||||
resetConnectionScenario: runtime.resetConnectionScenario,
|
resetConnectionScenario: runtime.resetConnectionScenario,
|
||||||
@@ -729,6 +739,7 @@ export default function App() {
|
|||||||
<SystemNavigationPanel
|
<SystemNavigationPanel
|
||||||
title={currentRoot.title}
|
title={currentRoot.title}
|
||||||
onAdd={computeContourSettings.openCreate}
|
onAdd={computeContourSettings.openCreate}
|
||||||
|
onNavigateRoot={() => openNavigationView("modules")}
|
||||||
onClose={workspace.closeNavigation}
|
onClose={workspace.closeNavigation}
|
||||||
/>
|
/>
|
||||||
) : currentRoot ? (
|
) : currentRoot ? (
|
||||||
@@ -755,7 +766,7 @@ export default function App() {
|
|||||||
icon: <Icon name={item.icon} />,
|
icon: <Icon name={item.icon} />,
|
||||||
}))}
|
}))}
|
||||||
activeId={workspace.activeView ?? undefined}
|
activeId={workspace.activeView ?? undefined}
|
||||||
onItemChange={openView}
|
onItemChange={openNavigationView}
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
|
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
|
||||||
@@ -765,7 +776,8 @@ export default function App() {
|
|||||||
{rootWorkspaces.length}{" "}
|
{rootWorkspaces.length}{" "}
|
||||||
{rootWorkspaces.length === 1
|
{rootWorkspaces.length === 1
|
||||||
? "рабочая поверхность"
|
? "рабочая поверхность"
|
||||||
: "рабочих поверхностей"}
|
: rootWorkspaces.length >= 2 && rootWorkspaces.length <= 4
|
||||||
|
? "рабочие поверхности" : "рабочих поверхностей"}
|
||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
@@ -776,7 +788,9 @@ export default function App() {
|
|||||||
key={activeDefinition.id}
|
key={activeDefinition.id}
|
||||||
eyebrow={activeDefinition.eyebrow}
|
eyebrow={activeDefinition.eyebrow}
|
||||||
title={
|
title={
|
||||||
activeDefinition.kind === "recordings"
|
activeDefinition.kind === "vehicles"
|
||||||
|
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
|
||||||
|
: activeDefinition.kind === "recordings"
|
||||||
&& replayPresented
|
&& replayPresented
|
||||||
&& recordedReplayLabel
|
&& recordedReplayLabel
|
||||||
? `${activeDefinition.title}: ${recordedReplayLabel}`
|
? `${activeDefinition.title}: ${recordedReplayLabel}`
|
||||||
@@ -822,16 +836,18 @@ export default function App() {
|
|||||||
/>
|
/>
|
||||||
) : activeDefinition.kind === "missions" ? (
|
) : activeDefinition.kind === "missions" ? (
|
||||||
<div ref={setWorkspaceHeaderToolsHost} />
|
<div ref={setWorkspaceHeaderToolsHost} />
|
||||||
) : activeDefinition.kind === "vehicles" ? <div ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
|
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
|
||||||
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
|
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
|
||||||
) : activeDefinition.kind === "lab-archive" ? (
|
) : activeDefinition.kind === "lab-archive" ? (
|
||||||
laboratoryAnnotation.control
|
laboratoryAnnotation.control
|
||||||
) : activeDefinition.kind === "observatory" ? (
|
) : activeDefinition.kind === "observatory" ? (
|
||||||
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
||||||
|
) : activeDefinition.kind === "contour-health" ? (
|
||||||
|
<div ref={setWorkspaceHeaderToolsHost} />
|
||||||
) : activeDefinition.root === "system" ? (
|
) : activeDefinition.root === "system" ? (
|
||||||
<SystemWorkspaceSelector
|
<SystemWorkspaceSelector
|
||||||
value={activeDefinition.id}
|
value={activeDefinition.id}
|
||||||
onChange={openView}
|
onChange={openNavigationView}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
|
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
|
||||||
@@ -840,7 +856,7 @@ export default function App() {
|
|||||||
utilityActions={contentActions}
|
utilityActions={contentActions}
|
||||||
onClose={workspace.closeView}
|
onClose={workspace.closeView}
|
||||||
>
|
>
|
||||||
<PlanningCaptureGuard
|
<PlanningCaptureGuard key={`${activeDefinition.id}:${navigationRevision}`}
|
||||||
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
|
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
|
||||||
onResume={() => openView('local-device', 'planning')}
|
onResume={() => openView('local-device', 'planning')}
|
||||||
>
|
>
|
||||||
@@ -860,8 +876,8 @@ export default function App() {
|
|||||||
<WorkspaceRenderer
|
<WorkspaceRenderer
|
||||||
launchProfile={launchProfile}
|
launchProfile={launchProfile}
|
||||||
definition={activeDefinition}
|
definition={activeDefinition}
|
||||||
fleetCreateRequest={fleetCreateRequest}
|
|
||||||
headerToolsHost={workspaceHeaderToolsHost}
|
headerToolsHost={workspaceHeaderToolsHost}
|
||||||
|
headerTitleHost={workspaceHeaderTitleHost}
|
||||||
state={activeRuntimeState}
|
state={activeRuntimeState}
|
||||||
backendStatus={runtime.backendStatus}
|
backendStatus={runtime.backendStatus}
|
||||||
sourceUrl={effectiveSourceUrl}
|
sourceUrl={effectiveSourceUrl}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import {createPortal} from 'react-dom';
|
||||||
|
import {Icon,IconButton} from '@nodedc/ui-react';
|
||||||
|
|
||||||
|
/** A nested workspace returns through the shared panel header. */
|
||||||
|
export function WorkspaceBackButton({label,onClick,host}:{label:string;onClick:()=>void;host?:HTMLElement|null}) {
|
||||||
|
const button=<IconButton label={label} onClick={onClick}><Icon name="chevron-left"/></IconButton>;
|
||||||
|
return host?createPortal(button,host):button;
|
||||||
|
}
|
||||||
@@ -6,40 +6,41 @@ import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
|||||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||||
import './rover.css';
|
import './rover.css';
|
||||||
const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer'));
|
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}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
|
||||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
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 [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),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||||
|
const [editing,setEditing]=useState(false);
|
||||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
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]);
|
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]);
|
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||||
useEffect(()=>{if(!active)stop();},[active,stop]);
|
useEffect(()=>{if(!active)stop();},[active,stop]);
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
if(!c.ready||!active||open||!stage.current)return;
|
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 binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
|
||||||
input.current=binding;c.setInputGuard(binding.valid);
|
input.current=binding;c.setInputGuard(binding.valid);
|
||||||
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
|
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
|
||||||
},[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
|
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
|
||||||
const showSettings=()=>{stop();setOpen(true);};
|
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
|
||||||
const preparing=c.pending||(c.armed&&!c.ready);
|
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 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 tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||||
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||||
return <>
|
return <>
|
||||||
{createPortal(<IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton>,header.actionsTarget)}
|
{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(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
|
||||||
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
|
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
|
||||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
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'} label="Загрузка модели ровера">
|
||||||
<Suspense fallback={null}><Scene modelUrl="/rover-scene/dcd006-v020.glb" cameraAutoRotate={false} onModelState={setModelState}/></Suspense>
|
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||||
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||||
<div className="rover-view__status"><StatusBadge tone={tone}>{status}</StatusBadge></div>
|
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
|
||||||
{c.ready&&<div className="rover-view__controls">
|
{c.ready&&!editing&&<div className="rover-view__controls">
|
||||||
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
|
<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)}
|
{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)}
|
||||||
disabled={!c.ready||!active} pressed={held.has(code)}
|
disabled={!c.ready||!active} pressed={held.has(code)}
|
||||||
@@ -50,9 +51,9 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
|
|||||||
</div>
|
</div>
|
||||||
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
|
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
|
||||||
</div>}
|
</div>}
|
||||||
<div className="rover-view__authority">
|
{!editing&&<div className="rover-view__authority">
|
||||||
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
|
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
|
||||||
</div>
|
</div>}
|
||||||
</div>
|
</div>
|
||||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
<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="Тип управления" 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}))}/>
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import {LutField} from './LutField';
|
||||||
|
import {useRef} from 'react';
|
||||||
|
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||||
|
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
|
||||||
|
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
|
||||||
|
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||||
|
const groups=[...new Set(environmentFields.map(f=>f.group))];
|
||||||
|
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
|
||||||
|
}
|
||||||
|
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||||
|
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
|
||||||
|
if(f.type==='action')return <Button onClick={onResetCamera}>Сбросить камеру</Button>;
|
||||||
|
if(f.type==='toggle')return <Switch label={f.label} checked={!!value} disabled={disabled} onChange={onChange}/>;
|
||||||
|
if(f.type==='color')return <ControlRow label={f.label}><ColorField label={f.label} value={String(value)} disabled={disabled} onChange={onChange}/></ControlRow>;
|
||||||
|
if(f.type==='select')return <InspectorSelectField label={f.label} value={String(value)} options={f.options??[]} disabled={disabled} onChange={onChange}/>;
|
||||||
|
if(f.type==='doubleSlider'){const range=value as number[];return <>{['Начало тумана, м','Конец тумана, м'].map((label,i)=><RangeControl key={i} label={label} min={f.min??0} max={f.max??100} step={f.step??1} exactValueBounds={{min:f.min,max:f.max}} value={range[i]} disabled={disabled} onChange={v=>onChange(i?[range[0],v]:[v,range[1]])}/>)}</>;}
|
||||||
|
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
|
||||||
|
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
|
||||||
|
}
|
||||||
|
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
|
||||||
|
const input=useRef<HTMLInputElement>(null);
|
||||||
|
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import {useRef,useState} from 'react';
|
||||||
|
import {Button,Icon,IconButton} from '@nodedc/ui-react';
|
||||||
|
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
|
||||||
|
export function LutField({value,onChange,onError}:{value:string|null|undefined;onChange:(value:string|null)=>void;onError:(error:string)=>void}){
|
||||||
|
const input=useRef<HTMLInputElement>(null),[loading,setLoading]=useState(false);
|
||||||
|
return <div className="rover-scene-fields"><p className="rover-scene-note">PNG 256 × 16 · горизонтальная таблица 16³</p><div className="rover-scene-actions"><Button loading={loading} onClick={()=>input.current?.click()}>{value?'Заменить LUT':'Загрузить LUT'}</Button>{value&&<IconButton label="Удалить LUT" onClick={()=>onChange(null)}><Icon name="trash"/></IconButton>}</div><input hidden ref={input} type="file" accept="image/png" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setLoading(true);try{const bitmap=await createImageBitmap(file);const valid=bitmap.width===256&&bitmap.height===16;bitmap.close();if(!valid||file.type!=='image/png')throw new Error('Нужна PNG-таблица LUT размером 256 × 16.');onChange((await textureFromFile(file)).data);}catch(error){onError(error instanceof Error?error.message:'Не удалось прочитать LUT.');}finally{setLoading(false);}}}/></div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {useRef,useState} from 'react';
|
||||||
|
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||||
|
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||||
|
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
|
||||||
|
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
|
||||||
|
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
|
||||||
|
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
|
||||||
|
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[
|
||||||
|
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
|
||||||
|
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
|
||||||
|
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
|
||||||
|
]}/><Button onClick={onReset}>Исходный материал</Button></>;
|
||||||
|
}
|
||||||
|
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
|
||||||
|
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
|
||||||
|
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import {useCallback,useEffect,useState,type CSSProperties} from 'react';
|
||||||
|
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
|
||||||
|
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||||
|
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
|
||||||
|
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer';
|
||||||
|
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
|
||||||
|
import {MaterialInspector} from './MaterialInspector';
|
||||||
|
import './sceneEditor.css';
|
||||||
|
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
|
||||||
|
const scene=useSceneDocument(vehicleID),[palette,setPalette]=useState(false),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
|
||||||
|
const [selectedGroup,setSelectedGroup]=useState<string|null>(null);
|
||||||
|
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]);
|
||||||
|
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=128){scene.setError('В сцене может быть не больше 128 материалов.');return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
|
||||||
|
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
|
||||||
|
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
|
||||||
|
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
|
||||||
|
const material=selected?scene.document.materials[selected]:null;
|
||||||
|
return <>
|
||||||
|
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены">
|
||||||
|
{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-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>}
|
||||||
|
</>}
|
||||||
|
<Window open={editing&&environment} title="Окружение сцены" placement="end" draggable onClose={()=>setEnvironment(false)} footer={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaultScene().postFx}))}/>}>
|
||||||
|
<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>
|
||||||
|
</Window>
|
||||||
|
<Window open={editing&&materialOpen&&!!material} title={material?.name||'Материал'} subtitle="Материал сцены" placement="end" draggable style={{position:'fixed',left:'var(--nodedc-space-4)',top:'6rem',right:'auto'}} onClose={()=>setMaterialOpen(false)}>
|
||||||
|
{material&&selected&&<>
|
||||||
|
{selectedGroup?<div className="rover-scene-fields"><p className="rover-scene-note">Выбранная группа: {defaultScene().materials[selectedGroup]?.name}</p><Button disabled={(scene.document.assignments[selectedGroup]??selectedGroup)===selected} onClick={()=>scene.update(doc=>assignMaterial(doc,selectedGroup,selected))}>Назначить выбранной группе</Button></div>:<p className="rover-scene-note">Нажмите на деталь в сцене, затем выберите материал в палитре, чтобы назначить его группе.</p>}
|
||||||
|
<MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaultScene().materials[selected]??createMaterial(defaultScene(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/>
|
||||||
|
</>}
|
||||||
|
</Window>
|
||||||
|
<ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
.rover-scene-tools {position:absolute;right:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3));}
|
||||||
|
.rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;}
|
||||||
|
.rover-scene-tools__surface {padding:var(--nodedc-space-1);}
|
||||||
|
.rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;}
|
||||||
|
.rover-material-palette {position:absolute;bottom:var(--nodedc-space-3);left:var(--nodedc-space-3);right:var(--nodedc-space-3);padding:var(--nodedc-space-2);}
|
||||||
|
.rover-material-palette__header {display:flex;align-items:center;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);}
|
||||||
|
.rover-material-palette__items {display:flex;gap:var(--nodedc-space-2);overflow:auto;}
|
||||||
|
.rover-material-palette__items > * {flex:0 0 auto;}
|
||||||
|
.rover-material-tile {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size:var(--nodedc-font-size-xs);}
|
||||||
|
/* Domain material thumbnail: a swatch, not a replacement control. */
|
||||||
|
.rover-material-swatch {display:block;width:38px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;}
|
||||||
|
.rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
|
||||||
|
.rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);}
|
||||||
|
.rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;}
|
||||||
|
.rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;}
|
||||||
|
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;}
|
||||||
|
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}.rover-material-tile{width:82px}.rover-material-palette__header>span{max-width:210px}}
|
||||||
@@ -11,6 +11,13 @@
|
|||||||
"No fallback to a different vehicle",
|
"No fallback to a different vehicle",
|
||||||
"Removed unused node-editor type helper; rendering settings unchanged",
|
"Removed unused node-editor type helper; rendering settings unchanged",
|
||||||
"Observe the host pane on resize; preserve responsive canvas CSS sizing",
|
"Observe the host pane on resize; preserve responsive canvas CSS sizing",
|
||||||
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect"
|
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect",
|
||||||
]
|
"Scene editing uses canonical modeless Design Guideline inspectors; all 109 donor camera/post-FX fields retained as a versioned field catalog",
|
||||||
|
"Original NodeDC environment preset restored by owner request; editor reset changes environment only",
|
||||||
|
"Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal",
|
||||||
|
"Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected",
|
||||||
|
"Responsive scene framing and palette space without drive authority"
|
||||||
|
],
|
||||||
|
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
|
||||||
|
"model_revision": "dcd006-v020-materials-v2"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,16 @@ import * as pc from 'playcanvas'
|
|||||||
import { buildSceneTree } from './sceneTree'
|
import { buildSceneTree } from './sceneTree'
|
||||||
import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx'
|
import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx'
|
||||||
|
|
||||||
|
import {useLutTexture} from './useLutTexture'
|
||||||
|
import {useSceneMaterials,type SceneMaterialsProps} from './useSceneMaterials'
|
||||||
|
|
||||||
const DEFAULT_MODEL_URL = ''
|
const DEFAULT_MODEL_URL = ''
|
||||||
const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7
|
const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7
|
||||||
const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18
|
const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18
|
||||||
const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12
|
const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12
|
||||||
const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
|
const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
|
||||||
|
|
||||||
export type PlayCanvasViewerProps = {
|
export type PlayCanvasViewerProps = SceneMaterialsProps & {
|
||||||
modelUrl: string | null
|
modelUrl: string | null
|
||||||
postFx?: Partial<PostFxSettings> | null
|
postFx?: Partial<PostFxSettings> | null
|
||||||
viewportSize?: { width: number; height: number }
|
viewportSize?: { width: number; height: number }
|
||||||
@@ -390,16 +393,9 @@ function toColor(value: ColorInput, fallback?: pc.Color): pc.Color {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function setWireframeForScene(app: pc.Application, enabled: boolean) {
|
function setWireframeForScene(app: pc.Application, enabled: boolean) {
|
||||||
const renders = app.root.findComponents('render') as any[]
|
const root = app.root.findByName('ModelRoot') as pc.Entity | null
|
||||||
for (const r of renders) {
|
for (const mi of collectMeshInstances(root)) {
|
||||||
const meshInstances = r?.meshInstances ?? []
|
mi.renderStyle = enabled ? pc.RENDERSTYLE_WIREFRAME : pc.RENDERSTYLE_SOLID
|
||||||
for (const mi of meshInstances) {
|
|
||||||
const mat = mi.material as any
|
|
||||||
if (mat && 'wireframe' in mat) {
|
|
||||||
mat.wireframe = enabled
|
|
||||||
mat.update?.()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -805,7 +801,7 @@ function applyPostFx(
|
|||||||
}
|
}
|
||||||
frame.rendering.renderTargetScale = fx.rendering.renderTargetScale
|
frame.rendering.renderTargetScale = fx.rendering.renderTargetScale
|
||||||
frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples
|
frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples
|
||||||
frame.rendering.sceneColorMap = true
|
frame.rendering.sceneColorMap = !!fx.rendering.sceneColorMap
|
||||||
frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap
|
frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap
|
||||||
frame.rendering.toneMapping = fx.rendering.toneMapping
|
frame.rendering.toneMapping = fx.rendering.toneMapping
|
||||||
frame.rendering.sharpness = fx.rendering.sharpness
|
frame.rendering.sharpness = fx.rendering.sharpness
|
||||||
@@ -882,6 +878,7 @@ function applyPostFx(
|
|||||||
|
|
||||||
export default function PlayCanvasViewer({
|
export default function PlayCanvasViewer({
|
||||||
modelUrl,
|
modelUrl,
|
||||||
|
materials, assignments, editing, onMaterialPick, onTextureState,
|
||||||
postFx,
|
postFx,
|
||||||
viewportSize,
|
viewportSize,
|
||||||
onSceneReady,
|
onSceneReady,
|
||||||
@@ -928,7 +925,11 @@ export default function PlayCanvasViewer({
|
|||||||
const [skyboxVersion, setSkyboxVersion] = useState(0)
|
const [skyboxVersion, setSkyboxVersion] = useState(0)
|
||||||
const [modelVersion, setModelVersion] = useState(0)
|
const [modelVersion, setModelVersion] = useState(0)
|
||||||
|
|
||||||
|
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState})
|
||||||
|
|
||||||
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
|
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
|
||||||
|
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
|
||||||
|
useLutTexture(appRef,cameraFrameRef,lutTextureRef,fx.lut.textureUrl,appReady,lutError)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
cameraStateRef.current = cameraState ?? null
|
cameraStateRef.current = cameraState ?? null
|
||||||
@@ -962,7 +963,7 @@ export default function PlayCanvasViewer({
|
|||||||
if (bounds && orbit) {
|
if (bounds && orbit) {
|
||||||
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
|
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
|
||||||
const horizontal = Math.atan(Math.tan(vertical) * w / h)
|
const horizontal = Math.atan(Math.tan(vertical) * w / h)
|
||||||
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
|
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@@ -1112,6 +1113,8 @@ export default function PlayCanvasViewer({
|
|||||||
`,
|
`,
|
||||||
fragmentGLSL: `
|
fragmentGLSL: `
|
||||||
uniform vec2 uHalfExtents;
|
uniform vec2 uHalfExtents;
|
||||||
|
uniform float uGridStep;
|
||||||
|
uniform float uGridRadius;
|
||||||
uniform vec3 uColorX;
|
uniform vec3 uColorX;
|
||||||
uniform vec3 uColorZ;
|
uniform vec3 uColorZ;
|
||||||
uniform vec3 uColorMain;
|
uniform vec3 uColorMain;
|
||||||
@@ -1182,7 +1185,9 @@ export default function PlayCanvasViewer({
|
|||||||
void main(void) {
|
void main(void) {
|
||||||
vec2 uv = uv0;
|
vec2 uv = uv0;
|
||||||
|
|
||||||
vec2 pos = (uv * 2.0 - 1.0) * uHalfExtents;
|
vec2 worldPos = (uv * 2.0 - 1.0) * uHalfExtents;
|
||||||
|
if (length(worldPos) > uGridRadius) discard;
|
||||||
|
vec2 pos = worldPos / uGridStep;
|
||||||
vec2 ddx = dFdx(pos);
|
vec2 ddx = dFdx(pos);
|
||||||
vec2 ddy = dFdy(pos);
|
vec2 ddy = dFdy(pos);
|
||||||
|
|
||||||
@@ -1262,7 +1267,7 @@ export default function PlayCanvasViewer({
|
|||||||
float fadeEnd = max(0.0, uFadeEnd);
|
float fadeEnd = max(0.0, uFadeEnd);
|
||||||
float fade = 1.0;
|
float fade = 1.0;
|
||||||
if (fadeEnd > fadeStart && fadeEnd > 0.0) {
|
if (fadeEnd > fadeStart && fadeEnd > 0.0) {
|
||||||
float d = length(pos);
|
float d = length(worldPos);
|
||||||
fade = 1.0 - smoothstep(fadeStart, fadeEnd, d);
|
fade = 1.0 - smoothstep(fadeStart, fadeEnd, d);
|
||||||
}
|
}
|
||||||
outAlpha *= fade;
|
outAlpha *= fade;
|
||||||
@@ -1312,6 +1317,8 @@ export default function PlayCanvasViewer({
|
|||||||
gridMaterial.setParameter('uFadeStart', 0)
|
gridMaterial.setParameter('uFadeStart', 0)
|
||||||
gridMaterial.setParameter('uFadeEnd', 0)
|
gridMaterial.setParameter('uFadeEnd', 0)
|
||||||
gridMaterial.setParameter('uResolution', 2)
|
gridMaterial.setParameter('uResolution', 2)
|
||||||
|
gridMaterial.setParameter('uGridStep', fx.grid.step)
|
||||||
|
gridMaterial.setParameter('uGridRadius', fx.grid.diameter / 2)
|
||||||
const gridHalfExtents = new pc.Vec2(500, 500)
|
const gridHalfExtents = new pc.Vec2(500, 500)
|
||||||
gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y])
|
gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y])
|
||||||
gridMaterial.update()
|
gridMaterial.update()
|
||||||
@@ -1528,7 +1535,7 @@ export default function PlayCanvasViewer({
|
|||||||
const cam = cameraEntityRef.current?.camera
|
const cam = cameraEntityRef.current?.camera
|
||||||
const vertical = (cam?.fov ?? 28) * Math.PI / 360
|
const vertical = (cam?.fov ?? 28) * Math.PI / 360
|
||||||
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
|
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
|
||||||
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
|
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
|
||||||
}
|
}
|
||||||
|
|
||||||
if (exposeSceneGraph || onSceneGraph) {
|
if (exposeSceneGraph || onSceneGraph) {
|
||||||
@@ -1617,7 +1624,7 @@ export default function PlayCanvasViewer({
|
|||||||
if (!aabb) return
|
if (!aabb) return
|
||||||
orbit.setState({
|
orbit.setState({
|
||||||
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
|
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
|
||||||
distance: Math.max(1.8, aabb.halfExtents.length() * 2.5),
|
distance: Math.max(1.8,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88),
|
||||||
azimuthDeg: 45,
|
azimuthDeg: 45,
|
||||||
elevationDeg: 10,
|
elevationDeg: 10,
|
||||||
})
|
})
|
||||||
@@ -1638,6 +1645,9 @@ export default function PlayCanvasViewer({
|
|||||||
|
|
||||||
const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled
|
const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled
|
||||||
grid.enabled = gridVisible
|
grid.enabled = gridVisible
|
||||||
|
grid.setLocalScale(fx.grid.diameter,1,fx.grid.diameter)
|
||||||
|
mat.setParameter('uGridStep',fx.grid.step)
|
||||||
|
mat.setParameter('uGridRadius',fx.grid.diameter/2)
|
||||||
const cX = toColor(fx.grid.colorX)
|
const cX = toColor(fx.grid.colorX)
|
||||||
const cZ = toColor(fx.grid.colorZ)
|
const cZ = toColor(fx.grid.colorZ)
|
||||||
const cMain = toColor(fx.grid.colorMain)
|
const cMain = toColor(fx.grid.colorMain)
|
||||||
@@ -1661,6 +1671,7 @@ export default function PlayCanvasViewer({
|
|||||||
mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0))
|
mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0))
|
||||||
mat.update()
|
mat.update()
|
||||||
}, [
|
}, [
|
||||||
|
fx.grid.step,fx.grid.diameter,
|
||||||
fx.grid.enabled,
|
fx.grid.enabled,
|
||||||
fx.grid.colorX,
|
fx.grid.colorX,
|
||||||
fx.grid.colorZ,
|
fx.grid.colorZ,
|
||||||
@@ -1690,7 +1701,7 @@ export default function PlayCanvasViewer({
|
|||||||
const app = appRef.current
|
const app = appRef.current
|
||||||
if (!app) return
|
if (!app) return
|
||||||
setWireframeForScene(app, fx.rendering.wireframe)
|
setWireframeForScene(app, fx.rendering.wireframe)
|
||||||
}, [fx.rendering.wireframe])
|
}, [fx.rendering.wireframe,modelVersion])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const frame: any = cameraFrameRef.current
|
const frame: any = cameraFrameRef.current
|
||||||
@@ -1703,9 +1714,10 @@ export default function PlayCanvasViewer({
|
|||||||
const app = appRef.current
|
const app = appRef.current
|
||||||
if (!app) return
|
if (!app) return
|
||||||
if (fx.lighting) {
|
if (fx.lighting) {
|
||||||
|
app.scene.ambientLight = new pc.Color(fx.lighting.ambientIntensity,fx.lighting.ambientIntensity,fx.lighting.ambientIntensity)
|
||||||
app.scene.exposure = fx.lighting.exposure
|
app.scene.exposure = fx.lighting.exposure
|
||||||
}
|
}
|
||||||
}, [fx.lighting?.exposure])
|
}, [fx.lighting?.exposure,fx.lighting.ambientIntensity])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const app = appRef.current
|
const app = appRef.current
|
||||||
@@ -1924,6 +1936,8 @@ export default function PlayCanvasViewer({
|
|||||||
envAtlasVersion,
|
envAtlasVersion,
|
||||||
skyboxVersion,
|
skyboxVersion,
|
||||||
modelVersion,
|
modelVersion,
|
||||||
|
materials,
|
||||||
|
assignments,
|
||||||
fx.envAtlas.enabled,
|
fx.envAtlas.enabled,
|
||||||
fx.envAtlas.background,
|
fx.envAtlas.background,
|
||||||
fx.envAtlas.reflection,
|
fx.envAtlas.reflection,
|
||||||
|
|||||||
@@ -1,393 +1,2 @@
|
|||||||
|
// Shared serializable contract; donor defaults remain available.
|
||||||
export type PostFxSettings = {
|
export * from '../../../core/roverScene/postFx';
|
||||||
lighting: {
|
|
||||||
exposure: number
|
|
||||||
skyBoxIntensity: number
|
|
||||||
}
|
|
||||||
envAtlas: {
|
|
||||||
enabled: boolean
|
|
||||||
background: boolean
|
|
||||||
reflection: boolean
|
|
||||||
intensity: number
|
|
||||||
reflectionIntensity: number
|
|
||||||
brightness: number
|
|
||||||
contrast: number
|
|
||||||
saturation: number
|
|
||||||
toneMapping: number
|
|
||||||
mip: number
|
|
||||||
rotation: number
|
|
||||||
}
|
|
||||||
skybox: {
|
|
||||||
enabled: boolean
|
|
||||||
background: boolean
|
|
||||||
reflection: boolean
|
|
||||||
intensity: number
|
|
||||||
reflectionIntensity: number
|
|
||||||
mip: number
|
|
||||||
rotation: number
|
|
||||||
colorA: string
|
|
||||||
colorB: string
|
|
||||||
}
|
|
||||||
rendering: {
|
|
||||||
backgroundColor: string
|
|
||||||
wireframe: boolean
|
|
||||||
renderFormat: number
|
|
||||||
renderFormatFallback0: number
|
|
||||||
renderFormatFallback1: number
|
|
||||||
stencil: boolean
|
|
||||||
renderTargetScale: number
|
|
||||||
samples: number
|
|
||||||
sharpness: number
|
|
||||||
toneMapping: number
|
|
||||||
sceneColorMap: boolean
|
|
||||||
sceneDepthMap: boolean
|
|
||||||
fog: 'none' | 'linear' | 'exp' | 'exp2'
|
|
||||||
fogColor: string
|
|
||||||
fogRange: [number, number]
|
|
||||||
fogDensity: number
|
|
||||||
fogStart: number
|
|
||||||
fogEnd: number
|
|
||||||
}
|
|
||||||
grid: {
|
|
||||||
enabled: boolean
|
|
||||||
colorX: string
|
|
||||||
colorZ: string
|
|
||||||
colorMain: string
|
|
||||||
alphaX: number
|
|
||||||
alphaZ: number
|
|
||||||
alphaMain: number
|
|
||||||
dotsEnabled: boolean
|
|
||||||
dotsColor: string
|
|
||||||
dotsAlpha: number
|
|
||||||
dotsDiameter: number
|
|
||||||
crossEnabled: boolean
|
|
||||||
crossColor: string
|
|
||||||
crossAlpha: number
|
|
||||||
crossLength: number
|
|
||||||
crossWidth: number
|
|
||||||
fadeStart: number
|
|
||||||
fadeEnd: number
|
|
||||||
}
|
|
||||||
ssao: {
|
|
||||||
type: 'none' | 'lighting' | 'combine'
|
|
||||||
blurEnabled: boolean
|
|
||||||
intensity: number
|
|
||||||
radius: number
|
|
||||||
samples: number
|
|
||||||
power: number
|
|
||||||
minAngle: number
|
|
||||||
scale: number
|
|
||||||
}
|
|
||||||
bloom: {
|
|
||||||
enabled: boolean
|
|
||||||
intensity: number
|
|
||||||
lastMipLevel: number
|
|
||||||
}
|
|
||||||
chromaticAberration: {
|
|
||||||
enabled: boolean
|
|
||||||
intensity: number
|
|
||||||
}
|
|
||||||
taa: {
|
|
||||||
enabled: boolean
|
|
||||||
jitter: number
|
|
||||||
}
|
|
||||||
grading: {
|
|
||||||
enabled: boolean
|
|
||||||
brightness: number
|
|
||||||
contrast: number
|
|
||||||
saturation: number
|
|
||||||
tint: string
|
|
||||||
}
|
|
||||||
lut: {
|
|
||||||
intensity: number
|
|
||||||
textureUrl?: string | null
|
|
||||||
}
|
|
||||||
vignette: {
|
|
||||||
enabled: boolean
|
|
||||||
intensity: number
|
|
||||||
inner: number
|
|
||||||
outer: number
|
|
||||||
curvature: number
|
|
||||||
color: string
|
|
||||||
}
|
|
||||||
directionalLight: {
|
|
||||||
enabled: boolean
|
|
||||||
color: string
|
|
||||||
intensity: number
|
|
||||||
azimuth: number
|
|
||||||
elevation: number
|
|
||||||
castShadows: boolean
|
|
||||||
shadowIntensity: number
|
|
||||||
shadowDistance: number
|
|
||||||
shadowResolution: number
|
|
||||||
shadowBias: number
|
|
||||||
normalOffsetBias: number
|
|
||||||
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
|
||||||
vsmBlurSize: number
|
|
||||||
}
|
|
||||||
shadowCatcher: {
|
|
||||||
enabled: boolean
|
|
||||||
size: number
|
|
||||||
yOffset: number
|
|
||||||
lightIntensity: number
|
|
||||||
lightColor: string
|
|
||||||
lightAzimuth: number
|
|
||||||
lightElevation: number
|
|
||||||
shadowIntensity: number
|
|
||||||
shadowDistance: number
|
|
||||||
shadowResolution: number
|
|
||||||
shadowBias: number
|
|
||||||
normalOffsetBias: number
|
|
||||||
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
|
||||||
vsmBlurSize: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_POSTFX: PostFxSettings = {
|
|
||||||
lighting: {
|
|
||||||
exposure: 1.21,
|
|
||||||
skyBoxIntensity: 0.86,
|
|
||||||
},
|
|
||||||
envAtlas: {
|
|
||||||
enabled: true,
|
|
||||||
background: false,
|
|
||||||
reflection: true,
|
|
||||||
intensity: 0.76,
|
|
||||||
reflectionIntensity: 0.6,
|
|
||||||
brightness: 1.65,
|
|
||||||
contrast: 1,
|
|
||||||
saturation: 1,
|
|
||||||
toneMapping: 0,
|
|
||||||
mip: 1,
|
|
||||||
rotation: 247,
|
|
||||||
},
|
|
||||||
skybox: {
|
|
||||||
enabled: false,
|
|
||||||
background: false,
|
|
||||||
reflection: true,
|
|
||||||
intensity: 0.62,
|
|
||||||
reflectionIntensity: 1,
|
|
||||||
mip: 0,
|
|
||||||
rotation: 0,
|
|
||||||
colorA: '#c5bfbf',
|
|
||||||
colorB: '#c7bcbc',
|
|
||||||
},
|
|
||||||
rendering: {
|
|
||||||
backgroundColor: '#111113',
|
|
||||||
wireframe: false,
|
|
||||||
renderFormat: 18,
|
|
||||||
renderFormatFallback0: 12,
|
|
||||||
renderFormatFallback1: 14,
|
|
||||||
stencil: false,
|
|
||||||
renderTargetScale: 1,
|
|
||||||
samples: 4,
|
|
||||||
sharpness: 0,
|
|
||||||
toneMapping: 4,
|
|
||||||
sceneColorMap: false,
|
|
||||||
sceneDepthMap: false,
|
|
||||||
fog: 'exp',
|
|
||||||
fogColor: '#dcc2ff',
|
|
||||||
fogRange: [0, 100],
|
|
||||||
fogDensity: 0.008,
|
|
||||||
fogStart: 0,
|
|
||||||
fogEnd: 100,
|
|
||||||
},
|
|
||||||
grid: {
|
|
||||||
enabled: true,
|
|
||||||
colorX: '#ffffff',
|
|
||||||
colorZ: '#ffffff',
|
|
||||||
colorMain: '#7a3cff',
|
|
||||||
alphaX: 0.18,
|
|
||||||
alphaZ: 0.18,
|
|
||||||
alphaMain: 0.6,
|
|
||||||
dotsEnabled: false,
|
|
||||||
dotsColor: '#ffffff',
|
|
||||||
dotsAlpha: 0.5,
|
|
||||||
dotsDiameter: 0.06,
|
|
||||||
crossEnabled: false,
|
|
||||||
crossColor: '#ffffff',
|
|
||||||
crossAlpha: 0.5,
|
|
||||||
crossLength: 0.5,
|
|
||||||
crossWidth: 0.06,
|
|
||||||
fadeStart: 0,
|
|
||||||
fadeEnd: 0,
|
|
||||||
},
|
|
||||||
ssao: {
|
|
||||||
type: 'none',
|
|
||||||
blurEnabled: true,
|
|
||||||
intensity: 0.5,
|
|
||||||
radius: 30,
|
|
||||||
samples: 12,
|
|
||||||
power: 6,
|
|
||||||
minAngle: 10,
|
|
||||||
scale: 1,
|
|
||||||
},
|
|
||||||
bloom: {
|
|
||||||
enabled: true,
|
|
||||||
intensity: 0.03,
|
|
||||||
lastMipLevel: 4,
|
|
||||||
},
|
|
||||||
chromaticAberration: {
|
|
||||||
enabled: true,
|
|
||||||
intensity: 30,
|
|
||||||
},
|
|
||||||
taa: {
|
|
||||||
enabled: false,
|
|
||||||
jitter: 1,
|
|
||||||
},
|
|
||||||
grading: {
|
|
||||||
enabled: true,
|
|
||||||
brightness: 0.837,
|
|
||||||
contrast: 1.1,
|
|
||||||
saturation: 1.126,
|
|
||||||
tint: '#ffffff',
|
|
||||||
},
|
|
||||||
lut: {
|
|
||||||
intensity: 1,
|
|
||||||
textureUrl: null,
|
|
||||||
},
|
|
||||||
vignette: {
|
|
||||||
enabled: true,
|
|
||||||
intensity: 1,
|
|
||||||
inner: 0.25,
|
|
||||||
outer: 1.52,
|
|
||||||
curvature: 0.78,
|
|
||||||
color: '#000000',
|
|
||||||
},
|
|
||||||
directionalLight: {
|
|
||||||
enabled: true,
|
|
||||||
color: '#ffffff',
|
|
||||||
intensity: 0.4,
|
|
||||||
azimuth: 0,
|
|
||||||
elevation: 0,
|
|
||||||
castShadows: false,
|
|
||||||
shadowIntensity: 0.5,
|
|
||||||
shadowDistance: 16,
|
|
||||||
shadowResolution: 1024,
|
|
||||||
shadowBias: 0,
|
|
||||||
normalOffsetBias: 0,
|
|
||||||
shadowType: 'vsm16',
|
|
||||||
vsmBlurSize: 8,
|
|
||||||
},
|
|
||||||
shadowCatcher: {
|
|
||||||
enabled: true,
|
|
||||||
size: 9,
|
|
||||||
yOffset: 0.001,
|
|
||||||
lightIntensity: 0.3,
|
|
||||||
lightColor: '#ffffff',
|
|
||||||
lightAzimuth: 20,
|
|
||||||
lightElevation: 60,
|
|
||||||
shadowIntensity: 0.29,
|
|
||||||
shadowDistance: 16,
|
|
||||||
shadowResolution: 2048,
|
|
||||||
shadowBias: 0,
|
|
||||||
normalOffsetBias: 0,
|
|
||||||
shadowType: 'vsm16',
|
|
||||||
vsmBlurSize: 8,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
function isObject(value: any): value is Record<string, any> {
|
|
||||||
return !!value && typeof value === 'object' && !Array.isArray(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
|
|
||||||
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
|
|
||||||
|
|
||||||
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
|
|
||||||
const merge = (target: any, source: any) => {
|
|
||||||
if (!isObject(source)) return
|
|
||||||
for (const [key, value] of Object.entries(source)) {
|
|
||||||
if (isObject(value)) {
|
|
||||||
if (!isObject(target[key])) target[key] = {}
|
|
||||||
merge(target[key], value)
|
|
||||||
} else {
|
|
||||||
target[key] = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
merge(out, raw)
|
|
||||||
|
|
||||||
const legacy: any = raw as any
|
|
||||||
if (legacy?.hdrLight) {
|
|
||||||
const src = legacy.hdrLight
|
|
||||||
const env = legacy?.envAtlas ?? {}
|
|
||||||
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
|
|
||||||
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
|
|
||||||
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
|
|
||||||
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
|
|
||||||
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
|
|
||||||
}
|
|
||||||
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
|
|
||||||
if (typeof legacy.hdrReflection.enabled === 'boolean') {
|
|
||||||
out.envAtlas.reflection = legacy.hdrReflection.enabled
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
|
|
||||||
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
|
|
||||||
}
|
|
||||||
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
|
|
||||||
out.envAtlas.brightness = 1
|
|
||||||
}
|
|
||||||
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
|
|
||||||
out.envAtlas.contrast = 1
|
|
||||||
}
|
|
||||||
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
|
|
||||||
out.envAtlas.saturation = 1
|
|
||||||
}
|
|
||||||
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
|
|
||||||
out.envAtlas.toneMapping = 0
|
|
||||||
}
|
|
||||||
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
|
|
||||||
out.skybox.reflectionIntensity = out.skybox.intensity
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.enabled !== 'boolean') {
|
|
||||||
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.colorX !== 'string') {
|
|
||||||
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.colorZ !== 'string') {
|
|
||||||
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.colorMain !== 'string') {
|
|
||||||
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.alphaX !== 'number') {
|
|
||||||
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.alphaZ !== 'number') {
|
|
||||||
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.alphaMain !== 'number') {
|
|
||||||
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
|
|
||||||
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.dotsColor !== 'string') {
|
|
||||||
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
|
|
||||||
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
|
|
||||||
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
|
|
||||||
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.crossColor !== 'string') {
|
|
||||||
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
|
|
||||||
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.crossLength !== 'number') {
|
|
||||||
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
|
|
||||||
}
|
|
||||||
if (out.grid && typeof out.grid.crossWidth !== 'number') {
|
|
||||||
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
|
|
||||||
}
|
|
||||||
return out as PostFxSettings
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {useEffect,type RefObject} from 'react';
|
||||||
|
import * as pc from 'playcanvas';
|
||||||
|
export function useLutTexture(appRef:RefObject<pc.Application|null>,frameRef:RefObject<any>,textureRef:RefObject<pc.Texture|null>,url:string|null|undefined,ready:boolean,onError?:()=>void){
|
||||||
|
useEffect(()=>{
|
||||||
|
const app=appRef.current;let cancelled=false;
|
||||||
|
const clear=()=>{if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=null;frameRef.current.update?.();}textureRef.current?.destroy();textureRef.current=null;};
|
||||||
|
clear();if(!app||!ready||!url)return;
|
||||||
|
const img=new Image();img.onload=()=>{
|
||||||
|
if(cancelled)return;
|
||||||
|
if(img.width!==256||img.height!==16){onError?.();return;}
|
||||||
|
const texture=new pc.Texture(app.graphicsDevice,{name:'Rover color LUT',format:pc.PIXELFORMAT_SRGBA8,mipmaps:false,minFilter:pc.FILTER_LINEAR,magFilter:pc.FILTER_LINEAR,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
|
||||||
|
texture.setSource(img);textureRef.current=texture;
|
||||||
|
if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=texture;frameRef.current.update?.();}
|
||||||
|
};img.onerror=()=>{if(!cancelled)onError?.();};img.src=url;
|
||||||
|
return()=>{cancelled=true;clear();};
|
||||||
|
},[appRef,frameRef,textureRef,url,ready,onError]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import {useEffect,useRef,type RefObject} from 'react';
|
||||||
|
import * as pc from 'playcanvas';
|
||||||
|
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
|
||||||
|
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
|
||||||
|
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
|
||||||
|
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){
|
||||||
|
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState};
|
||||||
|
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
|
||||||
|
const generation=useRef(0);
|
||||||
|
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
|
||||||
|
const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
|
||||||
|
useEffect(()=>{
|
||||||
|
const app=appRef.current;if(!app||!modelVersion||!materials)return;
|
||||||
|
const current=++generation.current;let pending=0,failed=false;
|
||||||
|
const map=new Map<string,pc.StandardMaterial>();
|
||||||
|
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
|
||||||
|
if(!(mi.material instanceof pc.StandardMaterial))continue;
|
||||||
|
if(!originalGroups.current.has(mi))originalGroups.current.set(mi,{id:mi.material.name,material:mi.material});
|
||||||
|
const source=originalGroups.current.get(mi)!;map.set(source.id,source.material);
|
||||||
|
}
|
||||||
|
for(const id of Object.keys(materials))if(id.startsWith('custom/')){
|
||||||
|
if(!customMaterials.current.has(id)){const m=new pc.StandardMaterial();m.name=id;customMaterials.current.set(id,m);}
|
||||||
|
map.set(id,customMaterials.current.get(id)!);
|
||||||
|
}
|
||||||
|
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
|
||||||
|
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(assignments?.[source.id]??source.id)??source.material;
|
||||||
|
}
|
||||||
|
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
|
||||||
|
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
|
||||||
|
(m as any)[maps[slot]]=texture;
|
||||||
|
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
|
||||||
|
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
|
||||||
|
m.update();
|
||||||
|
};
|
||||||
|
const used=new Set<string>();
|
||||||
|
for(const [id,spec] of Object.entries(materials)){
|
||||||
|
const m=map.get(id);if(!m)continue;
|
||||||
|
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
|
||||||
|
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
|
||||||
|
// Specular factor is independent from the donor's global IBL multiplier.
|
||||||
|
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
|
||||||
|
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
|
||||||
|
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
|
||||||
|
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
|
||||||
|
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||||
|
m.depthWrite=m.blendType===pc.BLEND_NONE;
|
||||||
|
for(const slot of Object.keys(maps) as TextureSlot[]){
|
||||||
|
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
|
||||||
|
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
|
||||||
|
let item=textures.current.get(key);
|
||||||
|
if(!item){
|
||||||
|
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
|
||||||
|
item={promise};textures.current.set(key,item);const cached=item;
|
||||||
|
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
|
||||||
|
}
|
||||||
|
if(item.texture)applyTexture(m,slot,item.texture,spec);
|
||||||
|
else{
|
||||||
|
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.update();
|
||||||
|
}
|
||||||
|
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
|
||||||
|
onTextureState?.(pending?'loading':'ready');
|
||||||
|
return()=>{generation.current++;};
|
||||||
|
},[materials,assignments,modelVersion,appRef,onTextureState]);
|
||||||
|
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
|
||||||
|
useEffect(()=>{
|
||||||
|
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
|
||||||
|
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return;
|
||||||
|
const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null;
|
||||||
|
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;};
|
||||||
|
const up=(e:PointerEvent)=>{
|
||||||
|
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return;
|
||||||
|
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));
|
||||||
|
picker.prepare(camera.camera!,app.scene);
|
||||||
|
const hit=picker.getSelection(e.clientX-rect.left,e.clientY-rect.top).find(mi=>!!latest.current.materials?.[mi.material.name]);
|
||||||
|
if(hit instanceof pc.MeshInstance){const source=originalGroups.current.get(hit);if(source)latest.current.onMaterialPick?.(hit.material.name,source.id);}
|
||||||
|
};
|
||||||
|
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
|
||||||
|
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();};
|
||||||
|
},[editing,modelVersion,appRef,cameraRef,canvasRef]);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
|
.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 .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__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:var(--nodedc-space-3); left:var(--nodedc-space-3); }
|
.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; }
|
||||||
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
|
.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-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
|
.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); }
|
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
|
||||||
@container (max-width: 380px) {
|
@container (max-width: 380px) {
|
||||||
.rover-view__authority { top:48px; bottom:auto; }
|
.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 { 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-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||||
|
|||||||
@@ -9,12 +9,14 @@ import { useComputeContours } from "../../core/system/ComputeContourContext";
|
|||||||
interface SystemNavigationPanelProps {
|
interface SystemNavigationPanelProps {
|
||||||
title: string;
|
title: string;
|
||||||
onAdd: () => void;
|
onAdd: () => void;
|
||||||
|
onNavigateRoot: () => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SystemNavigationPanel({
|
export function SystemNavigationPanel({
|
||||||
title,
|
title,
|
||||||
onAdd,
|
onAdd,
|
||||||
|
onNavigateRoot,
|
||||||
onClose,
|
onClose,
|
||||||
}: SystemNavigationPanelProps) {
|
}: SystemNavigationPanelProps) {
|
||||||
const { contours, selectedContour, selectContour } = useComputeContours();
|
const { contours, selectedContour, selectContour } = useComputeContours();
|
||||||
@@ -40,7 +42,7 @@ export function SystemNavigationPanel({
|
|||||||
description: contour.expected_node_id,
|
description: contour.expected_node_id,
|
||||||
icon: <Icon name="apps" />,
|
icon: <Icon name="apps" />,
|
||||||
active: selectedContour?.contour_id === contour.contour_id,
|
active: selectedContour?.contour_id === contour.contour_id,
|
||||||
onSelect: () => selectContour(contour.contour_id),
|
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
|
||||||
}))}
|
}))}
|
||||||
items={[]}
|
items={[]}
|
||||||
onItemChange={() => undefined}
|
onItemChange={() => undefined}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import type { WorkspaceDefinition } from "../productModel";
|
|||||||
|
|
||||||
interface ApplicationPanelActionsOptions {
|
interface ApplicationPanelActionsOptions {
|
||||||
definition: WorkspaceDefinition | null;
|
definition: WorkspaceDefinition | null;
|
||||||
onAddVehicle?: () => void;
|
|
||||||
refreshRuntime: () => void;
|
refreshRuntime: () => void;
|
||||||
resetConnectionScenario?: () => Promise<boolean>;
|
resetConnectionScenario?: () => Promise<boolean>;
|
||||||
connectionScenarioResetting: boolean;
|
connectionScenarioResetting: boolean;
|
||||||
@@ -45,7 +44,6 @@ export function deviceRuntimeUtilityAction({
|
|||||||
|
|
||||||
export function useApplicationPanelActions({
|
export function useApplicationPanelActions({
|
||||||
definition,
|
definition,
|
||||||
onAddVehicle,
|
|
||||||
refreshRuntime,
|
refreshRuntime,
|
||||||
resetConnectionScenario,
|
resetConnectionScenario,
|
||||||
connectionScenarioResetting,
|
connectionScenarioResetting,
|
||||||
@@ -56,7 +54,6 @@ export function useApplicationPanelActions({
|
|||||||
}: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] {
|
}: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] {
|
||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
const actions: ApplicationPanelUtilityAction[] = [];
|
const actions: ApplicationPanelUtilityAction[] = [];
|
||||||
if (definition?.kind === "vehicles" && onAddVehicle) actions.push({ label: "Добавить аппарат", icon: "plus", onClick: onAddVehicle });
|
|
||||||
if (definition?.kind === "device") {
|
if (definition?.kind === "device") {
|
||||||
actions.push(deviceRuntimeUtilityAction({
|
actions.push(deviceRuntimeUtilityAction({
|
||||||
refreshRuntime,
|
refreshRuntime,
|
||||||
@@ -81,7 +78,6 @@ export function useApplicationPanelActions({
|
|||||||
return actions;
|
return actions;
|
||||||
}, [
|
}, [
|
||||||
definition,
|
definition,
|
||||||
onAddVehicle,
|
|
||||||
refreshRuntime,
|
refreshRuntime,
|
||||||
resetConnectionScenario,
|
resetConnectionScenario,
|
||||||
connectionScenarioResetting,
|
connectionScenarioResetting,
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type {CellularNetwork,CellularStamp,TrackerTelemetry} from './vps';
|
||||||
|
|
||||||
|
export function cellularFresh(value:CellularStamp|undefined,now=Date.now()/1000){
|
||||||
|
return !!value&&now-value.measured_at>=0&&now-value.measured_at<90;
|
||||||
|
}
|
||||||
|
// Public INTERNAL TAG table examples. A serving network never selects an APN.
|
||||||
|
const networks:Record<string,string>={'250:1':'МТС','250:2':'МегаФон','250:99':'Билайн'};
|
||||||
|
export function cellularCardOperator(telemetry:TrackerTelemetry|undefined,slot:string){
|
||||||
|
const card=telemetry?.sim_identity?.slots[slot];
|
||||||
|
const home=card?.binding_current?card.known_card?.home_network:undefined;
|
||||||
|
return home?({'25001':'МТС','25002':'МегаФон','25099':'Билайн'} as Record<string,string>)[home]:undefined;
|
||||||
|
}
|
||||||
|
export function cellularOperator(value:CellularNetwork|undefined){
|
||||||
|
return value?.mcc==null?undefined:networks[`${value.mcc}:${value.mnc}`];
|
||||||
|
}
|
||||||
|
/** Losing freshness does not prove card removal; retain explicitly labelled history. */
|
||||||
|
export function cellularSimOptions(telemetry:TrackerTelemetry|undefined,now=Date.now()/1000){
|
||||||
|
const status=telemetry?.cellular?.status;
|
||||||
|
if(!status||status.measured_at>now)return [];
|
||||||
|
const current=!!telemetry?.online&&cellularFresh(status,now);
|
||||||
|
return (['1','2'] as const).filter(slot=>[1,2,3,5,6].includes(status!.sim_states[slot])).map(slot=>{
|
||||||
|
const network=telemetry?.cellular?.networks[slot];
|
||||||
|
const registered=[1,5].includes(status!.sim_states[slot]);
|
||||||
|
const knownNetwork=network&&network.measured_at<=now&&(current?cellularFresh(network,now):network.measured_at<=status.measured_at);
|
||||||
|
const operator=cellularCardOperator(telemetry,slot)??(registered&&knownNetwork?cellularOperator(network):undefined);
|
||||||
|
return {value:slot,label:`SIM ${slot} (${operator??'оператор не определён'})${current?'':' · последние данные'}`};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function cellularSimCurrent(telemetry:TrackerTelemetry|undefined,slot:number,now=Date.now()/1000){
|
||||||
|
return !!telemetry?.online&&cellularFresh(telemetry.cellular?.status,now)&&[1,2,3,5,6].includes(telemetry.cellular!.status!.sim_states[String(slot)]);
|
||||||
|
}
|
||||||
|
export function cellularNetworkLabel(value:CellularNetwork|undefined){
|
||||||
|
if(!value||value.mcc===null)return 'Оператор не определён';
|
||||||
|
const code=`${String(value.mcc).padStart(3,'0')}-${String(value.mnc).padStart(2,'0')}`;
|
||||||
|
const name=cellularOperator(value);
|
||||||
|
return name?`${name} · ${code}`:`Оператор не определён · код ${code}`;
|
||||||
|
}
|
||||||
|
export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
|
||||||
|
const status=telemetry?.cellular?.status;
|
||||||
|
const current=!!telemetry?.online&&cellularFresh(status,now);
|
||||||
|
const absent=current&&status?.sim_states[slot]===0;
|
||||||
|
// A fresh removal invalidates the old serving-network reading for this slot.
|
||||||
|
const network=absent?undefined:telemetry?.cellular?.networks[slot];
|
||||||
|
const selected=current&&!absent&&status?.active_sim===Number(slot);
|
||||||
|
const internet=selected&&status?.gsm_state===4;
|
||||||
|
const role=!current?'Последнее полученное состояние':absent?'SIM не обнаружена':internet?'Используется для интернета':selected?'Выбрана модемом':'Не выбрана для интернета';
|
||||||
|
return {current,absent,network,internet,role};
|
||||||
|
}
|
||||||
|
export function cellularSimLabel(value:number|undefined){
|
||||||
|
return ({0:'SIM не обнаружена',1:'Регистрация в домашней сети',2:'Поиск сети',3:'Регистрация отклонена',5:'Регистрация в роуминге',6:'Ошибка PIN'} as Record<number,string>)[value??-1]??'Нет сведений';
|
||||||
|
}
|
||||||
|
export function cellularModemLabel(value:number|undefined){
|
||||||
|
return ({0:'Модем выключен',1:'Модем включён',2:'Модем отвечает',3:'Подключение GPRS',4:'GPRS подключён'} as Record<number,string>)[value??-1]??'Нет сведений о модеме';
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from './equipment';
|
||||||
|
|
||||||
|
export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string}
|
||||||
|
export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean}
|
||||||
|
export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]}
|
||||||
|
export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number;durable_kinds?:string[]}
|
||||||
|
export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state);
|
||||||
|
export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true;
|
||||||
|
export const commandStatus=(state:string)=>({accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Нет подтверждения',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус';
|
||||||
|
export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
|
||||||
|
export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU');
|
||||||
|
export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`;
|
||||||
|
export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):CommandEntry[]{
|
||||||
|
const values=new Map(current.map(item=>[item.id,item]));for(const item of incoming){const old=values.get(item.id);if(!old||(item.updated_at??0)>=(old.updated_at??0))values.set(item.id,item);}
|
||||||
|
return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0));
|
||||||
|
}
|
||||||
|
export function commandReason(value:CommandEntry):string{
|
||||||
|
return ({queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??'';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function commandReceipt(value:CommandEntry):string{
|
||||||
|
if(value.device_code===undefined)return 'Ответ трекера не получен';
|
||||||
|
return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2';
|
||||||
|
}
|
||||||
|
export const commandEntryStatus=(value:CommandEntry)=>value.durable&&commandPending(value.state)&&value.stop_requested?'Остановка повторов':value.durable&&commandPending(value.state)&&value.runtime_phase&&value.runtime_phase!=='executing'?({'waiting-link':'Ожидает связи с B2','retry-wait':'Ожидает следующей попытки','checking-result':'Проверка состояния B2',reconciling:'Уточнение результата у VPS'} as Record<string,string>)[value.runtime_phase]??commandStatus(value.state):value.state==='dispatched'&&value.device_accepted_at!==undefined?commandStatus('device_accepted'):commandStatus(value.state);
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
/** Independent equipment is owned by Fleet, never by a vehicle's Node transport. */
|
||||||
|
export interface EquipmentPolicy {
|
||||||
|
schema_version:1;
|
||||||
|
endpoint:{host:string;port:number;slot:number}|null;
|
||||||
|
connectivity:{strategy:'preserve'|'manual'|'operator'|'sim'|'both'|'native';apn1:string;apn2:string;apn?:string|null;preset_id?:string|null;sim_slot?:number;activate?:boolean;automatic?:boolean};
|
||||||
|
parameters:Record<string,number>;
|
||||||
|
}
|
||||||
|
export interface EquipmentField {key:string;label:string;group:string;min:number;max:number}
|
||||||
|
export interface ConnectivityPreset {id:string;label:string;apn:string}
|
||||||
|
export interface EquipmentModel {id:string;label:string;fields:EquipmentField[];profile_schema:number;connectivity_presets?:ConnectivityPreset[];usb_write_firmware?:string[]}
|
||||||
|
export interface EquipmentProfile {id:string;name:string;model_id:string;settings:EquipmentPolicy;created_at:number}
|
||||||
|
export interface EquipmentObservation {
|
||||||
|
output_modes?:Record<string,number>;configuration_read_at?:number;configuration_transport?:'vps';
|
||||||
|
supported_profile_fields?:string[];read_at:number;model:string;device_id:string;imei_suffix:string;firmware:string;
|
||||||
|
sim1_iccid_reported_suffix:string|null;sim1_iccid_reported_length:number;
|
||||||
|
sim2_iccid_reported_suffix:string|null;sim2_iccid_reported_length:number;
|
||||||
|
configuration:{record_count:number;apn1:string;apn2:string;servers:{slot:number;host:string;port:number;protocol_code:number}[]};
|
||||||
|
provisioned:false;
|
||||||
|
}
|
||||||
|
export interface EquipmentCandidate {id:string;model_id:string;observed:EquipmentObservation;settings:EquipmentPolicy;expires_at:number}
|
||||||
|
export type EquipmentCommand = {kind:'request-position'}|{kind:'restart'}|{kind:'pulse-output';pin:number;seconds:number}|{kind:'set-output';pin:number;enabled:boolean};
|
||||||
|
export interface EquipmentNetworkOperation {reason?:string;id:string;durable?:boolean;runtime_phase?:string;attempt_count?:number;next_attempt_at?:number;attempt_expires_at?:number;stop_requested?:boolean;reconcile_pending?:boolean;read_only?:boolean;state:string;stage?:string;scope:'server1'|'configuration'|'sim-selection'|'command';sim_policy?:'both';sim_slot?:number;active_sim?:number;command?:EquipmentCommand;kind?:EquipmentCommand['kind']|'read-settings'|'configure-server1'|'read-configuration'|'configure-all'|'select-sim';unchanged?:boolean;record_count?:number;configuration_sha256?:string;created_at?:number;expires_at?:number;dispatched_at?:number;queue_seconds?:number;roundtrip_seconds?:number;device_code?:number;device_accepted_at?:number;reconnected_at?:number;reconnect_seconds?:number;telemetry_measured_at?:number;verified_at?:number;server1?:{host:string;port:number}}
|
||||||
|
export interface IndependentDevice {network_operation?:EquipmentNetworkOperation;network_server1?:{host:string;port:number};id:string;name:string;model_id:string;vehicle_id:string;revision:number;observed:EquipmentObservation;settings:EquipmentPolicy;profile_id:string|null;policy_state:'saved'|'applied'|'unchanged'|'uncertain'|'rolled_back'|'not_applied'|'not_started';updated_at:number}
|
||||||
|
export async function equipmentRequest<T>(path:string,method='GET',body?:unknown):Promise<T>{
|
||||||
|
const response=await fetch(`/api/v1/fleet/equipment${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(path.endsWith('/apply')?120000:45000)});
|
||||||
|
if(!response.ok){const value=await response.json().catch(()=>({}));throw new Error(typeof value.detail==='string'?value.detail:'Не удалось выполнить действие с оборудованием.');}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
export const emptyEquipmentPolicy=():EquipmentPolicy=>({schema_version:1,endpoint:null,connectivity:{strategy:'preserve',apn1:'',apn2:''},parameters:{}});
|
||||||
|
/** Compare settings by value, including server defaults; JSON key order is not an edit. */
|
||||||
|
export function equipmentPolicyEqual(a:EquipmentPolicy,b:EquipmentPolicy):boolean{
|
||||||
|
const canonical=(p:EquipmentPolicy)=>{
|
||||||
|
const c=p.connectivity;
|
||||||
|
return JSON.stringify([p.schema_version,p.endpoint?[p.endpoint.host,p.endpoint.port,p.endpoint.slot]:null,[c.strategy,c.apn1,c.apn2,c.apn??null,c.preset_id??null,c.sim_slot??1,c.activate??false,c.automatic??false],Object.entries(p.parameters).sort(([x],[y])=>x.localeCompare(y))]);
|
||||||
|
};
|
||||||
|
return canonical(a)===canonical(b);
|
||||||
|
}
|
||||||
|
/** A saved SIM target does not itself request another modem restart. */
|
||||||
|
export function simSelectionIntent(draft:EquipmentPolicy,saved:EquipmentPolicy,selected:boolean):boolean{
|
||||||
|
return (['both','native'].includes(draft.connectivity.strategy)||draft.connectivity.strategy==='sim'&&draft.connectivity.activate===true)&&(selected||!equipmentPolicyEqual({...draft,endpoint:null,parameters:{}},{...saved,endpoint:null,parameters:{}}));
|
||||||
|
}
|
||||||
|
/** Selecting a SIM requests exclusive data service; keep its current APN unless edited. */
|
||||||
|
export function selectInternetSim(policy:EquipmentPolicy,slot:number):EquipmentPolicy{
|
||||||
|
if(![1,2].includes(slot))return policy;
|
||||||
|
const current=policy.connectivity;
|
||||||
|
const apn=current.strategy==='sim'&¤t.sim_slot===slot?current.apn??null:null;
|
||||||
|
return {...policy,connectivity:{strategy:'sim',sim_slot:slot,activate:true,automatic:apn===null,apn,apn1:'',apn2:'',preset_id:null}};
|
||||||
|
}
|
||||||
|
export function allowBothInternetSims(policy:EquipmentPolicy,withoutApn=false):EquipmentPolicy{
|
||||||
|
return {...policy,connectivity:{strategy:withoutApn?'native':'both',apn1:'',apn2:''}};
|
||||||
|
}
|
||||||
|
export function equipmentApplyMessage(state:IndependentDevice['policy_state']):string{
|
||||||
|
return {saved:'Настройки сохранены в Mission Core.',applied:'Настройки записаны в трекер и проверены чтением.',unchanged:'Настройки трекера уже совпадают с сохранёнными.',uncertain:'Результат записи не подтверждён. Прочитайте настройки повторно перед следующим действием.',rolled_back:'Проверка записи не прошла. Предыдущие настройки восстановлены.',not_applied:'Трекер сохранил прежние настройки. Изменения не применены.',not_started:'Запись не началась. Прочитайте устройство повторно и проверьте настройки.'}[state];
|
||||||
|
}
|
||||||
|
export function policyError(policy:EquipmentPolicy,fields:EquipmentField[]):string{
|
||||||
|
if(policy.endpoint&&(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i.test(policy.endpoint.host)||!Number.isInteger(policy.endpoint.port)||policy.endpoint.port<1||policy.endpoint.port>65535))return 'Укажите DNS/IP и порт от 1 до 65535.';
|
||||||
|
if(policy.connectivity.strategy==='sim'&&(![1,2].includes(policy.connectivity.sim_slot??1)||!/^([A-Za-z0-9.-]{0,29})$/.test(policy.connectivity.apn??'')))return 'Проверьте APN выбранной SIM.';
|
||||||
|
if(policy.connectivity.strategy==='manual'&&!policy.connectivity.apn1.trim())return 'Укажите APN основной SIM.';
|
||||||
|
if(policy.connectivity.strategy==='operator'&&(!policy.connectivity.preset_id||![1,2].includes(policy.connectivity.sim_slot??1)))return 'Выберите настройки оператора и SIM.';
|
||||||
|
for(const [key,value]of Object.entries(policy.parameters)){const field=fields.find(f=>f.key===key);if(!field||!Number.isInteger(value)||value<field.min||value>field.max)return `Проверьте значение: ${field?.label??key}.`;}
|
||||||
|
for(const [a,b]of [['243','244'],['245','246']])if(policy.parameters[a]!==undefined&&policy.parameters[b]!==undefined&&policy.parameters[a]>policy.parameters[b])return 'Минимальное значение превышает максимальное.';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A local deadline ends the spinner, not the VPS operation or the write interlock. */
|
||||||
|
export function networkOperationProgress(operation?:EquipmentNetworkOperation,now=Date.now()/1000){
|
||||||
|
const pending=!!operation&&['submitting','queued','dispatched'].includes(operation.state);
|
||||||
|
const deadline=operation?.durable?undefined:operation?.expires_at??(operation?.created_at!==undefined?operation.created_at+240:undefined);
|
||||||
|
const overdue=pending&&deadline!==undefined&&now>=deadline;
|
||||||
|
const remaining=pending&&deadline!==undefined?Math.max(0,Math.ceil(deadline-now)):undefined;
|
||||||
|
return {pending,overdue,waiting:pending&&!overdue,remaining};
|
||||||
|
}
|
||||||
|
export function configurationWriteNotStarted(operation?:EquipmentNetworkOperation):boolean{
|
||||||
|
return !!operation&&['configuration','sim-selection'].includes(operation.scope)&&!operation.read_only&&operation.stage==='preflight'&&['unconfirmed','expired'].includes(operation.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function networkOperationMessage(operation?:EquipmentNetworkOperation):string{
|
||||||
|
if(operation?.reason==='sim_card_changed')return 'Карта в выбранном слоте изменилась. Выберите SIM заново и сохраните настройки.';
|
||||||
|
if(!operation)return 'Сохранение профиля и подтверждение трекером отображаются отдельно.';
|
||||||
|
if(operation.durable){
|
||||||
|
if(operation.stop_requested&&['submitting','queued','dispatched'].includes(operation.state))return 'Останавливаем дальнейшие повторы. Уже отправленная попытка может завершиться.';
|
||||||
|
if(operation.state==='stopped')return 'Дальнейшие попытки остановлены. История отправок сохранена.';
|
||||||
|
if(operation.state==='accepted')return 'B2 подтвердил приём команды перезапуска. Возвращение на связь пока не подтверждено; повторного перезапуска не будет.';
|
||||||
|
if(['submitting','queued','dispatched'].includes(operation.state))return ({reconciling:'Уточняем сохранённый результат у VPS. Задание остаётся в очереди.', 'waiting-identity':'Ожидаем подтверждение карты в выбранном слоте. Настройки пока не отправляются.', 'waiting-link':'Задание сохранено. Ожидаем свежую связь с B2.', 'retry-wait':'Ответ предыдущей попытки не подтверждён. Задание ожидает следующую попытку.', 'checking-result':'Читаем фактические настройки B2 перед решением о повторной записи.', executing:operation.stage==='preflight'?'Читаем текущую конфигурацию B2…':operation.stage==='write'?'Передаём настройки B2…':operation.stage==='verify'?'Проверяем настройки повторным чтением…':operation.stage==='restart'?'Настройки проверены. Ожидаем свежую связь после перезапуска B2…':'Ожидаем результат текущей попытки от B2.'} as Record<string,string>)[operation.runtime_phase??'']??'Задание сохранено. Передаём его на VPS…';
|
||||||
|
}
|
||||||
|
if(operation.scope==='command'&&operation.command?.kind==='restart'){
|
||||||
|
if(operation.state==='dispatched')return 'Команда перезапуска отправлена. Ожидаем свежие данные по новому соединению.';
|
||||||
|
if(operation.state==='reconnected')return 'После команды перезапуска трекер прислал свежие данные по новому соединению.';
|
||||||
|
if(operation.state==='unconfirmed')return 'Команда отправлена, но возвращение трекера на связь не подтверждено. Автоматического повторения не будет.';
|
||||||
|
}
|
||||||
|
if(operation.scope==='command')return ({submitting:'Передача команды на VPS…',queued:'VPS ожидает соединение с трекером…',dispatched:'Команда отправлена трекеру. Ожидаем ответ.',device_confirmed:'Трекер подтвердил приём команды.',device_rejected:'Трекер отклонил команду.',expired:'Срок отправки истёк. Команда не отправлена.',unconfirmed:'Команда отправлена, но её выполнение не подтверждено отдельным ответом.',uncertain:'Результат команды неизвестен. Автоматического повторения не будет.'} as Record<string,string>)[operation.state]??'Статус команды недоступен.';
|
||||||
|
if(configurationWriteNotStarted(operation))return 'Трекер не прислал конфигурацию до истечения срока ожидания. Запись настроек не началась. Прочитайте настройки через VPS перед новой попыткой.';
|
||||||
|
if(operation.scope==='sim-selection'){
|
||||||
|
if(operation.sim_policy==='both'){
|
||||||
|
if(operation.state==='sim_selected')return `Обе SIM разрешены. Связь через SIM ${operation.active_sim} подтверждена свежими данными B2.`;
|
||||||
|
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?'Обе SIM разрешены. Перезапускаем B2 и ждём восстановления интернета…':'Настройки записаны, но возвращение B2 на связь пока не подтверждено.';
|
||||||
|
}
|
||||||
|
if(operation.state==='sim_selected')return `SIM ${operation.active_sim} подключена к интернету. Получены свежие данные B2 через VPS.`;
|
||||||
|
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?`Настройки проверены. Перезапускаем B2 и ждём интернет через SIM ${operation.sim_slot}…`:`Настройки записаны, но интернет через SIM ${operation.sim_slot} не подтверждён. Повторного перезапуска не будет.`;
|
||||||
|
}
|
||||||
|
if(['configuration','sim-selection'].includes(operation.scope))return ({submitting:'Передача запроса на VPS…',queued:'Ожидание следующего шага обмена с трекером…',dispatched:operation.stage==='preflight'?'Чтение полной конфигурации трекера…':operation.stage==='write'?'Передача настроек трекеру…':'Повторное чтение и проверка записи…',observed:`Конфигурация прочитана с трекера: ${operation.record_count??'—'} параметров.`,verified:operation.unchanged?'Настройки B2 уже совпадают с сохранённым профилем.':'Настройки записаны в B2 и подтверждены повторным чтением.',rejected:'Запись отменена: конфигурация трекера изменилась либо затронут резервный канал связи. Прочитайте настройки повторно.',not_applied:'Трекер сохранил прежние настройки.',expired:'Срок операции истёк. Начните с повторного чтения.',uncertain:'Результат записи не подтверждён. Автоматического повтора не будет.',unconfirmed:operation.stage==='preflight'?'Выгрузка настроек не получена. Прочитайте устройство повторно.':'Завершение записи не подтверждено. Прочитайте настройки B2 повторно.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
|
||||||
|
if(operation.state==='observed')return `Сервер 1 прочитан с трекера: ${operation.server1?.host}:${operation.server1?.port}.`;
|
||||||
|
if(operation.state==='verified')return `Сервер 1 подтверждён трекером: ${operation.server1?.host}:${operation.server1?.port}. Проверено ${new Date((operation.verified_at??0)*1000).toLocaleString('ru-RU')}.`;
|
||||||
|
return ({submitting:'Отправка запроса на VPS…',queued:'Ожидание связи с трекером…',dispatched:operation.stage==='preflight'?'Чтение текущих настроек трекера…':operation.stage==='write'?'Запись адреса сервера…':'Проверка адреса сервера повторным чтением…',rejected:'Запись отменена: текущие настройки трекера отличаются от ожидаемых.',not_applied:'Трекер сохранил прежний адрес сервера.',expired:'Трекер не вышел на связь. Запись не началась.',uncertain:'Результат записи не подтверждён. Повторная запись автоматически не выполняется.',unconfirmed:'Ответ не получен. Результат записи не подтверждён.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
export interface FirmwareImage {
|
||||||
|
id:string;model_id:string;filename:string;bytes:number;sha256:string;added_at:number;
|
||||||
|
version:string|null;source_url:string|null;source:'manufacturer'|'user';installable:false;
|
||||||
|
}
|
||||||
|
export interface FirmwareCatalog {items:FirmwareImage[];update_available:false}
|
||||||
|
const root='/api/v1/fleet/equipment/firmware';
|
||||||
|
async function response(url:string,init:RequestInit={}){
|
||||||
|
const value=await fetch(url,{...init,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(30000)});
|
||||||
|
if(!value.ok){const error=await value.json().catch(()=>({}));throw new Error(typeof error.detail==='string'?error.detail:'Архив прошивок недоступен. Повторите действие.');}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export async function readFirmware(model:string):Promise<FirmwareCatalog>{
|
||||||
|
return (await response(`${root}/${encodeURIComponent(model)}`)).json();
|
||||||
|
}
|
||||||
|
export async function uploadFirmware(model:string,file:File):Promise<FirmwareImage>{
|
||||||
|
if(!/\.dfw$/i.test(file.name)||file.size===0||file.size>4*1024*1024)throw new Error('Выберите непустой файл .dfw размером до 4 МБ.');
|
||||||
|
return (await response(`${root}/${encodeURIComponent(model)}?filename=${encodeURIComponent(file.name)}`,{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:file})).json();
|
||||||
|
}
|
||||||
|
export async function downloadFirmware(image:FirmwareImage):Promise<void>{
|
||||||
|
const value=await response(`${root}/${encodeURIComponent(image.model_id)}/${image.id}/download`);
|
||||||
|
const data=await value.arrayBuffer();
|
||||||
|
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data)),b=>b.toString(16).padStart(2,'0')).join('');
|
||||||
|
if(digest!==image.sha256||data.byteLength!==image.bytes)throw new Error('Контрольная сумма файла не совпала. Скачивание отменено.');
|
||||||
|
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'}));
|
||||||
|
const anchor=document.createElement('a');anchor.href=url;anchor.download=image.filename;
|
||||||
|
document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||||
|
}
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
export interface ObservationLayout {
|
export interface ObservationLayout {
|
||||||
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
|
||||||
splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
|
catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
|
||||||
}
|
}
|
||||||
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
|
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
|
||||||
const record=(value:unknown):Record<string,unknown>=>value!==null&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{};
|
const record=(value:unknown):Record<string,unknown>=>value!==null&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{};
|
||||||
export function decodeObservationLayout(value:unknown):ObservationLayout {
|
export function decodeObservationLayout(value:unknown):ObservationLayout {
|
||||||
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
|
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
|
||||||
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
|
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
|
||||||
|
if(source.catalogVisible!==undefined)result.catalogVisible=ids(source.catalogVisible);
|
||||||
result.order=ids(source.order);result.hidden=ids(source.hidden);
|
result.order=ids(source.order);result.hidden=ids(source.hidden);
|
||||||
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
|
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
|
||||||
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
|
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {useEffect,useState} from 'react';
|
||||||
|
import {equipmentRequest} from './equipment';
|
||||||
|
import {commandPending,type CommandEntry} from './commandRuntime';
|
||||||
|
export interface CommandAttempt {id:string;number:number;phase:string;state:string;observed_at:number;dispatched_at?:number;received_at?:number;device_accepted_at?:number;device_code?:number;roundtrip_seconds?:number}
|
||||||
|
interface Page {items:CommandAttempt[];next_before:number|null}
|
||||||
|
export function useCommandAttempts(identifier:string,entry:CommandEntry){
|
||||||
|
const [page,setPage]=useState<Page>({items:[],next_before:null}),[error,setError]=useState(''),[working,setWorking]=useState(false),[retry,setRetry]=useState(0);
|
||||||
|
const path=`/instances/${identifier}/commands/${entry.id}/attempts`;
|
||||||
|
useEffect(()=>{
|
||||||
|
if(!entry.durable)return;
|
||||||
|
let active=true;let timer:ReturnType<typeof setTimeout>;
|
||||||
|
async function read(){try{const value=await equipmentRequest<Page>(path);if(active){setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:old.items.length>20?old.next_before:value.next_before}));setError('');}}catch(e){if(active)setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{if(active&&commandPending(entry.state))timer=setTimeout(()=>void read(),3000);}}
|
||||||
|
void read();return()=>{active=false;clearTimeout(timer);};
|
||||||
|
},[path,entry.durable,entry.state,retry]);
|
||||||
|
async function more(){if(page.next_before===null||working)return;setWorking(true);try{const value=await equipmentRequest<Page>(`${path}?before=${page.next_before}`);setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:value.next_before}));setError('');}catch(e){setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{setWorking(false);}}
|
||||||
|
return {...page,error,working,more,refresh:()=>setRetry(n=>n+1)};
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||||
|
import {equipmentRequest} from './equipment';
|
||||||
|
import {commandTracked,mergeCommands,type CommandEntry,type CommandRuntime} from './commandRuntime';
|
||||||
|
|
||||||
|
type Intent={request_id:string;preset_id:string};
|
||||||
|
export function useCommandRuntime(identifier:string){
|
||||||
|
const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`;
|
||||||
|
const [data,setData]=useState<CommandRuntime|null>(null),[items,setItems]=useState<CommandEntry[]>([]),[before,setBefore]=useState<number|null>(null),[error,setError]=useState(''),[activity,setActivity]=useState('');
|
||||||
|
const alive=useRef(true),sending=useRef(false),first=useRef(true);
|
||||||
|
const tracked=useRef<string[]>([]);
|
||||||
|
const [intent,setIntent]=useState<Intent|null>(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&typeof v.preset_id==='string'?v:null;}catch{return null;}});
|
||||||
|
const accept=useCallback((value:CommandRuntime)=>{if(!alive.current)return;tracked.current=value.tracked_items.filter(commandTracked).map(item=>item.id).slice(0,32);setData(value);setItems(old=>mergeCommands(old,[...value.items,...value.tracked_items]));if(first.current){first.current=false;setBefore(value.next_before);}setError('');},[]);
|
||||||
|
const refresh=useCallback(async()=>{const query=new URLSearchParams();for(const id of tracked.current)query.append('tracked',id);accept(await equipmentRequest<CommandRuntime>(`${path}?${query}`));},[path,accept]);
|
||||||
|
useEffect(()=>{alive.current=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{await refresh();}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Журнал временно недоступен.');}finally{if(alive.current)timer=setTimeout(()=>void poll(),2000);}}void poll();return()=>{alive.current=false;clearTimeout(timer);};},[refresh]);
|
||||||
|
useEffect(()=>{if(intent&&items.some(item=>item.id===intent.request_id)){localStorage.removeItem(key);setIntent(null);}},[items,intent,key]);
|
||||||
|
async function send(preset:string){
|
||||||
|
if(sending.current)return;sending.current=true;setActivity('send');setError('');
|
||||||
|
const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),preset_id:preset};
|
||||||
|
try{
|
||||||
|
// Persist the request ID before HTTP. A lost reply/reopened window reuses it.
|
||||||
|
localStorage.setItem(key,JSON.stringify(request));setIntent(request);
|
||||||
|
const response=await fetch(`/api/v1/fleet/equipment${path}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request),signal:AbortSignal.timeout(15000)});
|
||||||
|
if(!response.ok){const value=await response.json().catch(()=>({}));if(response.status>=400&&response.status<500){localStorage.removeItem(key);if(alive.current)setIntent(null);}throw new Error(value.detail??'Ответ на отправку не получен. Уточните её с тем же ID.');}
|
||||||
|
localStorage.removeItem(key);if(alive.current)setIntent(null);await refresh();
|
||||||
|
}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Ответ не получен. Уточните отправку с тем же ID.');}
|
||||||
|
finally{sending.current=false;if(alive.current)setActivity('');}
|
||||||
|
}
|
||||||
|
async function cancel(id:string){setActivity(id);try{await equipmentRequest(`${path}/${id}/cancel`,'POST');await refresh();}catch(e){setError(e instanceof Error?e.message:'Отмена не подтверждена.');}finally{if(alive.current)setActivity('');}}
|
||||||
|
async function more(){if(before===null)return;setActivity('more');try{const value=await equipmentRequest<CommandRuntime>(`${path}?before=${before}`);if(alive.current){setItems(old=>mergeCommands(old,value.items));setBefore(value.next_before);}}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать историю.');}finally{if(alive.current)setActivity('');}}
|
||||||
|
return {data,items,before,error,setError,working:!!activity,activity,intent,send,cancel,more,refresh};
|
||||||
|
}
|
||||||
@@ -57,5 +57,8 @@ export function useFleet() {
|
|||||||
events.onerror = unavailable;
|
events.onerror = unavailable;
|
||||||
return () => { active = false; events.close(); if (fallback) clearInterval(fallback); };
|
return () => { active = false; events.close(); if (fallback) clearInterval(fallback); };
|
||||||
}, []);
|
}, []);
|
||||||
return { items, error, refresh };
|
const acceptVehicle = useCallback((vehicle: Vehicle) => {
|
||||||
|
setItems(current => current?.map(item => item.id === vehicle.id ? vehicle : item) ?? null);
|
||||||
|
}, []);
|
||||||
|
return { items, error, refresh, acceptVehicle };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import {useEffect,useState} from 'react';
|
||||||
|
|
||||||
|
export interface VPSHost {id:string;name:string;endpoint:string;network_interface?:string|null;vehicle_ids:string[];revision:number;state:'pending'|'paired';last_sync_at:number|null;status:{version:string;tracker:{host:string;port:number};pending_packages:number;devices:number;capabilities:string[]}|null}
|
||||||
|
export interface TrackerPosition {instance_id:string;host_id:string;latitude:number;longitude:number;measured_at:number;received_at:number;source:'gnss'|'lbs'|'wifi';satellites:number|null;course:number;speed_kmh:number}
|
||||||
|
export interface TrackerOutputs {pins:Record<string,boolean>;host_id:string;measured_at:number;received_at:number}
|
||||||
|
export interface CellularStamp {measured_at:number;received_at:number}
|
||||||
|
export interface CellularStatus extends CellularStamp {gsm_state:number;active_sim:1|2;sim_states:Record<string,number>}
|
||||||
|
export interface CellularNetwork extends CellularStamp {mcc:number|null;mnc:number;signal:number|null}
|
||||||
|
export interface TrackerCellular {host_id:string;status?:CellularStatus;networks:Record<string,CellularNetwork>}
|
||||||
|
export interface InternetAccess {state:'ready'|'waiting_identity'|'unknown_card'|'unsupported_operator';source?:'verified_card'|'carrier_candidate';apn?:string;home_network?:string;card_ref?:string}
|
||||||
|
export interface TrackerTelemetry {instance_id:string;name:string;vehicle_id:string;position:TrackerPosition|null;last_packet_at:number|null;online:boolean;position_fresh:boolean;outputs?:TrackerOutputs|null;outputs_fresh?:boolean;cellular?:TrackerCellular|null;internet_access?:Record<string,InternetAccess>|null;sim_identity?:{slots:Record<string,{binding_current?:boolean;known_card?:{home_network:string;card_ref:string}|null}>}|null}
|
||||||
|
export async function vpsRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
|
||||||
|
const response=await fetch(`/api/v1/fleet/vps-hosts${path}`,{method,cache:'no-store',credentials:'same-origin',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(45000)});
|
||||||
|
if(!response.ok){const data=await response.json().catch(()=>({}));throw new Error(typeof data.detail==='string'?data.detail:'VPS недоступен. Повторите действие.');}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
export function hostOnline(host:VPSHost){return !!host.last_sync_at&&Date.now()/1000-host.last_sync_at<30;}
|
||||||
|
export function telemetryLabel(item:TrackerTelemetry|undefined){return item?.online?'Передаёт данные на VPS':item?.last_packet_at?`Последний пакет: ${new Date(item.last_packet_at*1000).toLocaleString('ru-RU')}`:'Ожидание первого пакета на VPS';}
|
||||||
|
export function useTrackerTelemetry(vehicleID:string){
|
||||||
|
const [items,setItems]=useState<TrackerTelemetry[]>([]),[unavailable,setUnavailable]=useState(false);
|
||||||
|
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;setItems([]);
|
||||||
|
async function poll(){try{const value=await vpsRequest<{items:TrackerTelemetry[]}>(`/telemetry?vehicle_id=${encodeURIComponent(vehicleID)}`);if(active){setItems(value.items);setUnavailable(false);}}catch{if(active)setUnavailable(true);}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}
|
||||||
|
void poll();return()=>{active=false;clearTimeout(timer);};
|
||||||
|
},[vehicleID]);
|
||||||
|
return {items,unavailable};
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {useEffect,useRef} from 'react';
|
||||||
|
|
||||||
|
/** Recover the existing renderer only after its own gateway is reachable again. */
|
||||||
|
export function useMapRecovery(unavailable:boolean,retry:()=>void){
|
||||||
|
const callback=useRef(retry);callback.current=retry;
|
||||||
|
useEffect(()=>{
|
||||||
|
if(!unavailable)return;
|
||||||
|
let active=true;let timer:ReturnType<typeof setTimeout>;
|
||||||
|
const abort=new AbortController();
|
||||||
|
async function check(){
|
||||||
|
try{
|
||||||
|
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
|
||||||
|
const value=response.ok?await response.json():null;
|
||||||
|
if(active&&value?.ok===true){callback.current();return;}
|
||||||
|
}catch{/* Retain the unavailable state; no public-provider fallback. */}
|
||||||
|
if(active)timer=setTimeout(()=>void check(),30000);
|
||||||
|
}
|
||||||
|
timer=setTimeout(()=>void check(),30000);
|
||||||
|
return()=>{active=false;abort.abort();clearTimeout(timer);};
|
||||||
|
},[unavailable]);
|
||||||
|
}
|
||||||
@@ -37,5 +37,5 @@ export function useSessionOverviewMode(enabled: boolean) {
|
|||||||
window.addEventListener("keydown", close, true);
|
window.addEventListener("keydown", close, true);
|
||||||
return () => window.removeEventListener("keydown", close, true);
|
return () => window.removeEventListener("keydown", close, true);
|
||||||
}, [open]);
|
}, [open]);
|
||||||
return { open: enabled && open, toggle: useCallback(() => setOpen(v => !v), []) };
|
return { open: enabled && open, close: useCallback(() => setOpen(false), []), toggle: useCallback(() => setOpen(v => !v), []) };
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,399 @@
|
|||||||
|
|
||||||
|
export type PostFxSettings = {
|
||||||
|
lighting: {
|
||||||
|
ambientIntensity: number
|
||||||
|
exposure: number
|
||||||
|
skyBoxIntensity: number
|
||||||
|
}
|
||||||
|
envAtlas: {
|
||||||
|
enabled: boolean
|
||||||
|
background: boolean
|
||||||
|
reflection: boolean
|
||||||
|
intensity: number
|
||||||
|
reflectionIntensity: number
|
||||||
|
brightness: number
|
||||||
|
contrast: number
|
||||||
|
saturation: number
|
||||||
|
toneMapping: number
|
||||||
|
mip: number
|
||||||
|
rotation: number
|
||||||
|
}
|
||||||
|
skybox: {
|
||||||
|
enabled: boolean
|
||||||
|
background: boolean
|
||||||
|
reflection: boolean
|
||||||
|
intensity: number
|
||||||
|
reflectionIntensity: number
|
||||||
|
mip: number
|
||||||
|
rotation: number
|
||||||
|
colorA: string
|
||||||
|
colorB: string
|
||||||
|
}
|
||||||
|
rendering: {
|
||||||
|
backgroundColor: string
|
||||||
|
wireframe: boolean
|
||||||
|
renderFormat: number
|
||||||
|
renderFormatFallback0: number
|
||||||
|
renderFormatFallback1: number
|
||||||
|
stencil: boolean
|
||||||
|
renderTargetScale: number
|
||||||
|
samples: number
|
||||||
|
sharpness: number
|
||||||
|
toneMapping: number
|
||||||
|
sceneColorMap: boolean
|
||||||
|
sceneDepthMap: boolean
|
||||||
|
fog: 'none' | 'linear' | 'exp' | 'exp2'
|
||||||
|
fogColor: string
|
||||||
|
fogRange: [number, number]
|
||||||
|
fogDensity: number
|
||||||
|
fogStart: number
|
||||||
|
fogEnd: number
|
||||||
|
}
|
||||||
|
grid: {
|
||||||
|
step: number
|
||||||
|
diameter: number
|
||||||
|
enabled: boolean
|
||||||
|
colorX: string
|
||||||
|
colorZ: string
|
||||||
|
colorMain: string
|
||||||
|
alphaX: number
|
||||||
|
alphaZ: number
|
||||||
|
alphaMain: number
|
||||||
|
dotsEnabled: boolean
|
||||||
|
dotsColor: string
|
||||||
|
dotsAlpha: number
|
||||||
|
dotsDiameter: number
|
||||||
|
crossEnabled: boolean
|
||||||
|
crossColor: string
|
||||||
|
crossAlpha: number
|
||||||
|
crossLength: number
|
||||||
|
crossWidth: number
|
||||||
|
fadeStart: number
|
||||||
|
fadeEnd: number
|
||||||
|
}
|
||||||
|
ssao: {
|
||||||
|
type: 'none' | 'lighting' | 'combine'
|
||||||
|
blurEnabled: boolean
|
||||||
|
intensity: number
|
||||||
|
radius: number
|
||||||
|
samples: number
|
||||||
|
power: number
|
||||||
|
minAngle: number
|
||||||
|
scale: number
|
||||||
|
}
|
||||||
|
bloom: {
|
||||||
|
enabled: boolean
|
||||||
|
intensity: number
|
||||||
|
lastMipLevel: number
|
||||||
|
}
|
||||||
|
chromaticAberration: {
|
||||||
|
enabled: boolean
|
||||||
|
intensity: number
|
||||||
|
}
|
||||||
|
taa: {
|
||||||
|
enabled: boolean
|
||||||
|
jitter: number
|
||||||
|
}
|
||||||
|
grading: {
|
||||||
|
enabled: boolean
|
||||||
|
brightness: number
|
||||||
|
contrast: number
|
||||||
|
saturation: number
|
||||||
|
tint: string
|
||||||
|
}
|
||||||
|
lut: {
|
||||||
|
intensity: number
|
||||||
|
textureUrl?: string | null
|
||||||
|
}
|
||||||
|
vignette: {
|
||||||
|
enabled: boolean
|
||||||
|
intensity: number
|
||||||
|
inner: number
|
||||||
|
outer: number
|
||||||
|
curvature: number
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
directionalLight: {
|
||||||
|
enabled: boolean
|
||||||
|
color: string
|
||||||
|
intensity: number
|
||||||
|
azimuth: number
|
||||||
|
elevation: number
|
||||||
|
castShadows: boolean
|
||||||
|
shadowIntensity: number
|
||||||
|
shadowDistance: number
|
||||||
|
shadowResolution: number
|
||||||
|
shadowBias: number
|
||||||
|
normalOffsetBias: number
|
||||||
|
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
||||||
|
vsmBlurSize: number
|
||||||
|
}
|
||||||
|
shadowCatcher: {
|
||||||
|
enabled: boolean
|
||||||
|
size: number
|
||||||
|
yOffset: number
|
||||||
|
lightIntensity: number
|
||||||
|
lightColor: string
|
||||||
|
lightAzimuth: number
|
||||||
|
lightElevation: number
|
||||||
|
shadowIntensity: number
|
||||||
|
shadowDistance: number
|
||||||
|
shadowResolution: number
|
||||||
|
shadowBias: number
|
||||||
|
normalOffsetBias: number
|
||||||
|
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
|
||||||
|
vsmBlurSize: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_POSTFX: PostFxSettings = {
|
||||||
|
lighting: {
|
||||||
|
ambientIntensity: 0,
|
||||||
|
exposure: 1.21,
|
||||||
|
skyBoxIntensity: 0.86,
|
||||||
|
},
|
||||||
|
envAtlas: {
|
||||||
|
enabled: true,
|
||||||
|
background: false,
|
||||||
|
reflection: true,
|
||||||
|
intensity: 0.76,
|
||||||
|
reflectionIntensity: 0.6,
|
||||||
|
brightness: 1.65,
|
||||||
|
contrast: 1,
|
||||||
|
saturation: 1,
|
||||||
|
toneMapping: 0,
|
||||||
|
mip: 1,
|
||||||
|
rotation: 247,
|
||||||
|
},
|
||||||
|
skybox: {
|
||||||
|
enabled: false,
|
||||||
|
background: false,
|
||||||
|
reflection: true,
|
||||||
|
intensity: 0.62,
|
||||||
|
reflectionIntensity: 1,
|
||||||
|
mip: 0,
|
||||||
|
rotation: 0,
|
||||||
|
colorA: '#c5bfbf',
|
||||||
|
colorB: '#c7bcbc',
|
||||||
|
},
|
||||||
|
rendering: {
|
||||||
|
backgroundColor: '#111113',
|
||||||
|
wireframe: false,
|
||||||
|
renderFormat: 18,
|
||||||
|
renderFormatFallback0: 12,
|
||||||
|
renderFormatFallback1: 14,
|
||||||
|
stencil: false,
|
||||||
|
renderTargetScale: 1,
|
||||||
|
samples: 4,
|
||||||
|
sharpness: 0,
|
||||||
|
toneMapping: 4,
|
||||||
|
sceneColorMap: false,
|
||||||
|
sceneDepthMap: false,
|
||||||
|
fog: 'exp',
|
||||||
|
fogColor: '#dcc2ff',
|
||||||
|
fogRange: [0, 100],
|
||||||
|
fogDensity: 0.008,
|
||||||
|
fogStart: 0,
|
||||||
|
fogEnd: 100,
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
step: 1,
|
||||||
|
diameter: 1000,
|
||||||
|
enabled: true,
|
||||||
|
colorX: '#ffffff',
|
||||||
|
colorZ: '#ffffff',
|
||||||
|
colorMain: '#7a3cff',
|
||||||
|
alphaX: 0.18,
|
||||||
|
alphaZ: 0.18,
|
||||||
|
alphaMain: 0.6,
|
||||||
|
dotsEnabled: false,
|
||||||
|
dotsColor: '#ffffff',
|
||||||
|
dotsAlpha: 0.5,
|
||||||
|
dotsDiameter: 0.06,
|
||||||
|
crossEnabled: false,
|
||||||
|
crossColor: '#ffffff',
|
||||||
|
crossAlpha: 0.5,
|
||||||
|
crossLength: 0.5,
|
||||||
|
crossWidth: 0.06,
|
||||||
|
fadeStart: 0,
|
||||||
|
fadeEnd: 0,
|
||||||
|
},
|
||||||
|
ssao: {
|
||||||
|
type: 'none',
|
||||||
|
blurEnabled: true,
|
||||||
|
intensity: 0.5,
|
||||||
|
radius: 30,
|
||||||
|
samples: 12,
|
||||||
|
power: 6,
|
||||||
|
minAngle: 10,
|
||||||
|
scale: 1,
|
||||||
|
},
|
||||||
|
bloom: {
|
||||||
|
enabled: true,
|
||||||
|
intensity: 0.03,
|
||||||
|
lastMipLevel: 4,
|
||||||
|
},
|
||||||
|
chromaticAberration: {
|
||||||
|
enabled: true,
|
||||||
|
intensity: 30,
|
||||||
|
},
|
||||||
|
taa: {
|
||||||
|
enabled: false,
|
||||||
|
jitter: 1,
|
||||||
|
},
|
||||||
|
grading: {
|
||||||
|
enabled: true,
|
||||||
|
brightness: 0.837,
|
||||||
|
contrast: 1.1,
|
||||||
|
saturation: 1.126,
|
||||||
|
tint: '#ffffff',
|
||||||
|
},
|
||||||
|
lut: {
|
||||||
|
intensity: 1,
|
||||||
|
textureUrl: null,
|
||||||
|
},
|
||||||
|
vignette: {
|
||||||
|
enabled: true,
|
||||||
|
intensity: 1,
|
||||||
|
inner: 0.25,
|
||||||
|
outer: 1.52,
|
||||||
|
curvature: 0.78,
|
||||||
|
color: '#000000',
|
||||||
|
},
|
||||||
|
directionalLight: {
|
||||||
|
enabled: true,
|
||||||
|
color: '#ffffff',
|
||||||
|
intensity: 0.4,
|
||||||
|
azimuth: 0,
|
||||||
|
elevation: 0,
|
||||||
|
castShadows: false,
|
||||||
|
shadowIntensity: 0.5,
|
||||||
|
shadowDistance: 16,
|
||||||
|
shadowResolution: 1024,
|
||||||
|
shadowBias: 0,
|
||||||
|
normalOffsetBias: 0,
|
||||||
|
shadowType: 'vsm16',
|
||||||
|
vsmBlurSize: 8,
|
||||||
|
},
|
||||||
|
shadowCatcher: {
|
||||||
|
enabled: true,
|
||||||
|
size: 9,
|
||||||
|
yOffset: 0.001,
|
||||||
|
lightIntensity: 0.3,
|
||||||
|
lightColor: '#ffffff',
|
||||||
|
lightAzimuth: 20,
|
||||||
|
lightElevation: 60,
|
||||||
|
shadowIntensity: 0.29,
|
||||||
|
shadowDistance: 16,
|
||||||
|
shadowResolution: 2048,
|
||||||
|
shadowBias: 0,
|
||||||
|
normalOffsetBias: 0,
|
||||||
|
shadowType: 'vsm16',
|
||||||
|
vsmBlurSize: 8,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObject(value: any): value is Record<string, any> {
|
||||||
|
return !!value && typeof value === 'object' && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
|
||||||
|
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
|
||||||
|
|
||||||
|
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
|
||||||
|
const merge = (target: any, source: any) => {
|
||||||
|
if (!isObject(source)) return
|
||||||
|
for (const [key, value] of Object.entries(source)) {
|
||||||
|
if (isObject(value)) {
|
||||||
|
if (!isObject(target[key])) target[key] = {}
|
||||||
|
merge(target[key], value)
|
||||||
|
} else {
|
||||||
|
target[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merge(out, raw)
|
||||||
|
|
||||||
|
const legacy: any = raw as any
|
||||||
|
if (legacy?.hdrLight) {
|
||||||
|
const src = legacy.hdrLight
|
||||||
|
const env = legacy?.envAtlas ?? {}
|
||||||
|
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
|
||||||
|
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
|
||||||
|
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
|
||||||
|
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
|
||||||
|
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
|
||||||
|
}
|
||||||
|
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
|
||||||
|
if (typeof legacy.hdrReflection.enabled === 'boolean') {
|
||||||
|
out.envAtlas.reflection = legacy.hdrReflection.enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
|
||||||
|
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
|
||||||
|
}
|
||||||
|
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
|
||||||
|
out.envAtlas.brightness = 1
|
||||||
|
}
|
||||||
|
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
|
||||||
|
out.envAtlas.contrast = 1
|
||||||
|
}
|
||||||
|
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
|
||||||
|
out.envAtlas.saturation = 1
|
||||||
|
}
|
||||||
|
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
|
||||||
|
out.envAtlas.toneMapping = 0
|
||||||
|
}
|
||||||
|
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
|
||||||
|
out.skybox.reflectionIntensity = out.skybox.intensity
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.enabled !== 'boolean') {
|
||||||
|
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.colorX !== 'string') {
|
||||||
|
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.colorZ !== 'string') {
|
||||||
|
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.colorMain !== 'string') {
|
||||||
|
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.alphaX !== 'number') {
|
||||||
|
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.alphaZ !== 'number') {
|
||||||
|
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.alphaMain !== 'number') {
|
||||||
|
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
|
||||||
|
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.dotsColor !== 'string') {
|
||||||
|
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
|
||||||
|
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
|
||||||
|
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
|
||||||
|
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.crossColor !== 'string') {
|
||||||
|
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
|
||||||
|
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.crossLength !== 'number') {
|
||||||
|
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
|
||||||
|
}
|
||||||
|
if (out.grid && typeof out.grid.crossWidth !== 'number') {
|
||||||
|
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
|
||||||
|
}
|
||||||
|
return out as PostFxSettings
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import {mergePostFxDefaults,type PostFxSettings} from './postFx';
|
||||||
|
import donorFields from './environmentFields.json';
|
||||||
|
export type SceneField={key:string;type:string;label:string;group:string;default?:unknown;min?:number;max?:number;step?:number;options?:{label:string;value:string}[];disabledIf?:string};
|
||||||
|
export const environmentFields:SceneField[]=[...donorFields,
|
||||||
|
{key:'postFx.lut.textureUrl',type:'texture',label:'Таблица LUT',group:'PostProcess/LUT'},
|
||||||
|
{key:'postFx.lighting.ambientIntensity',type:'sliderNumber',label:'Заполняющий свет',group:'PostProcess/Lighting',min:0,max:1,step:.01},
|
||||||
|
{key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01},
|
||||||
|
{key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1},
|
||||||
|
];
|
||||||
|
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
|
||||||
|
export type TextureSlot=typeof textureSlots[number];
|
||||||
|
export type MaterialSpec={name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
|
||||||
|
export type SceneDocument={schema:'missioncore.rover-scene/v1';model:'dcd006-v020-materials-v2';environmentVersion:2;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>};
|
||||||
|
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
|
||||||
|
export function defaultScene():SceneDocument{
|
||||||
|
const postFx=mergePostFxDefaults();
|
||||||
|
return {schema:'missioncore.rover-scene/v1',model:'dcd006-v020-materials-v2',environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{
|
||||||
|
'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53),
|
||||||
|
'rover/rubber':material('Резина гусениц и катков','#202328',0,.72),
|
||||||
|
'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17),
|
||||||
|
'rover/box':material('Бортовой ящик','#34373a',.08,.4),
|
||||||
|
'rover/molle':material('MOLLE панель','#52575b',.3,.44),
|
||||||
|
'rover/motor':material('Алюминий моторов','#95999c',.68,.38),
|
||||||
|
'rover/hardware':material('Чёрный крепёж','#24272b',.45,.38),
|
||||||
|
'rover/polymer':material('Пластик и кожухи','#24292d',0,.44),
|
||||||
|
'rover/drive':material('Ведущие звёзды','#81652f',0,.46),
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
export function createMaterial(doc:SceneDocument,id:string):SceneDocument{
|
||||||
|
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=128)return doc;
|
||||||
|
const used=new Set(Object.values(doc.materials).map(m=>m.name));let n=1;while(used.has(`Материал ${n}`))n++;
|
||||||
|
return {...doc,materials:{...doc.materials,[id]:material(`Материал ${n}`,'#808080',0,.5)}};
|
||||||
|
}
|
||||||
|
export function assignMaterial(doc:SceneDocument,group:string,id:string):SceneDocument{
|
||||||
|
if(!Object.hasOwn(defaultScene().materials,group)||!Object.hasOwn(doc.materials,id))return doc;
|
||||||
|
return {...doc,assignments:{...doc.assignments,[group]:id}};
|
||||||
|
}
|
||||||
|
export function fieldValue(doc:SceneDocument,key:string):unknown{return key.split('.').reduce<unknown>((v,k)=>v&&typeof v==='object'?(v as Record<string,unknown>)[k]:undefined,doc);}
|
||||||
|
export function fieldDisabled(doc:SceneDocument,f:SceneField):boolean{
|
||||||
|
const rule=f.disabledIf;if(!rule)return false;
|
||||||
|
if(rule.startsWith('!'))return !fieldValue(doc,rule.slice(1));
|
||||||
|
const atlas=doc.postFx.envAtlas.enabled,sky=doc.postFx.skybox.enabled;
|
||||||
|
return ({ssaoDisabled:doc.postFx.ssao.type==='none',fogDisabled:doc.postFx.rendering.fog==='none',envAtlasBlocked:sky,skyboxBlocked:atlas,envAtlasFieldsDisabled:sky||!atlas,skyboxFieldsDisabled:atlas||!sky,gridDotsDisabled:!doc.postFx.grid.dotsEnabled,gridCrossDisabled:!doc.postFx.grid.crossEnabled} as Record<string,boolean>)[rule]??false;
|
||||||
|
}
|
||||||
|
export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDocument{
|
||||||
|
const f=environmentFields.find(x=>x.key===key);if(!f||f.type==='action')return doc;
|
||||||
|
if(f.type==='texture'&&value!==null&&(typeof value!=='string'||value.length>1_000_000||!/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(value)))return doc;
|
||||||
|
const old=fieldValue(doc,key);
|
||||||
|
if(typeof old==='number'){
|
||||||
|
value=Number(value);if(!Number.isFinite(value))return doc;
|
||||||
|
if(f.min!==undefined)value=Math.max(f.min,value as number);if(f.max!==undefined)value=Math.min(f.max,value as number);
|
||||||
|
}else if(typeof old==='boolean'){if(typeof value!=='boolean')return doc;}
|
||||||
|
else if(f.type==='color'){if(typeof value!=='string'||!/^#[0-9a-f]{6}$/i.test(value))return doc;}
|
||||||
|
if(f.options&&!f.options.some(o=>o.value===String(value)))return doc;
|
||||||
|
if(f.type==='doubleSlider'){
|
||||||
|
if(!Array.isArray(value)||value.length!==2||!value.every(Number.isFinite))return doc;
|
||||||
|
value=[Math.max(0,Math.min(100,value[0])),Math.max(0,Math.min(100,value[1]))].sort((a,b)=>a-b);
|
||||||
|
}
|
||||||
|
const result={...doc,postFx:structuredClone(doc.postFx)};const parts=key.split('.');const tail=parts.pop()!;
|
||||||
|
const target=parts.reduce((v,k)=>v[k],result as any);target[tail]=value;
|
||||||
|
if(key==='postFx.rendering.fogRange'){[result.postFx.rendering.fogStart,result.postFx.rendering.fogEnd]=value as [number,number];}
|
||||||
|
if(key==='postFx.envAtlas.enabled'&&value)result.postFx.skybox.enabled=false;
|
||||||
|
if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
|
||||||
|
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
|
||||||
|
export function parseScene(raw:unknown):SceneDocument{
|
||||||
|
const r=raw as SceneDocument;if(!r||r.schema!=='missioncore.rover-scene/v1'||r.model!=='dcd006-v020-materials-v2')throw new Error('Файл сцены не подходит к этой модели.');
|
||||||
|
let doc=defaultScene();
|
||||||
|
for(const f of environmentFields){const v=fieldValue(r,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
|
||||||
|
if(Object.keys(r.materials??{}).length>128)throw new Error('В сцене может быть не больше 128 материалов.');
|
||||||
|
for(const id of Object.keys(r.materials??{}))if(id.startsWith('custom/'))doc=createMaterial(doc,id);
|
||||||
|
for(const [id,base] of Object.entries(doc.materials)){
|
||||||
|
const m=r.materials?.[id];if(!m)continue;
|
||||||
|
if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name;
|
||||||
|
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key];
|
||||||
|
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));}
|
||||||
|
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
|
||||||
|
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
|
||||||
|
}
|
||||||
|
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
|
||||||
|
if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.');
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
|
||||||
|
|
||||||
|
// Fingerprint of the first editor's withdrawn neutral preset. Match the entire
|
||||||
|
// environment: independently edited environments must never be reset on load.
|
||||||
|
function withdrawnEnvironment(){
|
||||||
|
const fx=defaultScene().postFx;
|
||||||
|
Object.assign(fx.lighting,{exposure:1.1,skyBoxIntensity:1,ambientIntensity:.22});
|
||||||
|
Object.assign(fx.envAtlas,{reflectionIntensity:1,brightness:1.2});
|
||||||
|
Object.assign(fx.rendering,{backgroundColor:'#202227',fog:'none',toneMapping:4});
|
||||||
|
Object.assign(fx.grid,{colorMain:'#747982',colorX:'#93969c',colorZ:'#93969c',alphaMain:.25,alphaX:.35,alphaZ:.35,fadeStart:2,fadeEnd:5,step:.5,diameter:12});
|
||||||
|
fx.chromaticAberration.enabled=false;fx.vignette.enabled=false;fx.grading.enabled=false;fx.bloom.enabled=false;
|
||||||
|
Object.assign(fx.directionalLight,{intensity:1.8,azimuth:135,elevation:45});
|
||||||
|
Object.assign(fx.shadowCatcher,{size:4,lightIntensity:.5,shadowIntensity:.25});
|
||||||
|
return fx;
|
||||||
|
}
|
||||||
|
export function loadStoredScene(raw:unknown):{document:SceneDocument;updated:boolean;restoredEnvironment:boolean}{
|
||||||
|
const doc=parseScene(raw);
|
||||||
|
const updated=(raw as Partial<SceneDocument>).environmentVersion!==2;
|
||||||
|
const restoredEnvironment=updated&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment());
|
||||||
|
return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment};
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import type {SceneDocument} from './sceneDocument';
|
||||||
|
import {loadStoredScene} from './sceneMigration';
|
||||||
|
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
|
||||||
|
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
|
||||||
|
export async function readScene(vehicle:string):Promise<SceneDocument|null>{
|
||||||
|
const db=await database();try{
|
||||||
|
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);});
|
||||||
|
if(!raw)return null;
|
||||||
|
const result=loadStoredScene(raw);
|
||||||
|
if(result.updated)await new Promise<void>((resolve,reject)=>{
|
||||||
|
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
|
||||||
|
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
|
||||||
|
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
|
||||||
|
});
|
||||||
|
return result.document;
|
||||||
|
}finally{db.close();}
|
||||||
|
}
|
||||||
|
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}}
|
||||||
|
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
|
||||||
|
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
|
||||||
|
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
|
||||||
|
return new Promise((resolve,reject)=>{const r=new FileReader();r.onerror=()=>reject(r.error);r.onload=()=>resolve({name:file.name,data:String(r.result)});r.readAsDataURL(file);});
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||||
|
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
|
||||||
|
import {readScene,saveScene} from './sceneStorage';
|
||||||
|
let writes=Promise.resolve();
|
||||||
|
const enqueue=(vehicle:string,doc:SceneDocument)=>{const next=writes.catch(()=>{}).then(()=>saveScene(vehicle,doc));writes=next;return next;};
|
||||||
|
export function useSceneDocument(vehicle:string){
|
||||||
|
const [document,setDocument]=useState(defaultScene),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
|
||||||
|
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
|
||||||
|
const latest=useRef({document,revision,vehicle});latest.current={document,revision,vehicle};
|
||||||
|
const savedRevision=useRef(0);
|
||||||
|
useEffect(()=>{let cancelled=false;readScene(vehicle).then(value=>{if(!cancelled){setDocument(value??defaultScene());setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle]);
|
||||||
|
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{setDocument(d=>fn(d));setRevision(v=>v+1);setSaveState('saving');},[]);
|
||||||
|
useEffect(()=>{
|
||||||
|
if(!ready||revision===0)return;
|
||||||
|
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
|
||||||
|
return()=>{cancelled=true;clearTimeout(timer);};
|
||||||
|
},[ready,revision,vehicle,document]);
|
||||||
|
useEffect(()=>()=>{const v=latest.current;if(v.revision>savedRevision.current)void enqueue(v.vehicle,v.document).catch(()=>{});},[]);
|
||||||
|
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()));update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
|
||||||
|
const exportDocument=()=>{const blob=new Blob([JSON.stringify(document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download='rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||||
|
return {document,ready,saveState,error,setError,update,importDocument,exportDocument};
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import {fetchComputeContours,type ComputeContour} from './computeContours';
|
||||||
|
import {fetchWorkerTelemetry,type WorkerTelemetry} from './workerTelemetry';
|
||||||
|
import type {Vehicle} from '../fleet/useFleet';
|
||||||
|
import {workerConnectionStatus} from './workerConnectionStatus';
|
||||||
|
|
||||||
|
export interface CoreHealth {
|
||||||
|
ok:boolean; service:string; version:string;
|
||||||
|
plugin_runtimes:{ready:number;total:number};
|
||||||
|
components?:{recording_cache?:{status?:string}};
|
||||||
|
}
|
||||||
|
export interface ContourSnapshot {
|
||||||
|
core:CoreHealth|null; latency:number|null;
|
||||||
|
workers:{contour:ComputeContour;telemetry:WorkerTelemetry|null}[]|null;
|
||||||
|
vehicles:Vehicle[]|null; errors:string[]; observedAt:number;
|
||||||
|
}
|
||||||
|
async function json(url:string,signal:AbortSignal):Promise<unknown>{
|
||||||
|
const response=await fetch(url,{signal,cache:'no-store',headers:{Accept:'application/json'}});
|
||||||
|
if(!response.ok)throw new Error(`HTTP ${response.status}`);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
export async function readContourSnapshot(signal:AbortSignal):Promise<ContourSnapshot>{
|
||||||
|
const bounded=AbortSignal.any([signal,AbortSignal.timeout(8000)]);
|
||||||
|
const errors:string[]=[];
|
||||||
|
const [coreResult,workersResult,fleetResult]=await Promise.allSettled([
|
||||||
|
(async()=>{
|
||||||
|
const start=performance.now();
|
||||||
|
const data=await json('/api/health',bounded) as CoreHealth;
|
||||||
|
if(!data||typeof data.ok!=='boolean'||data.service!=='mission-core-control-plane'||typeof data.version!=='string'||!Number.isFinite(data.plugin_runtimes?.ready)||!Number.isFinite(data.plugin_runtimes?.total))throw new Error('Invalid health');
|
||||||
|
return {data,latency:performance.now()-start};
|
||||||
|
})(),
|
||||||
|
(async()=>{
|
||||||
|
const contours=await fetchComputeContours(bounded);
|
||||||
|
return Promise.all(contours.map(async contour=>{
|
||||||
|
try{return {contour,telemetry:await fetchWorkerTelemetry(contour.contour_id,bounded)};}
|
||||||
|
catch{errors.push(`Не удалось проверить вычислитель «${contour.display_name}».`);return {contour,telemetry:null};}
|
||||||
|
}));
|
||||||
|
})(),
|
||||||
|
(async()=>{
|
||||||
|
const data=await json('/api/v1/fleet',bounded) as {items:Vehicle[]};
|
||||||
|
if(!data||!Array.isArray(data.items)||data.items.some(item=>!item||typeof item.id!=='string'||typeof item.name!=='string'||!['online','offline'].includes(item.connectivity)))throw new Error('Invalid fleet');
|
||||||
|
return data.items;
|
||||||
|
})(),
|
||||||
|
]);
|
||||||
|
if(coreResult.status==='rejected')errors.push('Не удалось проверить Mission Core.');
|
||||||
|
if(workersResult.status==='rejected')errors.push('Не удалось получить список вычислителей.');
|
||||||
|
if(fleetResult.status==='rejected')errors.push('Не удалось получить бортовые компьютеры.');
|
||||||
|
return {
|
||||||
|
core:coreResult.status==='fulfilled'?coreResult.value.data:null,
|
||||||
|
latency:coreResult.status==='fulfilled'?coreResult.value.latency:null,
|
||||||
|
workers:workersResult.status==='fulfilled'?workersResult.value:null,
|
||||||
|
vehicles:fleetResult.status==='fulfilled'?fleetResult.value:null,
|
||||||
|
errors,observedAt:Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function workerAvailable(telemetry:WorkerTelemetry|null):boolean{
|
||||||
|
return Boolean(telemetry?.connection.reachable&&telemetry.connection.identity_matches&&telemetry.node);
|
||||||
|
}
|
||||||
|
export function boardAvailable(vehicle:Vehicle):boolean{
|
||||||
|
return vehicle.enrollment==='paired'&&vehicle.connectivity==='online';
|
||||||
|
}
|
||||||
|
export function contourSummary(snapshot:ContourSnapshot|null){
|
||||||
|
if(!snapshot)return {tone:'warning' as const,label:'Проверка состояния',online:null,total:null};
|
||||||
|
const total=snapshot.workers!==null&&snapshot.vehicles!==null?1+snapshot.workers.length+snapshot.vehicles.length:null;
|
||||||
|
const online=Number(snapshot.core!==null)+(snapshot.workers??[]).filter(item=>workerAvailable(item.telemetry)).length+(snapshot.vehicles??[]).filter(boardAvailable).length;
|
||||||
|
if(snapshot.errors.length)return {tone:'warning' as const,label:'Проверка неполная',online,total};
|
||||||
|
if(!snapshot.core)return {tone:'danger' as const,label:'Mission Core не в сети',online,total};
|
||||||
|
if(!snapshot.core.ok)return {tone:'warning' as const,label:'Mission Core работает с ограничениями',online,total};
|
||||||
|
if(snapshot.workers?.some(item=>workerConnectionStatus(item.telemetry).state==='unknown'))return {tone:'warning' as const,label:'Состояние части узлов не подтверждено',online,total};
|
||||||
|
return {tone:online===total?'success' as const:'warning' as const,label:online===total?'Все узлы в сети':'Часть узлов не в сети',online,total};
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import type {WorkerTelemetry} from './workerTelemetry';
|
||||||
|
|
||||||
|
// Receiver failure is not evidence that the remote host has shut down.
|
||||||
|
export function workerConnectionStatus(telemetry: WorkerTelemetry | null) {
|
||||||
|
const connection = telemetry?.connection;
|
||||||
|
if (!connection) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Состояние вычислителя пока не подтверждено.'} as const;
|
||||||
|
if (connection.reachable && !connection.identity_matches) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Ответивший узел не совпадает с выбранным вычислителем.'} as const;
|
||||||
|
if (connection.reachable && connection.identity_matches && telemetry.node) return {state:'online', tone:'success', label:'В сети', detail:null} as const;
|
||||||
|
if (['telemetry-receiver-unavailable','telemetry-agent-unavailable','invalid-telemetry-response'].includes(connection.error_code ?? '')) {
|
||||||
|
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Mission Core не получает данные через службу телеметрии. Состояние самого вычислителя не подтверждено.'} as const;
|
||||||
|
}
|
||||||
|
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Последние данные не подтверждают текущее состояние вычислителя.'} as const;
|
||||||
|
}
|
||||||
@@ -186,7 +186,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
|||||||
label: "Состояние контура",
|
label: "Состояние контура",
|
||||||
title: "Состояние контура",
|
title: "Состояние контура",
|
||||||
eyebrow: "ПАРК / СОСТОЯНИЕ",
|
eyebrow: "ПАРК / СОСТОЯНИЕ",
|
||||||
description: "Узлы, процессы, сеть и подключённые устройства по данным живого контура.",
|
description: "Связь с Mission Core, вычислителями и бортовыми компьютерами аппаратов.",
|
||||||
icon: "shield",
|
icon: "shield",
|
||||||
kind: "contour-health",
|
kind: "contour-health",
|
||||||
groups: [],
|
groups: [],
|
||||||
@@ -213,50 +213,6 @@ export const workspaces: WorkspaceDefinition[] = [
|
|||||||
kind: "device",
|
kind: "device",
|
||||||
groups: [],
|
groups: [],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: "payload",
|
|
||||||
root: "fleet",
|
|
||||||
label: "Сенсоры и каналы",
|
|
||||||
title: "Сенсоры и каналы",
|
|
||||||
eyebrow: "ПАРК / ПОЛЕЗНАЯ НАГРУЗКА",
|
|
||||||
description: "Полезная нагрузка аппарата и каналы данных, которые она публикует.",
|
|
||||||
icon: "grid",
|
|
||||||
kind: "catalog",
|
|
||||||
groups: [
|
|
||||||
{
|
|
||||||
title: "Пространственные сенсоры",
|
|
||||||
description: "Единый контракт для разных источников.",
|
|
||||||
capabilities: [
|
|
||||||
active("Облако точек", "Доказанный декодированный поток точек текущего устройства."),
|
|
||||||
active("Поза и траектория", "Доказанный поток позы и накопление пути."),
|
|
||||||
contract("Камеры", "Изображение, видео, глубина, внутренние и внешние параметры."),
|
|
||||||
contract("Навигация", "IMU, GNSS/RTK, одометрия и система координат."),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "configurations",
|
|
||||||
root: "fleet",
|
|
||||||
label: "Компоновки",
|
|
||||||
title: "Компоновки борта",
|
|
||||||
eyebrow: "ПАРК / КОМПОНОВКИ",
|
|
||||||
description: "Версионируемые сочетания сенсоров, вычислителей, транспорта и питания.",
|
|
||||||
icon: "settings",
|
|
||||||
kind: "catalog",
|
|
||||||
groups: [
|
|
||||||
{
|
|
||||||
title: "Шаблон компоновки",
|
|
||||||
description: "Повторяемая конфигурация для одинаковых аппаратов.",
|
|
||||||
capabilities: [
|
|
||||||
contract("Состав модулей", "Сенсоры, адаптеры, обработчики и зависимости."),
|
|
||||||
contract("Калибровки", "Системы координат, преобразования, внутренние и внешние параметры."),
|
|
||||||
contract("Профиль сети", "Локальная сеть, ячеистая сеть, LTE и серверный маршрут."),
|
|
||||||
later("Развёртывание на борт", "Пакет конфигурации и контролируемое обновление."),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: "spatial-scene",
|
id: "spatial-scene",
|
||||||
root: "polygon",
|
root: "polygon",
|
||||||
|
|||||||
@@ -2173,6 +2173,7 @@
|
|||||||
|
|
||||||
.contour-health-summary {
|
.contour-health-summary {
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2203,7 +2204,7 @@
|
|||||||
|
|
||||||
.contour-health-kpis {
|
.contour-health-kpis {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr));
|
||||||
gap: 0.45rem;
|
gap: 0.45rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2235,7 +2236,7 @@
|
|||||||
|
|
||||||
.contour-node-grid {
|
.contour-node-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||||
gap: 0.65rem;
|
gap: 0.65rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2251,6 +2252,7 @@
|
|||||||
|
|
||||||
.contour-node header {
|
.contour-node header {
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2262,7 +2264,7 @@
|
|||||||
|
|
||||||
.contour-node dl {
|
.contour-node dl {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
margin: 0;
|
margin: 0;
|
||||||
border-radius: 0.75rem;
|
border-radius: 0.75rem;
|
||||||
background: rgb(255 255 255 / 0.022);
|
background: rgb(255 255 255 / 0.022);
|
||||||
@@ -2277,11 +2279,10 @@
|
|||||||
|
|
||||||
.contour-node dd {
|
.contour-node dd {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
overflow: hidden;
|
overflow-wrap: anywhere;
|
||||||
color: var(--nodedc-text-secondary);
|
color: var(--nodedc-text-secondary);
|
||||||
font-size: 0.62rem;
|
font-size: var(--nodedc-font-size-sm);
|
||||||
text-overflow: ellipsis;
|
white-space: normal;
|
||||||
white-space: nowrap;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.contour-process-list {
|
.contour-process-list {
|
||||||
|
|||||||
@@ -1,41 +1,10 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import {useEffect,useState} from 'react';
|
||||||
import { Button, Icon, StatusBadge } from "@nodedc/ui-react";
|
import {createPortal} from 'react-dom';
|
||||||
|
import {workerConnectionStatus} from '../core/system/workerConnectionStatus';
|
||||||
import type { MissionRuntimeState } from "../core/runtime/contracts";
|
import {IconButton,Icon,StatusBadge} from '@nodedc/ui-react';
|
||||||
import {
|
import type {MissionRuntimeState} from '../core/runtime/contracts';
|
||||||
fetchPolygonWorkerStatus,
|
import {boardAvailable,contourSummary,readContourSnapshot,type ContourSnapshot} from '../core/system/contourHealth';
|
||||||
type PolygonWorkerStatus,
|
import {startSequentialPolling} from '../core/system/sequentialPolling';
|
||||||
} from "../core/polygon/liveWorker";
|
|
||||||
|
|
||||||
interface ControlPlaneHealth {
|
|
||||||
ok: boolean;
|
|
||||||
status: string;
|
|
||||||
service: string;
|
|
||||||
version: string;
|
|
||||||
plugin_runtimes: {
|
|
||||||
ready: number;
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PluginRuntimeHealth {
|
|
||||||
runtime_instance_id: string;
|
|
||||||
plugin_id: string;
|
|
||||||
plugin_version: string;
|
|
||||||
status: string;
|
|
||||||
observed_at: string;
|
|
||||||
detail_code: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ContourSnapshot {
|
|
||||||
controlPlane: ControlPlaneHealth | null;
|
|
||||||
pluginRuntimes: PluginRuntimeHealth[];
|
|
||||||
simulationWorker: PolygonWorkerStatus | null;
|
|
||||||
controlPlaneLatencyMs: number | null;
|
|
||||||
simulationGatewayLatencyMs: number | null;
|
|
||||||
observedAt: Date;
|
|
||||||
error: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function contourRuntimeAuthorityPresentation(
|
export function contourRuntimeAuthorityPresentation(
|
||||||
state: MissionRuntimeState | null,
|
state: MissionRuntimeState | null,
|
||||||
@@ -56,310 +25,64 @@ export function contourRuntimeAuthorityPresentation(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function validControlPlaneHealth(value: unknown): value is ControlPlaneHealth {
|
function observed(value:number|string|null|undefined){
|
||||||
if (!value || typeof value !== "object") return false;
|
if(value===null||value===undefined)return '—';
|
||||||
const item = value as Partial<ControlPlaneHealth>;
|
const date=new Date(value);
|
||||||
return typeof item.ok === "boolean"
|
return Number.isFinite(date.getTime())?date.toLocaleString('ru-RU'):'—';
|
||||||
&& typeof item.status === "string"
|
|
||||||
&& typeof item.service === "string"
|
|
||||||
&& typeof item.version === "string"
|
|
||||||
&& Boolean(item.plugin_runtimes)
|
|
||||||
&& typeof item.plugin_runtimes?.ready === "number"
|
|
||||||
&& typeof item.plugin_runtimes?.total === "number";
|
|
||||||
}
|
}
|
||||||
|
export function ContourHealthWorkspace({state,headerToolsHost}:{state:MissionRuntimeState|null;headerToolsHost?:HTMLElement|null}){
|
||||||
function validPluginRuntime(value: unknown): value is PluginRuntimeHealth {
|
|
||||||
if (!value || typeof value !== "object") return false;
|
|
||||||
const item = value as Partial<PluginRuntimeHealth>;
|
|
||||||
return typeof item.runtime_instance_id === "string"
|
|
||||||
&& typeof item.plugin_id === "string"
|
|
||||||
&& typeof item.plugin_version === "string"
|
|
||||||
&& typeof item.status === "string"
|
|
||||||
&& typeof item.observed_at === "string";
|
|
||||||
}
|
|
||||||
|
|
||||||
async function timedJson(
|
|
||||||
url: string,
|
|
||||||
signal: AbortSignal,
|
|
||||||
): Promise<{ payload: unknown; latencyMs: number }> {
|
|
||||||
const started = performance.now();
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: "GET",
|
|
||||||
headers: { Accept: "application/json" },
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
const latencyMs = performance.now() - started;
|
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
||||||
return { payload: await response.json(), latencyMs };
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatLatency(value: number | null): string {
|
|
||||||
if (value === null) return "—";
|
|
||||||
return `${Math.max(1, Math.round(value))} мс`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatObservedAt(value: Date | string | null): string {
|
|
||||||
if (!value) return "—";
|
|
||||||
const date = value instanceof Date ? value : new Date(value);
|
|
||||||
if (!Number.isFinite(date.getTime())) return "—";
|
|
||||||
return new Intl.DateTimeFormat("ru-RU", {
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
second: "2-digit",
|
|
||||||
}).format(date);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ContourHealthWorkspace({
|
|
||||||
state,
|
|
||||||
}: {
|
|
||||||
state: MissionRuntimeState | null;
|
|
||||||
}) {
|
|
||||||
const [snapshot,setSnapshot]=useState<ContourSnapshot|null>(null);
|
const [snapshot,setSnapshot]=useState<ContourSnapshot|null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading,setLoading]=useState(true),[generation,setGeneration]=useState(0);
|
||||||
const [generation, setGeneration] = useState(0);
|
|
||||||
|
|
||||||
const refresh = useCallback(() => setGeneration((value) => value + 1), []);
|
|
||||||
|
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
const controller=new AbortController();
|
const controller=new AbortController();
|
||||||
|
const stop=startSequentialPolling(async()=>{
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
void Promise.allSettled([
|
try{const next=await readContourSnapshot(controller.signal);if(!controller.signal.aborted)setSnapshot(next);}
|
||||||
timedJson("/api/health", controller.signal),
|
finally{if(!controller.signal.aborted)setLoading(false);}
|
||||||
timedJson("/api/v1/device-plugin-runtimes", controller.signal),
|
},5000);
|
||||||
(async () => {
|
return ()=>{stop();controller.abort();};
|
||||||
const started = performance.now();
|
|
||||||
const worker = await fetchPolygonWorkerStatus({ signal: controller.signal });
|
|
||||||
return { worker, latencyMs: performance.now() - started };
|
|
||||||
})(),
|
|
||||||
]).then(([healthResult, runtimesResult, workerResult]) => {
|
|
||||||
if (controller.signal.aborted) return;
|
|
||||||
const healthPayload = healthResult.status === "fulfilled"
|
|
||||||
? healthResult.value.payload
|
|
||||||
: null;
|
|
||||||
const runtimesPayload = runtimesResult.status === "fulfilled"
|
|
||||||
? runtimesResult.value.payload
|
|
||||||
: null;
|
|
||||||
const runtimeItems = runtimesPayload
|
|
||||||
&& typeof runtimesPayload === "object"
|
|
||||||
&& Array.isArray((runtimesPayload as { items?: unknown }).items)
|
|
||||||
? (runtimesPayload as { items: unknown[] }).items.filter(validPluginRuntime)
|
|
||||||
: [];
|
|
||||||
const failures = [healthResult, runtimesResult, workerResult]
|
|
||||||
.filter((result) => result.status === "rejected").length;
|
|
||||||
setSnapshot({
|
|
||||||
controlPlane: validControlPlaneHealth(healthPayload) ? healthPayload : null,
|
|
||||||
pluginRuntimes: runtimeItems,
|
|
||||||
simulationWorker: workerResult.status === "fulfilled"
|
|
||||||
? workerResult.value.worker
|
|
||||||
: null,
|
|
||||||
controlPlaneLatencyMs: healthResult.status === "fulfilled"
|
|
||||||
? healthResult.value.latencyMs
|
|
||||||
: null,
|
|
||||||
simulationGatewayLatencyMs: workerResult.status === "fulfilled"
|
|
||||||
? workerResult.value.latencyMs
|
|
||||||
: null,
|
|
||||||
observedAt: new Date(),
|
|
||||||
error: failures === 0
|
|
||||||
? null
|
|
||||||
: `Не ответили ${failures} из 3 диагностических контрактов.`,
|
|
||||||
});
|
|
||||||
}).finally(() => {
|
|
||||||
if (!controller.signal.aborted) setLoading(false);
|
|
||||||
});
|
|
||||||
return () => controller.abort();
|
|
||||||
},[generation]);
|
},[generation]);
|
||||||
|
const summary=contourSummary(snapshot);
|
||||||
useEffect(() => {
|
const core=snapshot?.core;
|
||||||
const timer = window.setInterval(refresh, 5_000);
|
const {controlledDevice,deviceControlConnectivity}=contourRuntimeAuthorityPresentation(state);
|
||||||
return () => window.clearInterval(timer);
|
const refresh=<IconButton label={loading?"Проверка состояния":"Обновить состояние контура"} disabled={loading} onClick={()=>setGeneration(value=>value+1)}><Icon name="refresh" size={16}/></IconButton>;
|
||||||
}, [refresh]);
|
return <div className="contour-health-dashboard">
|
||||||
|
{headerToolsHost?createPortal(refresh,headerToolsHost):refresh}
|
||||||
const {
|
|
||||||
aiActive,
|
|
||||||
deviceControlConnectivity,
|
|
||||||
controlledDevice,
|
|
||||||
} = contourRuntimeAuthorityPresentation(state);
|
|
||||||
const simulationWorker = snapshot?.simulationWorker ?? null;
|
|
||||||
const controlPlaneReady = Boolean(snapshot?.controlPlane?.ok);
|
|
||||||
const runtimeReady = snapshot?.pluginRuntimes.filter(
|
|
||||||
(runtime) => runtime.status === "ready",
|
|
||||||
).length ?? 0;
|
|
||||||
const processCount = (snapshot?.pluginRuntimes.length ?? 0) + 2;
|
|
||||||
const readyProcessCount = runtimeReady
|
|
||||||
+ (controlPlaneReady ? 1 : 0)
|
|
||||||
+ (simulationWorker?.available ? 1 : 0);
|
|
||||||
const nodeStatus = useMemo(() => {
|
|
||||||
if (!snapshot) return "Проверяем";
|
|
||||||
if (controlPlaneReady && snapshot.error === null) return "Контур отвечает";
|
|
||||||
if (controlPlaneReady) return "Частично доступен";
|
|
||||||
return "Нет связи";
|
|
||||||
}, [controlPlaneReady, snapshot]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="contour-health-dashboard">
|
|
||||||
<section className="contour-health-summary">
|
<section className="contour-health-summary">
|
||||||
<div>
|
<div><h2>Узлы и связь</h2><p>Mission Core, зарегистрированные вычислители и бортовые компьютеры аппаратов.</p></div>
|
||||||
<span className="section-eyebrow">ЖИВОЙ ДИАГНОСТИЧЕСКИЙ СРЕЗ</span>
|
<div className="contour-health-summary__status"><StatusBadge tone={loading?'warning':summary.tone}>{loading?'Проверка состояния':summary.label}</StatusBadge></div>
|
||||||
<h2>Локальный вычислительный контур</h2>
|
|
||||||
<p>
|
|
||||||
Статусы читаются из Control Plane, plugin runtime и шлюза Simulation Worker.
|
|
||||||
Пустые значения не подменяются демонстрационными числами.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="contour-health-summary__status">
|
|
||||||
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
|
|
||||||
{nodeStatus}
|
|
||||||
</StatusBadge>
|
|
||||||
<Button
|
|
||||||
size="compact"
|
|
||||||
variant="secondary"
|
|
||||||
disabled={loading}
|
|
||||||
onClick={refresh}
|
|
||||||
>
|
|
||||||
<Icon name="refresh" size={14} />
|
|
||||||
{loading ? "Проверяем" : "Обновить"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
|
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
|
||||||
<div>
|
<div><span>Узлы в сети</span><strong>{summary.online??'—'} / {summary.total??'—'}</strong><small>Core, вычислители и бортовые ПК</small></div>
|
||||||
<span>Узлы</span>
|
<div><span>Вычислители</span><strong>{snapshot?.workers?.length??'—'}</strong><small>из настроек системы</small></div>
|
||||||
<strong>{snapshot ? 2 : "—"}</strong>
|
<div><span>Бортовые компьютеры</span><strong>{snapshot?.vehicles?.length??'—'}</strong><small>из реестра аппаратов</small></div>
|
||||||
<small>локальный + внешний worker</small>
|
<div><span>Последняя проверка</span><strong>{observed(snapshot?.observedAt)}</strong><small>обновление каждые 5 секунд</small></div>
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span>Процессы готовы</span>
|
|
||||||
<strong>{snapshot ? `${readyProcessCount} / ${processCount}` : "—"}</strong>
|
|
||||||
<small>по живым health-контрактам</small>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span>Локальный API</span>
|
|
||||||
<strong>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</strong>
|
|
||||||
<small>браузер → Control Plane</small>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span>Последняя проверка</span>
|
|
||||||
<strong>{formatObservedAt(snapshot?.observedAt ?? null)}</strong>
|
|
||||||
<small>автообновление каждые 5 секунд</small>
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
|
<section className="contour-node-grid" aria-label="Узлы контура">
|
||||||
<section className="contour-node-grid" aria-label="Вычислительные узлы">
|
<article className="contour-node" data-state={core?(core.ok?'online':'degraded'):'unknown'}>
|
||||||
<article className="contour-node" data-state={controlPlaneReady ? "online" : "offline"}>
|
<header><div><span className="section-eyebrow">КОМПЬЮТЕР ОПЕРАТОРА</span><h3>Mission Core</h3></div><StatusBadge tone={core?.ok?'success':'warning'}>{core?'В сети':snapshot?'Не в сети':'Проверка состояния'}</StatusBadge></header>
|
||||||
<header>
|
<dl><div><dt>Версия</dt><dd>{core?.version??'—'}</dd></div><div><dt>Время ответа</dt><dd>{snapshot?.latency==null?'—':`${Math.max(1,Math.round(snapshot.latency))} мс`}</dd></div><div><dt>Обработчики устройств готовы</dt><dd>{core?`${core.plugin_runtimes.ready} / ${core.plugin_runtimes.total}`:'—'}</dd></div></dl>
|
||||||
<div>
|
{!core?.ok&&core?.components?.recording_cache?.status==='capacity-pressure'&&<small>Недостаточно свободного места для новых записей.</small>}
|
||||||
<span className="section-eyebrow">УЗЕЛ 01 · ЛОКАЛЬНЫЙ</span>
|
|
||||||
<h3>Mission Core Control Plane</h3>
|
|
||||||
</div>
|
|
||||||
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
|
|
||||||
{controlPlaneReady ? "Доступен" : "Недоступен"}
|
|
||||||
</StatusBadge>
|
|
||||||
</header>
|
|
||||||
<dl>
|
|
||||||
<div><dt>Версия</dt><dd>{snapshot?.controlPlane?.version ?? "—"}</dd></div>
|
|
||||||
<div><dt>API latency</dt><dd>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</dd></div>
|
|
||||||
<div><dt>Plugin runtimes</dt><dd>{snapshot ? `${runtimeReady} / ${snapshot.pluginRuntimes.length}` : "—"}</dd></div>
|
|
||||||
<div><dt>Активный режим</dt><dd>{state?.sourceMode ?? "idle"}</dd></div>
|
|
||||||
</dl>
|
|
||||||
<div className="contour-process-list">
|
|
||||||
{snapshot?.pluginRuntimes.map((runtime) => (
|
|
||||||
<div key={runtime.runtime_instance_id}>
|
|
||||||
<i data-state={runtime.status === "ready" ? "online" : "offline"} />
|
|
||||||
<span>
|
|
||||||
<strong>Device runtime · {runtime.plugin_id}</strong>
|
|
||||||
<small>v{runtime.plugin_version} · {formatObservedAt(runtime.observed_at)}</small>
|
|
||||||
</span>
|
|
||||||
<em>{runtime.status}</em>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div>
|
|
||||||
<i data-state={aiActive ? "online" : "idle"} />
|
|
||||||
<span>
|
|
||||||
<strong>AI perception</strong>
|
|
||||||
<small>
|
|
||||||
{aiActive
|
|
||||||
? `${Math.round(state?.metrics?.aiFrameRateHz ?? 0)} кадр/с`
|
|
||||||
: "Нет активного задания"}
|
|
||||||
</small>
|
|
||||||
</span>
|
|
||||||
<em>{aiActive ? "active" : "idle"}</em>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
|
|
||||||
<article
|
|
||||||
className="contour-node"
|
|
||||||
data-state={simulationWorker?.available ? "online" : "offline"}
|
|
||||||
>
|
|
||||||
<header>
|
|
||||||
<div>
|
|
||||||
<span className="section-eyebrow">УЗЕЛ 02 · ВНЕШНИЙ</span>
|
|
||||||
<h3>{simulationWorker?.workerId ?? "Simulation Worker"}</h3>
|
|
||||||
</div>
|
|
||||||
<StatusBadge tone={simulationWorker?.available ? "success" : "neutral"}>
|
|
||||||
{simulationWorker?.available ? "Доступен" : "Offline"}
|
|
||||||
</StatusBadge>
|
|
||||||
</header>
|
|
||||||
<dl>
|
|
||||||
<div><dt>Gateway latency</dt><dd>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</dd></div>
|
|
||||||
<div><dt>Сеть worker</dt><dd>{simulationWorker?.isolation.network ?? "unavailable"}</dd></div>
|
|
||||||
<div><dt>Политика данных</dt><dd>{simulationWorker?.isolation.artifactPolicy ?? "d-only"}</dd></div>
|
|
||||||
<div><dt>Активный прогон</dt><dd>{simulationWorker?.activeRunId ?? "нет"}</dd></div>
|
|
||||||
</dl>
|
|
||||||
<div className="contour-process-list">
|
|
||||||
<div>
|
|
||||||
<i data-state={simulationWorker?.available ? "online" : "offline"} />
|
|
||||||
<span>
|
|
||||||
<strong>Simulation orchestration</strong>
|
|
||||||
<small>
|
|
||||||
{simulationWorker?.runState
|
|
||||||
? `Прогон: ${simulationWorker.runState}`
|
|
||||||
: "Нет активного прогона"}
|
|
||||||
</small>
|
|
||||||
</span>
|
|
||||||
<em>{simulationWorker?.available ? "ready" : "offline"}</em>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</article>
|
</article>
|
||||||
|
{snapshot?.workers?.map(({contour,telemetry})=>{
|
||||||
|
const status=workerConnectionStatus(telemetry);
|
||||||
|
return <article key={contour.contour_id} className="contour-node" data-state={status.state}>
|
||||||
|
<header><div><span className="section-eyebrow">ВЫЧИСЛИТЕЛЬ</span><h3>{contour.display_name}</h3></div><StatusBadge tone={status.tone}>{status.label}</StatusBadge></header>
|
||||||
|
<dl><div><dt>Узел</dt><dd>{contour.expected_node_id}</dd></div><div><dt>Телеметрия</dt><dd>{contour.telemetry_mode==='agent-mqtt'?'Агент':'Диагностика SSH'}</dd></div><div><dt>Проверено</dt><dd>{observed(telemetry?.connection.observed_at_utc)}</dd></div><div><dt>Последнее измерение</dt><dd>{observed(telemetry?.node?.observed_at_utc)}</dd></div><div><dt>Операционная система</dt><dd>{telemetry?.node?.os.caption??'—'}</dd></div></dl>
|
||||||
|
{status.detail&&<small>{status.detail}</small>}
|
||||||
|
</article>;
|
||||||
|
})}
|
||||||
|
{snapshot?.vehicles?.map(vehicle=>{
|
||||||
|
const online=boardAvailable(vehicle);
|
||||||
|
const status=vehicle.enrollment==='revoked'?'Привязка отозвана':vehicle.enrollment==='pending'?'Подключение':vehicle.enrollment==='failed'?'Не подключён':online?'В сети':'Не в сети';
|
||||||
|
return <article key={vehicle.id} className="contour-node" data-state={online?'online':'offline'}>
|
||||||
|
<header><div><span className="section-eyebrow">БОРТОВОЙ КОМПЬЮТЕР</span><h3>{vehicle.name}</h3></div><StatusBadge tone={online?'success':'neutral'}>{status}</StatusBadge></header>
|
||||||
|
<dl><div><dt>Имя БК</dt><dd>{vehicle.host?.hostname??'—'}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host?.os??'—'}</dd></div><div><dt>Последняя связь</dt><dd>{observed(vehicle.last_seen===null?null:vehicle.last_seen*1000)}</dd></div></dl>
|
||||||
|
{!online&&vehicle.host&&<small>Сведения о БК сохранены с последнего подключения.</small>}
|
||||||
|
</article>;
|
||||||
|
})}
|
||||||
</section>
|
</section>
|
||||||
|
{controlledDevice&&<section className="contour-connected-device"><span className="section-eyebrow">ПОДКЛЮЧЁННОЕ УСТРОЙСТВО ОПЕРАТОРА</span><strong>{controlledDevice.displayName}</strong><small>{deviceControlConnectivity==='degraded'?'Поток данных нарушен':'Управляющая связь подтверждена'}</small></section>}
|
||||||
<section className="contour-network-strip" aria-label="Состояние сети">
|
{snapshot?.errors.map(error=><p key={error} className="contour-health-error" role="status">{error}</p>)}
|
||||||
<div>
|
</div>;
|
||||||
<span className="section-eyebrow">СЕТЬ</span>
|
|
||||||
<strong>Браузер</strong>
|
|
||||||
<small>127.0.0.1:8000</small>
|
|
||||||
</div>
|
|
||||||
<Icon name="chevron-right" />
|
|
||||||
<div>
|
|
||||||
<i data-state={controlPlaneReady ? "online" : "offline"} />
|
|
||||||
<strong>Control Plane</strong>
|
|
||||||
<small>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</small>
|
|
||||||
</div>
|
|
||||||
<Icon name="chevron-right" />
|
|
||||||
<div>
|
|
||||||
<i data-state={simulationWorker?.available ? "online" : "offline"} />
|
|
||||||
<strong>Worker gateway</strong>
|
|
||||||
<small>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</small>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{controlledDevice ? (
|
|
||||||
<section className="contour-connected-device">
|
|
||||||
<span className="section-eyebrow">ПОДТВЕРЖДЁННАЯ УПРАВЛЯЮЩАЯ СЕССИЯ</span>
|
|
||||||
<strong>{controlledDevice.displayName}</strong>
|
|
||||||
<small>
|
|
||||||
{controlledDevice.endpointLabel ?? controlledDevice.modelId}
|
|
||||||
{deviceControlConnectivity === "degraded"
|
|
||||||
? " · управление подтверждено, поток данных нарушен"
|
|
||||||
: " · управление подтверждено"}
|
|
||||||
</small>
|
|
||||||
</section>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{snapshot?.error ? (
|
|
||||||
<p className="contour-health-error" role="status">{snapshot.error}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -431,12 +431,13 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
|
|||||||
case "missions":
|
case "missions":
|
||||||
return <MissionPlannerWorkspace openView={props.navigation.openView} headerToolsHost={props.headerToolsHost} />;
|
return <MissionPlannerWorkspace openView={props.navigation.openView} headerToolsHost={props.headerToolsHost} />;
|
||||||
case "vehicles":
|
case "vehicles":
|
||||||
return <VehiclesWorkspace createRequest={props.fleetCreateRequest} headerToolsHost={props.headerToolsHost} />;
|
return <VehiclesWorkspace headerToolsHost={props.headerToolsHost} headerTitleHost={props.headerTitleHost} />;
|
||||||
case "catalog":
|
case "catalog":
|
||||||
return <CatalogWorkspace {...props} />;
|
return <CatalogWorkspace {...props} />;
|
||||||
case "contour-health":
|
case "contour-health":
|
||||||
return (
|
return (
|
||||||
<ContourHealthWorkspace
|
<ContourHealthWorkspace
|
||||||
|
headerToolsHost={props.headerToolsHost}
|
||||||
state={props.state}
|
state={props.state}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ export interface LaboratoryViewAction {
|
|||||||
|
|
||||||
export interface WorkspaceRendererProps {
|
export interface WorkspaceRendererProps {
|
||||||
launchProfile?: WorkspaceLaunchProfile;
|
launchProfile?: WorkspaceLaunchProfile;
|
||||||
fleetCreateRequest?: number;
|
|
||||||
headerToolsHost?: HTMLElement | null;
|
headerToolsHost?: HTMLElement | null;
|
||||||
|
headerTitleHost?: HTMLElement | null;
|
||||||
definition: WorkspaceDefinition;
|
definition: WorkspaceDefinition;
|
||||||
state: MissionRuntimeState | null;
|
state: MissionRuntimeState | null;
|
||||||
backendStatus: BackendStatus;
|
backendStatus: BackendStatus;
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {Button,Icon,IconButton,ResourceRow,StatusBadge,Window} from '@nodedc/ui-react';
|
||||||
|
import type {Vehicle} from '../../core/fleet/useFleet';
|
||||||
|
|
||||||
|
export const boardStatus=(item:Vehicle,available=true)=>item.enrollment==='pending'?'Подтверждаем привязку':item.enrollment==='revoked'?'Не привязан':item.enrollment==='failed'?'Привязка не завершена':item.connectivity==='online'?(available?'В сети':'Не в сети'):'Не в сети';
|
||||||
|
export function BoardComputerRow({vehicle,enabled,showingSavedDevices,onSettings,onMonitor,onAdd,open,onToggle}:{vehicle:Vehicle;enabled:boolean;showingSavedDevices:boolean;onSettings:()=>void;onMonitor:()=>void;onAdd?:()=>void;open:boolean;onToggle:()=>void}){
|
||||||
|
const label=boardStatus(vehicle,enabled);
|
||||||
|
return <ResourceRow icon={<Icon name="apps"/>} title="Бортовой компьютер" description={vehicle.host?.hostname||'Mission Core Node'} metadata={`${label}${showingSavedDevices?' (показаны последние сохранённые устройства)':''}`} statusPlacement="leading"
|
||||||
|
status={<StatusBadge variant="indicator" tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'} aria-label={label} title={label}/>}
|
||||||
|
actions={<>{onAdd&&<IconButton label="Добавить устройство к БК" onClick={onAdd}><Icon name="plus"/></IconButton>}<IconButton label="Настройки бортового компьютера" onClick={onSettings}><Icon name="settings"/></IconButton><IconButton label="Мониторинг системы БК" onClick={onMonitor}><Icon name="activity"/></IconButton><IconButton label={open?'Свернуть устройства БК':'Показать устройства БК'} aria-expanded={open} onClick={onToggle}><Icon name={open?'chevron-down':'chevron-right'}/></IconButton></>}/>;
|
||||||
|
}
|
||||||
|
export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicle:Vehicle;enabled:boolean;onClose:()=>void;onRevoke:()=>void}){
|
||||||
|
return <Window open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'} onClose={onClose}>
|
||||||
|
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
|
||||||
|
{vehicle.notice&&<p role="status">{vehicle.notice}</p>}
|
||||||
|
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
|
||||||
|
{vehicle.host&&<><div><dt>Имя БК в системе</dt><dd>{vehicle.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host.os}</dd></div><div><dt>Архитектура</dt><dd>{vehicle.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{vehicle.host.cpus}</dd></div><div><dt>Память</dt><dd>{vehicle.host.memory_kib?`${(vehicle.host.memory_kib/1048576).toFixed(1)} ГиБ`:'Нет сведений'}</dd></div></>}
|
||||||
|
</dl>
|
||||||
|
{vehicle.enrollment!=='revoked'&&<Button onClick={onRevoke}>Отозвать привязку БК</Button>}
|
||||||
|
</div>
|
||||||
|
</Window>;
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
|
||||||
import {useState} from 'react';
|
import {useState} from 'react';
|
||||||
import {ActivityIndicator,Button,Icon,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
|
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
|
||||||
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
|
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
|
||||||
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
|
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
|
||||||
import '../../styles/system-telemetry.css';
|
import '../../styles/system-telemetry.css';
|
||||||
@@ -7,7 +8,7 @@ import './board-monitor.css';
|
|||||||
|
|
||||||
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
|
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
|
||||||
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
|
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
|
||||||
export function BoardMonitorView({vehicle,name,back}:{vehicle:string;name:string;back:()=>void}) {
|
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
|
||||||
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
|
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
|
||||||
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
|
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
|
||||||
const definitions=value?.definitions??{},definition=definitions[metric];
|
const definitions=value?.definitions??{},definition=definitions[metric];
|
||||||
@@ -15,7 +16,7 @@ export function BoardMonitorView({vehicle,name,back}:{vehicle:string;name:string
|
|||||||
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
|
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
|
||||||
const latest=value?.latest;
|
const latest=value?.latest;
|
||||||
return <div className="board-monitor">
|
return <div className="board-monitor">
|
||||||
<div><Button onClick={back}><Icon name="chevron-left"/>К аппарату</Button></div>
|
<WorkspaceBackButton label="К аппарату" onClick={back} host={headerToolsHost}/>
|
||||||
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
|
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
|
||||||
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
|
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
|
||||||
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
|
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import {useId,useState,type FormEvent} from 'react';
|
||||||
|
import {Button,Select,SettingsCard,TextAreaField,TextField,StatusBadge} from '@nodedc/ui-react';
|
||||||
|
import {fleetRequest,type FleetPreview,type Vehicle} from '../../core/fleet/useFleet';
|
||||||
|
import type {SensorEnrollmentProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||||
|
import {InstallerCard} from './equipment/InstallerCard';
|
||||||
|
|
||||||
|
export const platforms=[{value:'ugv',label:'Наземный (UGV)'},{value:'uav',label:'Воздушный (UAV)'},{value:'stationary',label:'Стационарный'},{value:'other',label:'Другой'}];
|
||||||
|
export const platformLabel=(value:string)=>platforms.find(item=>item.value===value)?.label??value;
|
||||||
|
|
||||||
|
/** The invitation admits a computer; an existing apparatus keeps its identity. */
|
||||||
|
export function NodeInvitationForm({vehicle,onClose,onComplete,renderWindow}:{vehicle?:Vehicle;onClose:()=>void;onComplete:(vehicle:Vehicle)=>void;renderWindow:SensorEnrollmentProps['renderWindow']}){
|
||||||
|
const form=useId();
|
||||||
|
const [revision]=useState(vehicle?.revision);
|
||||||
|
const [code,setCode]=useState(''),[name,setName]=useState(''),[platform,setPlatform]=useState('ugv');
|
||||||
|
const [preview,setPreview]=useState<FleetPreview|null>(null),[pending,setPending]=useState(false),[error,setError]=useState('');
|
||||||
|
async function inspect(event:FormEvent){
|
||||||
|
event.preventDefault();if(pending)return;setPending(true);setError('');
|
||||||
|
try{const value=await fleetRequest<FleetPreview>('/preview','POST',{code:code.trim()});setPreview(value);setName(current=>current||value.name);setCode('');}
|
||||||
|
catch(e){setError(e instanceof Error?e.message:'Не удалось проверить приглашение.');}
|
||||||
|
finally{setPending(false);}
|
||||||
|
}
|
||||||
|
async function attach(){
|
||||||
|
if(!preview||pending)return;setPending(true);setError('');
|
||||||
|
try{
|
||||||
|
const result=vehicle
|
||||||
|
?await fleetRequest<Vehicle>(`/${encodeURIComponent(vehicle.id)}/computer`,'POST',{preview_id:preview.preview_id,expected_revision:revision})
|
||||||
|
:await fleetRequest<Vehicle>('','POST',{preview_id:preview.preview_id,name:name.trim(),platform});
|
||||||
|
onComplete(result);
|
||||||
|
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить БК.');}
|
||||||
|
finally{setPending(false);}
|
||||||
|
}
|
||||||
|
const replacing=!!vehicle&&vehicle.enrollment!=='revoked';
|
||||||
|
return renderWindow({busy:pending,actions:<><Button disabled={pending} onClick={onClose}>Отмена</Button>{preview?<Button loading={pending} disabled={pending||(!vehicle&&!name.trim())} onClick={()=>void attach()}>{vehicle?(replacing?'Заменить БК':'Подключить БК'):'Добавить аппарат'}</Button>:<Button loading={pending} type="submit" form={form} disabled={pending||!code.trim()}>Проверить БК</Button>}</>,content:
|
||||||
|
<form id={form} className="fleet-form" onSubmit={inspect} aria-busy={pending}>
|
||||||
|
{!preview&&<InstallerCard kind="node"/>}
|
||||||
|
{!vehicle&&<><Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending}/><TextField label="Название аппарата" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={pending} autoComplete="off"/></>}
|
||||||
|
{vehicle&&<SettingsCard title={vehicle.name} description={replacing?'Новый БК заменит текущий. Аппарат, его название и раскладки сохранятся; прежняя привязка будет отозвана.':'Подключите БК к этому аппарату по приглашению Mission Core Node.'}/>}
|
||||||
|
{preview?<SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={()=>setPreview(null)}>Другое приглашение</Button></SettingsCard>:<TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={e=>setCode(e.target.value)}/>}
|
||||||
|
{pending&&<StatusBadge tone="warning">{preview?'Подключение БК':'Проверка приглашения БК'}</StatusBadge>}
|
||||||
|
{error&&<p role="alert">{error}</p>}
|
||||||
|
</form>});
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import {useEffect,useSyncExternalStore} from 'react';
|
||||||
|
import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
|
||||||
|
import type {BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout';
|
||||||
|
import type {SensorBoardContent} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||||
|
import type {Vehicle} from '../../core/fleet/useFleet';
|
||||||
|
import {VehicleIdentitySettings} from './VehicleIdentitySettings';
|
||||||
|
import {BoardComputerRow} from './BoardComputer';
|
||||||
|
import {IndependentEquipment} from './equipment/IndependentEquipment';
|
||||||
|
|
||||||
|
export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;layout:BoardLayoutStore;content:SensorBoardContent;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
|
||||||
|
const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot);
|
||||||
|
useEffect(()=>{void layout.load();},[layout]);
|
||||||
|
const computerOpen=state.value.open_sections.includes('computer');
|
||||||
|
// The former computer-section preference now controls its nested device branch.
|
||||||
|
const changeSections=(ids:string[])=>layout.change([...ids,...(computerOpen?['computer']:[])]);
|
||||||
|
const toggleComputer=()=>layout.change(computerOpen?state.value.open_sections.filter(id=>id!=='computer'):[...state.value.open_sections,'computer']);
|
||||||
|
return <div className="sensor-content">
|
||||||
|
{state.error&&<div role="alert"><p>{state.error}</p><Button onClick={()=>void layout.load()}>Повторить</Button></div>}
|
||||||
|
<LoadingRegion loading={!state.ready&&!state.error} label="Загрузка раскладки аппарата">
|
||||||
|
<Inspector variant="panel" openSections={state.value.open_sections.filter(id=>id!=='computer')} onOpenSectionsChange={changeSections} sections={[
|
||||||
|
{id:'settings',label:'Настройки аппарата',icon:<Icon name="sliders"/>,disabled:!state.ready,content:<div className="sensor-content"><VehicleIdentitySettings key={vehicle.id} vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>},
|
||||||
|
{id:'devices',label:'Оборудование',icon:<Icon name="apps"/>,disabled:!state.ready,content:<div className="sensor-content">
|
||||||
|
<IndependentEquipment key={vehicle.id} vehicle={vehicle} onComputer={onAddComputer} onRefresh={()=>void content.refresh()} computer={<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
|
||||||
|
{computerOpen&&<div className="fleet-computer-devices">{content.devices}</div>}
|
||||||
|
</div>}/>
|
||||||
|
</div>},
|
||||||
|
]}/>
|
||||||
|
</LoadingRegion>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import {useEffect,useState} from 'react';
|
||||||
|
import {Button,SettingsCard,TextField} from '@nodedc/ui-react';
|
||||||
|
import {fleetRequest,type Vehicle} from '../../core/fleet/useFleet';
|
||||||
|
|
||||||
|
export function VehicleIdentitySettings({vehicle,onUpdated}:{vehicle:Vehicle;onUpdated:(vehicle:Vehicle)=>void}){
|
||||||
|
const [base,setBase]=useState(vehicle),[name,setName]=useState(vehicle.name);
|
||||||
|
const [saving,setSaving]=useState(false),[message,setMessage]=useState(''),[error,setError]=useState('');
|
||||||
|
const dirty=name!==base.name;
|
||||||
|
useEffect(()=>{if(!dirty&&!saving){setBase(vehicle);setName(vehicle.name);}},[vehicle,dirty,saving]);
|
||||||
|
const reset=()=>{setBase(vehicle);setName(vehicle.name);setError('');setMessage('');};
|
||||||
|
const save=async()=>{
|
||||||
|
if(saving||!name.trim()||!dirty)return;
|
||||||
|
setSaving(true);setError('');setMessage('');
|
||||||
|
try{
|
||||||
|
const updated=await fleetRequest<Vehicle>(`/${encodeURIComponent(vehicle.id)}`,'PATCH',{name:name.trim(),expected_revision:base.revision});
|
||||||
|
onUpdated(updated);setBase(updated);setName(updated.name);setMessage('Название сохранено');
|
||||||
|
}catch(reason){setError(reason instanceof Error?reason.message:'Не удалось сохранить название.');}
|
||||||
|
finally{setSaving(false);}
|
||||||
|
};
|
||||||
|
return <SettingsCard title="Основные параметры">
|
||||||
|
<form className="fleet-form" onSubmit={event=>{event.preventDefault();void save();}}>
|
||||||
|
<TextField label="Название аппарата" value={name} maxLength={80} autoComplete="off" disabled={saving} onChange={event=>{setName(event.target.value);setMessage('');}}/>
|
||||||
|
<div className="sensor-actions"><Button type="submit" disabled={!dirty||!name.trim()||saving}>{saving?'Сохранение…':'Сохранить'}</Button>{dirty&&<Button type="button" variant="secondary" disabled={saving} onClick={reset}>Отмена</Button>}</div>
|
||||||
|
{error&&<p role="alert">{error}</p>}{message&&<p role="status">{message}</p>}
|
||||||
|
</form>
|
||||||
|
</SettingsCard>;
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
import {useMemo,type ReactNode} from 'react';
|
import {useMemo} from 'react';
|
||||||
import {boardLayout} from '../../core/fleet/boardLayout';
|
import {boardLayout} from '../../core/fleet/boardLayout';
|
||||||
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
|
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
|
||||||
import {createIsolatedRerunHost} from '../../components/rerun/isolatedRerunHost';
|
import {createIsolatedRerunHost} from '../../components/rerun/isolatedRerunHost';
|
||||||
import {SensorWorkspace} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
|
import {SensorWorkspace} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||||
import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
|
import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
|
||||||
export function VehicleSensors({vehicleID,enabled,computer,description}:{vehicleID:string;enabled:boolean;computer:ReactNode;description:string}){
|
import type {Vehicle} from '../../core/fleet/useFleet';
|
||||||
|
import {VehicleEquipment} from './VehicleEquipment';
|
||||||
|
export function VehicleSensors({vehicle,enabled,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
|
||||||
|
const vehicleID=vehicle.id;
|
||||||
const {registry}=useDevicePluginHost();
|
const {registry}=useDevicePluginHost();
|
||||||
const sensorContributions=registry.sensorContributions;
|
const sensorContributions=registry.sensorContributions;
|
||||||
const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]);
|
const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]);
|
||||||
const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
||||||
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} board={{layout,computer,description}}/>;
|
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={`${vehicleID}:${vehicle.node_id}`} transport={transport} enabled={enabled} readOfflineInventory renderBoard={content=><VehicleEquipment vehicle={vehicle} enabled={enabled} layout={layout} content={content} onAddComputer={onAddComputer} onSettings={onSettings} onMonitor={onMonitor} onUpdated={onUpdated}/>}/>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,75 +1,41 @@
|
|||||||
|
import {useState} from 'react';
|
||||||
|
import {createPortal} from 'react-dom';
|
||||||
|
import {LoadingRegion,ConfirmationModal,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||||
|
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
|
||||||
|
import {fleetRequest,useFleet,type Vehicle} from '../../core/fleet/useFleet';
|
||||||
import {BoardObservationCenter} from './observation/BoardObservationCenter';
|
import {BoardObservationCenter} from './observation/BoardObservationCenter';
|
||||||
import {BoardMonitorView} from './BoardMonitorView';
|
import {BoardMonitorView} from './BoardMonitorView';
|
||||||
import { useEffect, useRef, useState } from "react";
|
import {VehicleSensors} from './VehicleSensors';
|
||||||
import { LoadingRegion, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, TextAreaField, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
import {BoardComputerSettings,boardStatus} from './BoardComputer';
|
||||||
import { fleetRequest, useFleet, type FleetPreview, type Vehicle } from "../../core/fleet/useFleet";
|
import {NodeInvitationForm,platformLabel} from './NodeInvitationForm';
|
||||||
import "./fleet.css";
|
import './fleet.css';
|
||||||
import { VehicleSensors } from "./VehicleSensors";
|
|
||||||
|
|
||||||
const platforms = [{ value: "ugv", label: "Наземный (UGV)" }, { value: "uav", label: "Воздушный (UAV)" }, { value: "stationary", label: "Стационарный" }, { value: "other", label: "Другой" }];
|
export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){
|
||||||
const platformLabel = (value: string) => platforms.find(item => item.value === value)?.label ?? value;
|
|
||||||
function statusLabel(item: Vehicle) { return item.enrollment === "pending" ? "Подтверждаем привязку" : item.enrollment === "revoked" ? "Доверие отозвано" : item.enrollment === "failed" ? "Привязка не завершена" : item.connectivity === "online" ? "В сети" : "Нет связи"; }
|
|
||||||
|
|
||||||
export function VehiclesWorkspace({ createRequest = 0, headerToolsHost }: { createRequest?: number; headerToolsHost?: HTMLElement|null }) {
|
|
||||||
const fleet=useFleet();
|
const fleet=useFleet();
|
||||||
const [adding, setAdding] = useState(false);
|
|
||||||
const [code, setCode] = useState("");
|
|
||||||
const [name, setName] = useState("");
|
|
||||||
const [platform, setPlatform] = useState("ugv");
|
|
||||||
const [preview, setPreview] = useState<FleetPreview | null>(null);
|
|
||||||
const [pending, setPending] = useState(false);
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const [selected,setSelected]=useState<string|null>(null);
|
const [selected,setSelected]=useState<string|null>(null);
|
||||||
const [monitorOpen,setMonitorOpen]=useState(false);
|
const [adding,setAdding]=useState(false),[monitorOpen,setMonitorOpen]=useState(false),[observationOpen,setObservationOpen]=useState(false),[settingsOpen,setSettingsOpen]=useState(false);
|
||||||
const [observationOpen,setObservationOpen]=useState(false);
|
const [revoking,setRevoking]=useState<Vehicle|null>(null),[error,setError]=useState('');
|
||||||
const [revoking, setRevoking] = useState<Vehicle | null>(null);
|
|
||||||
const lastCreateRequest = useRef(createRequest);
|
|
||||||
useEffect(() => { if (createRequest !== lastCreateRequest.current) { lastCreateRequest.current = createRequest; setAdding(true); setError(""); } }, [createRequest]);
|
|
||||||
function close() { if (pending) return; setAdding(false); setPreview(null); setCode(""); setName(""); setError(""); }
|
|
||||||
async function inspect(event: React.FormEvent) {
|
|
||||||
event.preventDefault(); if (pending) return;
|
|
||||||
setPending(true); setError("");
|
|
||||||
try { const value = await fleetRequest<FleetPreview>("/preview", "POST", { code: code.trim() }); setPreview(value); setName(current => current || value.name); setCode(""); }
|
|
||||||
catch (error) { setError(error instanceof Error ? error.message : "Не удалось проверить приглашение."); }
|
|
||||||
finally { setPending(false); }
|
|
||||||
}
|
|
||||||
async function add() {
|
|
||||||
if (!preview || pending) return;
|
|
||||||
setPending(true); setError("");
|
|
||||||
try {
|
|
||||||
const item = await fleetRequest<Vehicle>("", "POST", { preview_id: preview.preview_id, name: name.trim(), platform });
|
|
||||||
await fleet.refresh(); setSelected(item.id); setAdding(false); setPreview(null); setCode(""); setName("");
|
|
||||||
} catch (error) { setError(error instanceof Error ? error.message : "Не удалось добавить аппарат."); void fleet.refresh().catch(() => undefined); }
|
|
||||||
finally { setPending(false); }
|
|
||||||
}
|
|
||||||
const detail=fleet.items?.find(item=>item.id===selected);
|
const detail=fleet.items?.find(item=>item.id===selected);
|
||||||
if(detail&&observationOpen)return <BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={!fleet.error&&detail.enrollment==="paired"&&detail.connectivity==="online"} back={()=>{setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>;
|
const enabled=!!detail&&!fleet.error&&detail.enrollment==='paired'&&detail.connectivity==='online';
|
||||||
if(detail&&monitorOpen)return <BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)}/>;
|
const refresh=()=>{void fleet.refresh().catch(()=>setError('Не удалось обновить аппарат. Повторите получение сведений.'));};
|
||||||
return <div className="fleet-workspace">
|
const complete=(item:Vehicle)=>{setSelected(item.id);setAdding(false);refresh();};
|
||||||
{fleet.error && <p role="alert">{fleet.error}</p>}
|
const addButton=<IconButton label="Добавить аппарат" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton>;
|
||||||
{!adding && error && <p role="alert">{error}</p>}
|
const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton);
|
||||||
|
const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:'';
|
||||||
|
const observationButton=<IconButton label="Центр наблюдения и управления" onClick={()=>setObservationOpen(true)}><Icon name="eye"/></IconButton>;
|
||||||
|
const headerObservation=detail&&!observationOpen&&!monitorOpen&&(headerToolsHost?createPortal(observationButton,headerToolsHost):observationButton);
|
||||||
|
const content=detail&&observationOpen?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled} back={()=>{setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>
|
||||||
|
:detail&&monitorOpen?<BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)} headerToolsHost={headerToolsHost}/>
|
||||||
|
:<div className="fleet-workspace">
|
||||||
{detail?<>
|
{detail?<>
|
||||||
<div><Button onClick={() => {setSelected(null);}}>К списку аппаратов</Button></div>
|
<WorkspaceBackButton label="К списку аппаратов" onClick={()=>setSelected(null)} host={headerToolsHost}/>
|
||||||
<VehicleSensors vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} description={detail.name} computer={<SettingsCard title={detail.name} description={`${platformLabel(detail.platform)} · с бортовым компьютером`} actions={<StatusBadge tone={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(detail)}</StatusBadge>}>
|
<VehicleSensors onUpdated={fleet.acceptVehicle} vehicle={detail} enabled={enabled} onAddComputer={()=>setAdding(true)} onSettings={()=>setSettingsOpen(true)} onMonitor={()=>setMonitorOpen(true)}/>
|
||||||
{detail.notice && <p role="status">{detail.notice}</p>}
|
</>:!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><li key={item.id}><ResourceRow icon={<Icon name="apps"/>} title={item.name} description={platformLabel(item.platform)} status={<StatusBadge tone={!fleet.error&&item.enrollment==='paired'&&item.connectivity==='online'?'success':'neutral'}>{fleet.error?'Нет свежих данных':`БК: ${boardStatus(item)}`}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={()=>setSelected(item.id)}><Icon name="sliders"/></IconButton><IconButton label={`Центр наблюдения и управления: ${item.name}`} onClick={()=>{setSelected(item.id);setObservationOpen(true);}}><Icon name="eye"/></IconButton></>}/></li>)}</ResourceList>}
|
||||||
<dl className="fleet-facts"><div><dt>Бортовой компьютер</dt><dd>{detail.node_id}</dd></div>
|
|
||||||
<div><dt>Последняя связь</dt><dd>{detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}</dd></div>
|
|
||||||
{detail.host && <><div><dt>Имя БК в системе</dt><dd>{detail.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{detail.host.os}</dd></div><div><dt>Архитектура</dt><dd>{detail.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{detail.host.cpus}</dd></div><div><dt>Память</dt><dd>{detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}</dd></div></>}
|
|
||||||
</dl>
|
|
||||||
<div className="fleet-board-actions"><Button onClick={()=>setMonitorOpen(true)}><Icon name="activity"/>Мониторинг системы БК</Button>
|
|
||||||
<Button onClick={()=>setObservationOpen(true)}><Icon name="eye"/>Центр наблюдения и управления</Button>
|
|
||||||
{detail.enrollment !== "revoked" && <Button onClick={() => setRevoking(detail)}>Отозвать привязку БК</Button>}</div>
|
|
||||||
</SettingsCard>}/>
|
|
||||||
</> : !fleet.items ? <LoadingRegion loading label="Получение аппаратов" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="sliders" /></IconButton><IconButton label={`Центр наблюдения и управления: ${item.name}`} onClick={() => {setSelected(item.id);setObservationOpen(true);}}><Icon name="eye" /></IconButton></>} /></li>)}</ResourceList>}
|
|
||||||
<Window open={adding} title="Добавить аппарат" subtitle="Подключить бортовой компьютер по приглашению Node" size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={close} footer={<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button>{preview ? <Button disabled={pending || !name.trim()} onClick={() => void add()}>{pending ? "Добавление…" : "Добавить аппарат"}</Button> : <Button type="submit" form="fleet-invitation" disabled={pending || !code.trim()}>{pending ? "Проверка БК…" : "Проверить БК"}</Button>}</WindowFooterActions>}>
|
|
||||||
<form id="fleet-invitation" className="fleet-form" onSubmit={inspect} aria-busy={pending}>
|
|
||||||
<Select label="Способ подключения" value="node" options={[{ value: "node", label: "С бортовым компьютером" }]} onChange={() => undefined} disabled={pending} />
|
|
||||||
<Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending} />
|
|
||||||
<TextField label="Название аппарата" value={name} maxLength={80} onChange={event => setName(event.target.value)} disabled={pending} autoComplete="off" />
|
|
||||||
{preview ? <SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={() => setPreview(null)}>Другое приглашение</Button></SettingsCard> : <TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={event => setCode(event.target.value)} />}
|
|
||||||
{error && <p role="alert">{error}</p>}
|
|
||||||
</form>
|
|
||||||
</Window>
|
|
||||||
<ConfirmationModal open={revoking !== null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name ?? ""}» останется в реестре, а его БК потеряет доступ к Core. БК получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={() => setRevoking(null)} onConfirm={async () => { if (!revoking) return; try { await fleetRequest(`/${encodeURIComponent(revoking.id)}`, "DELETE"); await fleet.refresh(); setRevoking(null); } catch (error) { setError(error instanceof Error ? error.message : "Не удалось отозвать привязку."); throw error; } }} />
|
|
||||||
</div>;
|
</div>;
|
||||||
|
return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{headerObservation}{content}
|
||||||
|
{adding&&<NodeInvitationForm key={detail?.id??'new'} vehicle={detail} onClose={()=>setAdding(false)} onComplete={complete} renderWindow={({content,actions,busy})=><Window open title={detail?'Подключить бортовой компьютер':'Добавить аппарат'} subtitle={detail?detail.name:'Создать аппарат и подключить БК по приглашению Node'} size="md" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)setAdding(false);}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}>{content}</Window>}/>}
|
||||||
|
{settingsOpen&&detail&&<BoardComputerSettings vehicle={detail} enabled={enabled} onClose={()=>setSettingsOpen(false)} onRevoke={()=>{setSettingsOpen(false);setRevoking(detail);}}/>}
|
||||||
|
<ConfirmationModal open={revoking!==null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name??''}» останется в реестре. БК потеряет доступ к Core и получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={()=>setRevoking(null)} onConfirm={async()=>{if(!revoking)return;try{await fleetRequest(`/${encodeURIComponent(revoking.id)}`,'DELETE');await fleet.refresh();setRevoking(null);}catch(e){setError(e instanceof Error?e.message:'Не удалось отозвать привязку.');throw e;}}}/>
|
||||||
|
<ToastStack items={error||fleet.error?[{id:'fleet-error',title:error||fleet.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
|
||||||
|
</>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import {Button,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||||
|
import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime';
|
||||||
|
import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts';
|
||||||
|
|
||||||
|
export function CommandHistory({identifier,items,selected,onSelect,onCancel,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;working:boolean;cancelling:string}){
|
||||||
|
return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){
|
||||||
|
const attempts=useCommandAttempts(identifier,current);
|
||||||
|
return <SettingsCard title={current.description.label??'Операция B2'} description={`ID ${current.id} · ПО ${current.firmware??'неизвестно'}`}>
|
||||||
|
{current.description.wire&&<p><code>{current.description.wire}</code></p>}
|
||||||
|
<dl className="fleet-facts">
|
||||||
|
<div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div>
|
||||||
|
{current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>}
|
||||||
|
<div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div>
|
||||||
|
{current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>}
|
||||||
|
{current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>}
|
||||||
|
<div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div>
|
||||||
|
{current.reconnected_at!==undefined&&<div><dt>Возвращение на связь</dt><dd>{commandDate(current.reconnected_at)}</dd></div>}
|
||||||
|
</dl>
|
||||||
|
{commandReason(current)&&<p>{commandReason(current)}</p>}
|
||||||
|
<p>{current.description.confirmation}</p>
|
||||||
|
{current.stop_requested&&<p>Новые попытки остановлены или ожидают остановки на VPS. Уже переданная попытка может завершиться.</p>}
|
||||||
|
{current.durable&&<>
|
||||||
|
<ResourceList aria-label="Попытки доставки">{attempts.items.map(item=><li key={item.id}><ResourceRow title={`Попытка ${item.number}${item.phase==='inspect'?' · проверка состояния':''}`} description={`Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDate(item.received_at)} · ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandStatus(item.state)}</StatusBadge>} metadata={item.device_code!==undefined?commandReceipt({...current,device_code:item.device_code}):undefined}/></li>)}</ResourceList>
|
||||||
|
{attempts.error&&<><p>{attempts.error}</p><Button onClick={attempts.refresh}>Повторить чтение попыток</Button></>}
|
||||||
|
{attempts.next_before!==null&&<Button loading={attempts.working} onClick={()=>void attempts.more()}>Предыдущие попытки</Button>}
|
||||||
|
</>}
|
||||||
|
<ResourceList aria-label="Этапы операции">{[...current.events].sort((a,b)=>(a.occurred_at??a.observed_at)-(b.occurred_at??b.observed_at)).map((event,index)=><li key={index}><ResourceRow title={`${commandStatus(event.state)}${event.attempt?` ${event.attempt}`:''}`} description={event.stage?({preflight:'Чтение настроек',write:'Запись',verify:'Проверка',restart:'Ожидание после перезапуска'} as Record<string,string>)[event.stage]:undefined} metadata={`${commandDate(event.occurred_at??event.observed_at)}${event.historical?' · восстановлено из истории':''}`}/></li>)}</ResourceList>
|
||||||
|
</SettingsCard>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import {SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||||
|
import {cellularCardOperator,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular';
|
||||||
|
import type {EquipmentObservation} from '../../../core/fleet/equipment';
|
||||||
|
import type {TrackerTelemetry} from '../../../core/fleet/vps';
|
||||||
|
|
||||||
|
export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation}){
|
||||||
|
const status=telemetry?.cellular?.status;
|
||||||
|
const configTime=observed.configuration_read_at??observed.read_at;
|
||||||
|
return <div className="fleet-form">
|
||||||
|
{(['1','2'] as const).map(slot=>{
|
||||||
|
const view=cellularSlotView(telemetry,slot),network=view.network;
|
||||||
|
const fresh=!!telemetry?.online&&cellularFresh(network);
|
||||||
|
const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
|
||||||
|
return <SettingsCard key={slot} title={`SIM ${slot}`} description={view.absent?'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.':cellularCardOperator(telemetry,slot)??cellularNetworkLabel(network)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}>
|
||||||
|
<dl className="fleet-facts">
|
||||||
|
<div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div>
|
||||||
|
{!view.absent&&network&&<>
|
||||||
|
<div><dt>Сигнал</dt><dd>{network.signal===null?'Неизвестен':`${network.signal} из 31`}</dd></div>
|
||||||
|
<div><dt>{fresh?'Сеть измерена':'Последнее измерение сети'}</dt><dd>{new Date(network.measured_at*1000).toLocaleString('ru-RU')}</dd></div>
|
||||||
|
</>}
|
||||||
|
<div><dt>APN из настроек B2</dt><dd>{apn||'Не задан'}<br/>Прочитан {new Date(configTime*1000).toLocaleString('ru-RU')}</dd></div>
|
||||||
|
</dl>
|
||||||
|
</SettingsCard>;
|
||||||
|
})}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import {useState} from 'react';
|
||||||
|
import {Button,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||||
|
import {commandPending} from '../../../core/fleet/commandRuntime';
|
||||||
|
import {useCommandRuntime} from '../../../core/fleet/useCommandRuntime';
|
||||||
|
import {telemetryLabel,type TrackerTelemetry} from '../../../core/fleet/vps';
|
||||||
|
import type {IndependentDevice} from '../../../core/fleet/equipment';
|
||||||
|
import {CommandHistory} from './CommandHistory';
|
||||||
|
|
||||||
|
export function EquipmentCommandWindow({device,telemetry,onClose}:{device:IndependentDevice;telemetry?:TrackerTelemetry;onClose:()=>void}){
|
||||||
|
const runtime=useCommandRuntime(device.id);
|
||||||
|
const [preset,setPreset]=useState('position'),[filter,setFilter]=useState('all'),[selected,setSelected]=useState('');
|
||||||
|
const data=runtime.data,chosen=data?.catalog.find(value=>value.id===(runtime.intent?.preset_id??preset));
|
||||||
|
const pending=Object.entries(data?.counts??{}).reduce((total,[state,n])=>total+(commandPending(state)?n:0),0);
|
||||||
|
const items=runtime.items.filter(item=>filter==='all'||(filter==='active'?commandPending(item.state):!commandPending(item.state)));
|
||||||
|
return <><Window open title="Команды ARNavi B2" subtitle={data?.device.name??device.name} size="lg" onClose={onClose}>
|
||||||
|
<div className="fleet-form">
|
||||||
|
<StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>
|
||||||
|
<LoadingRegion loading={!data&&!runtime.error} label="Загрузка команд и журнала">
|
||||||
|
{data&&<>
|
||||||
|
<SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}>
|
||||||
|
<Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/>
|
||||||
|
{chosen&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.':`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>}
|
||||||
|
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||pending>=data.capacity))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions>
|
||||||
|
</SettingsCard>
|
||||||
|
<SettingsCard title="Журнал операций" description={`Незавершённых: ${pending} · Вместимость очереди: ${data.capacity}`}>
|
||||||
|
<Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/>
|
||||||
|
{!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>}
|
||||||
|
<CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} working={runtime.working} cancelling={runtime.activity}/>
|
||||||
|
{runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>}
|
||||||
|
</SettingsCard>
|
||||||
|
</>}
|
||||||
|
</LoadingRegion>
|
||||||
|
{!data&&runtime.error&&<Button onClick={()=>void runtime.refresh().catch(()=>undefined)}>Повторить чтение</Button>}
|
||||||
|
</div>
|
||||||
|
</Window><ToastStack items={runtime.error?[{id:'command-runtime-error',title:runtime.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>runtime.setError('')}/></>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import {useState} from 'react';
|
||||||
|
import {Button,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||||
|
import {equipmentRequest,type EquipmentCandidate,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||||
|
import {NodeInvitationForm} from '../NodeInvitationForm';
|
||||||
|
import {VPSHostSettings} from './VPSHostSettings';
|
||||||
|
import type {VPSHost} from '../../../core/fleet/vps';
|
||||||
|
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||||
|
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||||
|
|
||||||
|
export function EquipmentConnect({vehicle,vehicles,models,profiles,hosts,onComputer,onVPS,onClose,onAdded}:{vehicle:Vehicle;vehicles:Vehicle[];models:EquipmentModel[];profiles:EquipmentProfile[];hosts:VPSHost[];onComputer:()=>void;onVPS:()=>void;onClose:()=>void;onAdded:(item:IndependentDevice)=>void}){
|
||||||
|
const [type,setType]=useState('computer'),[name,setName]=useState(''),[target,setTarget]=useState(vehicle.id),[profile,setProfile]=useState('');
|
||||||
|
const [candidate,setCandidate]=useState<EquipmentCandidate|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||||
|
const model=models.find(m=>m.id===type),selectedProfile=profiles.find(p=>p.id===profile);
|
||||||
|
async function inspect(){setBusy(true);setError('');setCandidate(null);try{const value=await equipmentRequest<EquipmentCandidate>('/inspect','POST',{model_id:type});setCandidate(value);setName(current=>current||`${model?.label??''} · ${value.observed.device_id}`);}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать устройство.');}finally{setBusy(false);}}
|
||||||
|
async function add(){if(!candidate)return;setBusy(true);setError('');try{onAdded(await equipmentRequest<IndependentDevice>('/instances','POST',{candidate_id:candidate.id,name:name.trim(),vehicle_id:target,profile_id:profile||null}));}catch(e){setError(e instanceof Error?e.message:'Не удалось добавить устройство.');}finally{setBusy(false);}}
|
||||||
|
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,busy:pending})=><Window open title="Подключить независимое устройство" subtitle={vehicle.name} size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={()=>{if(!pending)onClose();}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}><div className="fleet-form"><Select label="Тип устройства" value={type} options={[{value:'computer',label:'Бортовой компьютер'},...models.map(m=>({value:m.id,label:m.label})),{value:'vps-host',label:'VPS Host ARNavi'}]} disabled={pending} onChange={value=>{setType(value);setCandidate(null);setName('');setProfile('');}}/>{content}</div></Window>;
|
||||||
|
if(type==='computer')return <NodeInvitationForm vehicle={vehicle} onClose={onClose} onComplete={()=>onComputer()} renderWindow={renderWindow}/>;
|
||||||
|
if(type==='vps-host')return <VPSHostSettings hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={onClose} onSaved={onVPS} renderWindow={renderWindow}/>;
|
||||||
|
return <>{renderWindow({busy,actions:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!candidate||!name.trim()||!target} onClick={()=>void add()}>Добавить к аппарату</Button></>,content:<div className="fleet-form">
|
||||||
|
{model&&<><TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||||
|
<Select label="Аппарат" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
|
||||||
|
<Select label="Профиль настроек" value={profile} options={[{value:'',label:'Прочитать настройки трекера'},...profiles.filter(p=>p.model_id===type).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} onChange={setProfile} disabled={busy}/>
|
||||||
|
{selectedProfile&&<SettingsCard title={selectedProfile.name} description={selectedProfile.settings.endpoint?`${selectedProfile.settings.endpoint.host}:${selectedProfile.settings.endpoint.port} · сервер ${selectedProfile.settings.endpoint.slot}`:'Адрес сервера сохраняется из трекера'}/>}
|
||||||
|
<SettingsCard title="USB на этом Mac" description="Подключите один трекер кабелем с передачей данных. Проверка считает модель, идентификатор и настройки."><Button loading={busy} disabled={busy} onClick={()=>void inspect()}>{candidate?'Прочитать повторно':'Проверить USB'}</Button></SettingsCard>
|
||||||
|
{candidate&&<SettingsCard title={`${candidate.observed.model} · ${candidate.observed.device_id}`} description={`IMEI …${candidate.observed.imei_suffix} · ПО ${candidate.observed.firmware}`}><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>Устройство будет добавлено в реестр. Передача на ваш сервер ещё не подтверждена; выбранный профиль будет сохранён для настройки.</p></SettingsCard>}
|
||||||
|
</>}
|
||||||
|
</div>
|
||||||
|
})}<ToastStack items={error?[{id:'equipment-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import {useEffect,useRef,useState} from 'react';
|
||||||
|
import {Button,Icon,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
|
||||||
|
import type {IndependentDevice} from '../../../core/fleet/equipment';
|
||||||
|
import {downloadFirmware,readFirmware,uploadFirmware,type FirmwareCatalog} from '../../../core/fleet/firmware';
|
||||||
|
|
||||||
|
export function EquipmentFirmware({device}:{device:IndependentDevice}){
|
||||||
|
const [catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[selected,setSelected]=useState('');
|
||||||
|
const [loading,setLoading]=useState(true),[uploading,setUploading]=useState(false),[downloading,setDownloading]=useState(false);
|
||||||
|
const [loadError,setLoadError]=useState(''),[error,setError]=useState(''),[notice,setNotice]=useState(''),[reload,setReload]=useState(0);
|
||||||
|
const picker=useRef<HTMLInputElement>(null);
|
||||||
|
useEffect(()=>{let active=true;setLoading(true);setLoadError('');
|
||||||
|
readFirmware(device.model_id).then(value=>{if(active){setCatalog(value);setSelected(current=>value.items.some(item=>item.id===current)?current:value.items[0]?.id??'');}})
|
||||||
|
.catch(e=>{if(active)setLoadError(e instanceof Error?e.message:'Не удалось прочитать архив прошивок.');})
|
||||||
|
.finally(()=>{if(active)setLoading(false);});return()=>{active=false;};
|
||||||
|
},[device.model_id,reload]);
|
||||||
|
const item=catalog?.items.find(image=>image.id===selected);
|
||||||
|
async function add(file:File){setUploading(true);setError('');setNotice('');try{
|
||||||
|
const image=await uploadFirmware(device.model_id,file);setSelected(image.id);setReload(value=>value+1);setNotice('Файл сохранён в Mission Core. Прошивка трекера не изменена.');
|
||||||
|
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}finally{setUploading(false);}}
|
||||||
|
async function download(){if(!item)return;setDownloading(true);setError('');try{await downloadFirmware(item);}catch(e){setError(e instanceof Error?e.message:'Не удалось скачать файл.');}finally{setDownloading(false);}}
|
||||||
|
const recordedVersion=device.observed.firmware;
|
||||||
|
return <>
|
||||||
|
<SettingsCard title="Прошивка трекера" description="Последняя считанная версия устройства.">
|
||||||
|
<dl className="fleet-facts"><div><dt>Версия</dt><dd>{recordedVersion||'Нет сведений'}</dd></div><div><dt>Считана</dt><dd>{device.observed.read_at?new Date(device.observed.read_at*1000).toLocaleString('ru-RU'):'Нет сведений'}</dd></div></dl>
|
||||||
|
<p>Обновление прошивки через Mission Core недоступно. Файлы ниже хранятся отдельно от настроек трекера.</p>
|
||||||
|
</SettingsCard>
|
||||||
|
<SettingsCard title="Файлы прошивок" description="Архив Mission Core. Добавление и выбор файла не запускают установку.">
|
||||||
|
<input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/>
|
||||||
|
<Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button>
|
||||||
|
<LoadingRegion loading={loading} label="Читаем архив прошивок">
|
||||||
|
{loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<>
|
||||||
|
<Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/>
|
||||||
|
{item&&<>
|
||||||
|
<StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge>
|
||||||
|
<dl className="fleet-facts"><div><dt>Версия файла</dt><dd>{item.version??'Не определена'}</dd></div><div><dt>Размер</dt><dd>{new Intl.NumberFormat('ru-RU').format(item.bytes)} байт</dd></div><div><dt>Сохранён</dt><dd>{new Date(item.added_at*1000).toLocaleString('ru-RU')}</dd></div></dl>
|
||||||
|
<Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button>
|
||||||
|
</>}
|
||||||
|
{recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>}
|
||||||
|
</>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>}
|
||||||
|
</LoadingRegion>
|
||||||
|
</SettingsCard>
|
||||||
|
<ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
|
||||||
|
import {cellularFresh,cellularSimOptions} from '../../../core/fleet/cellular';
|
||||||
|
import {allowBothInternetSims,selectInternetSim,type ConnectivityPreset,type EquipmentObservation,type EquipmentPolicy} from '../../../core/fleet/equipment';
|
||||||
|
import type {TrackerTelemetry} from '../../../core/fleet/vps';
|
||||||
|
|
||||||
|
export function EquipmentInternet({telemetry,observed,presets,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
|
||||||
|
const options=cellularSimOptions(telemetry);
|
||||||
|
const preferred=['both','native'].includes(value.connectivity.strategy)?value.connectivity.strategy:value.connectivity.activate?String(value.connectivity.sim_slot??1):'';
|
||||||
|
const both=['both','native'].includes(preferred);
|
||||||
|
const slot=both?preferred:options.some(option=>option.value===preferred)?preferred:'';
|
||||||
|
const current=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
|
||||||
|
const connection=value.connectivity;
|
||||||
|
const automatic=connection.strategy==='sim'&&connection.automatic===true;
|
||||||
|
const access=telemetry?.internet_access?.[slot];
|
||||||
|
const targeted=String(connection.sim_slot??1)===slot;
|
||||||
|
const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current;
|
||||||
|
return <SettingsCard title="Интернет"><div className="fleet-form">
|
||||||
|
<Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Обе SIM — без заданного APN'},{value:'both',label:'Обе SIM — сохранить APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/>
|
||||||
|
<p>{slot==='native'?'Оба слота разрешены. APN, логин и пароль обеих SIM будут очищены; B2 попробует подключиться без них. Для тарифов со специальным APN сохраните текущие параметры. После применения B2 перезапустится, результат проверим по новой связи.':slot==='both'?'B2 сможет использовать любую из установленных SIM. APN обеих карт сохранятся. Одновременно работает одна SIM; срок автоматического переключения не гарантирован. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или разрешите обе. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p>
|
||||||
|
{!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>}
|
||||||
|
{slot&&!both?<>
|
||||||
|
<Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/>
|
||||||
|
{automatic?<p>{access?.state==='ready'?`${access.source==='verified_card'?'Проверенные настройки этой карты':'Стандартные настройки оператора'}: ${access.apn}. После сохранения проверим запись и подключение выбранной SIM.`:access?.state==='unknown_card'?'Карта ещё не распознана. Прочитайте её через USB или отключите автоподбор и задайте APN.':access?.state==='unsupported_operator'?'Для этой карты нет сохранённых настроек. Отключите автоподбор и задайте APN.':'Ожидаем подтверждение карты в выбранном слоте.'}</p>:<TextField label="APN" value={apn} maxLength={29} disabled={disabled} hint={`В B2 прочитан: ${current||'не задан'}. Изменение будет отправлено при сохранении настроек.`} onChange={event=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:false,apn:event.target.value,apn1:'',apn2:'',preset_id:null}})}/>}
|
||||||
|
</>:!both&&!options.length&&<p>Ожидаем актуальные сведения о SIM от трекера.</p>}
|
||||||
|
</div></SettingsCard>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
|
||||||
|
import type {TrackerTelemetry,VPSHost} from '../../../core/fleet/vps';
|
||||||
|
import type {ConnectivityPreset,EquipmentField,EquipmentObservation,EquipmentPolicy} from '../../../core/fleet/equipment';
|
||||||
|
|
||||||
|
import {EquipmentInternet} from './EquipmentInternet';
|
||||||
|
|
||||||
|
export function EquipmentPolicyFields({hosts,section,fields,presets,telemetry,observed,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;hosts:VPSHost[];section:string;fields:EquipmentField[];presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
|
||||||
|
if(section==='connection')return <div className="fleet-form">
|
||||||
|
<EquipmentInternet telemetry={telemetry} observed={observed} presets={presets} value={value} onChange={onChange} disabled={disabled}/>
|
||||||
|
<SettingsCard title="Сервер мониторинга" description="Используйте постоянное DNS-имя: при переезде VPS можно сохранить адрес в трекерах.">
|
||||||
|
<div className="fleet-form"><Select label="Зарегистрированный VPS" value={hosts.find(h=>h.status?.tracker.host===value.endpoint?.host&&h.status?.tracker.port===value.endpoint?.port)?.id??''} options={[{value:'',label:'Сохранить адрес или указать вручную'},...hosts.filter(h=>h.status).map(h=>({value:h.id,label:h.name}))]} disabled={disabled} onChange={id=>{const host=hosts.find(h=>h.id===id);if(host?.status)onChange({...value,endpoint:{...host.status.tracker,slot:value.endpoint?.slot??2}});}}/><Switch label="Задать сервер в профиле" checked={value.endpoint!==null} disabled={disabled} onChange={enabled=>onChange({...value,endpoint:enabled?{host:'',port:0,slot:1}:null})}/>
|
||||||
|
{value.endpoint&&<><TextField label="DNS/IP сервера" value={value.endpoint.host} maxLength={49} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,host:e.target.value}})}/><TextField label="Порт" type="number" min={1} max={65535} value={value.endpoint.port||''} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,port:Number(e.target.value)}})}/><Select label="Слот сервера" value={String(value.endpoint.slot)} options={[1,2,3,4].map(n=>({value:String(n),label:`Сервер ${n}`}))} disabled={disabled} onChange={slot=>onChange({...value,endpoint:{...value.endpoint!,slot:Number(slot)}})}/><p>Протокол INTERNAL. Остальные серверы сохраняются.</p></>}
|
||||||
|
</div>
|
||||||
|
</SettingsCard>
|
||||||
|
</div>;
|
||||||
|
return <div className="fleet-form"><p>Пустое поле — сохранить значение конкретного трекера. Ноль — задать нулевое значение.</p>{fields.filter(f=>f.group===section).map(field=><TextField key={field.key} label={field.label} type="number" min={field.min} max={field.max} step={1} hint={`${field.min} … ${field.max}`} value={value.parameters[field.key]??''} disabled={disabled} onChange={e=>{const parameters={...value.parameters};if(e.target.value==='')delete parameters[field.key];else parameters[field.key]=Number(e.target.value);onChange({...value,parameters});}}/>)}</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import {useEffect,useRef,useState} from 'react';
|
||||||
|
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||||
|
import {configurationWriteNotStarted,simSelectionIntent,equipmentPolicyEqual,equipmentApplyMessage,equipmentRequest,networkOperationMessage,networkOperationProgress,policyError,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||||
|
import {cellularSimCurrent} from '../../../core/fleet/cellular';
|
||||||
|
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||||
|
import {telemetryLabel,type TrackerTelemetry,type VPSHost} from '../../../core/fleet/vps';
|
||||||
|
import {EquipmentPolicyFields} from './EquipmentPolicyFields';
|
||||||
|
import {EquipmentCellular} from './EquipmentCellular';
|
||||||
|
import {EquipmentFirmware} from './EquipmentFirmware';
|
||||||
|
|
||||||
|
export function EquipmentSettings({device,model,hosts,telemetry,vehicles,profiles,onClose,onObserved,onProfile,onCommands}:{device:IndependentDevice;model:EquipmentModel;hosts:VPSHost[];telemetry?:TrackerTelemetry;vehicles:Vehicle[];profiles:EquipmentProfile[];onClose:()=>void;onObserved:(item:IndependentDevice)=>void;onProfile:()=>void;onCommands:()=>void}){
|
||||||
|
const [name,setName]=useState(device.name),[target,setTarget]=useState(device.vehicle_id),[settings,setSettings]=useState(device.settings),[section,setSection]=useState('identity');
|
||||||
|
const [profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false),[working,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[selectedProfile,setSelectedProfile]=useState('');
|
||||||
|
const contentRef=useRef<HTMLDivElement>(null);
|
||||||
|
const [simRequested,setSimRequested]=useState(false);
|
||||||
|
const selectSim=simSelectionIntent(settings,device.settings,simRequested);
|
||||||
|
function changeSettings(value:typeof settings){if(value.connectivity!==settings.connectivity)setSimRequested(true);setSettings(value);}
|
||||||
|
const [now,setNow]=useState(()=>Date.now()/1000);
|
||||||
|
const progress=networkOperationProgress(device.network_operation,now);
|
||||||
|
const networkPending=progress.pending;
|
||||||
|
useEffect(()=>{if(!networkPending)return;setNow(Date.now()/1000);const timer=setInterval(()=>setNow(Date.now()/1000),1000);return()=>clearInterval(timer);},[networkPending,device.network_operation?.id]);
|
||||||
|
const busy=working||networkPending;
|
||||||
|
useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&¤t)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]);
|
||||||
|
const observed=device.observed;
|
||||||
|
const secondary=observed.configuration.servers.find(s=>s.slot===2);
|
||||||
|
const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port);
|
||||||
|
const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters);
|
||||||
|
const fields=model.fields.filter(f=>supported.includes(f.key));
|
||||||
|
const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':'');
|
||||||
|
const dirty=name!==device.name||target!==device.vehicle_id||!equipmentPolicyEqual(settings,device.settings);
|
||||||
|
const writable=model.usb_write_firmware?.includes(observed.firmware)??false;
|
||||||
|
const [applying,setApplying]=useState(false),[saving,setSaving]=useState(false),[readingUsb,setReadingUsb]=useState(false);
|
||||||
|
async function applyUsb(){setBusy(true);setApplying(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/apply`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Результат записи не получен. Прочитайте USB повторно.');}finally{setBusy(false);setApplying(false);}}
|
||||||
|
const sections=[{id:'identity',label:'Устройство и аппарат'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...Array.from(new Set(fields.map(f=>f.group))).map(group=>({id:group,label:group,group:'Параметры профиля'}))];
|
||||||
|
async function readNetwork(){setBusy(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect-network`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Чтение через VPS не подтверждено.');}finally{setBusy(false);}}
|
||||||
|
async function applyNetwork(item:IndependentDevice=device,selection=selectSim){setBusy(true);setError('');contentRef.current?.scrollIntoView({block:'start'});try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${item.id}/apply-network`,'POST',{expected_revision:item.revision,select_sim:selection}));setSimRequested(false);}catch(e){setError(e instanceof Error?e.message:'Отправка через VPS не подтверждена.');}finally{setBusy(false);}}
|
||||||
|
async function save(){setBusy(true);setSaving(true);setError('');setNotice('');try{const changed=!equipmentPolicyEqual(settings,device.settings);const retrySelection=selectSim;if(!dirty&&!retrySelection){setNotice('Изменений настроек нет. Команда трекеру не отправлена.');return;}const item=dirty?await equipmentRequest<IndependentDevice>(`/instances/${device.id}`,'PUT',{expected_revision:device.revision,name:name.trim(),vehicle_id:target,settings}):device;onObserved(item);if(changed||retrySelection)await applyNetwork(item,selectSim);else setNotice('Изменения сохранены в Mission Core.');}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить настройки.');}finally{setBusy(false);setSaving(false);}}
|
||||||
|
async function readUsb(){setBusy(true);setReadingUsb(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать USB.');}finally{setBusy(false);setReadingUsb(false);}}
|
||||||
|
async function saveProfile(){setBusy(true);setError('');try{await equipmentRequest('/profiles','POST',{name:profileName.trim(),model_id:device.model_id,settings});setProfileOpen(false);setNotice('Профиль сохранён и доступен при подключении новых трекеров.');onProfile();}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{setBusy(false);}}
|
||||||
|
return <><FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={device.name} identity={{title:model.label,subtitle:`IMEI …${observed.imei_suffix}`,avatarLabel:model.label}} sections={sections} activeSection={section} onSectionChange={setSection} onClose={()=>{if(!working)onClose();}} footer={section==='firmware'?undefined:<WindowFooterActions><Button loading={saving} disabled={busy||!!validation||!name.trim()||!target} onClick={()=>void save()}>Сохранить настройки</Button><Button disabled={working||!!validation} onClick={()=>{setProfileName(`${model.label} — ${name}`.slice(0,80));setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>}>
|
||||||
|
<div className="fleet-form" ref={contentRef}><StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>{section!=='commands'&§ion!=='firmware'&&<SettingsCard title="Настройки через VPS" description={fullSettings?"Параметры профиля записываются через VPS. Текущие настройки читаются перед записью, а результат проверяется повторным чтением. Адрес резервного сервера сохраняется.":"По сети доступна смена адреса и порта сервера 1. Сервер 2 сохраняет связь с текущим VPS. Для полной конфигурации нужен обновлённый VPS."}><p>{equipmentApplyMessage(configurationWriteNotStarted(device.network_operation)?'not_started':device.policy_state)}</p>{device.network_server1&&<p>Последний подтверждённый сервер 1: {device.network_server1.host}:{device.network_server1.port}.</p>}<p>{networkOperationMessage(device.network_operation?.scope!=='command'?device.network_operation:undefined)}</p>{networkPending&&device.network_operation?.scope!=='command'&&<p>{device.network_operation?.durable?`Попыток: ${device.network_operation.attempt_count??0}. Окно можно закрыть — задание сохранено. Повторы можно остановить в журнале команд.`:progress.overdue?'Срок ожидания истёк. Уточняем результат у VPS; повторная отправка заблокирована до получения результата.':`До окончания ожидания: ${progress.remaining??'—'} с. Окно можно закрыть — операция продолжится на VPS.`}</p>}<Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&!device.network_operation?.read_only} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyNetwork()}>Отправить через VPS</Button><Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&device.network_operation?.read_only} disabled={busy||dirty} onClick={()=>void readNetwork()}>Прочитать через VPS</Button></SettingsCard>}
|
||||||
|
{section==='connection'&&<EquipmentCellular telemetry={telemetry} observed={observed}/>}
|
||||||
|
{section==='firmware'?<EquipmentFirmware device={device}/>:section==='identity'?<>
|
||||||
|
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||||
|
<Select label="Привязка к аппарату" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
|
||||||
|
<Select label="Загрузить сохранённый профиль" value={selectedProfile} options={[{value:'',label:'Текущие настройки'},...profiles.filter(p=>p.model_id===device.model_id).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} disabled={busy} onChange={id=>{setSelectedProfile(id);const p=profiles.find(p=>p.id===id);changeSettings(p?.settings??device.settings);}}/>
|
||||||
|
<SettingsCard title="Сведения B2" description={`ID ${observed.device_id} · ПО ${observed.firmware} · идентификация по USB ${new Date(observed.read_at*1000).toLocaleString('ru-RU')}`}>{observed.configuration_read_at&&<p>Настройки прочитаны через VPS: {new Date(observed.configuration_read_at*1000).toLocaleString('ru-RU')}.</p>}<dl className="fleet-facts"><div><dt>Основная SIM</dt><dd>{observed.sim1_iccid_reported_suffix?`…${observed.sim1_iccid_reported_suffix} (${observed.sim1_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>Вторая SIM</dt><dd>{observed.sim2_iccid_reported_suffix?`…${observed.sim2_iccid_reported_suffix} (${observed.sim2_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>APN основной SIM</dt><dd>{observed.configuration.apn1||'Не задан'}</dd></div><div><dt>APN второй SIM</dt><dd>{observed.configuration.apn2||'Не задан'}</dd></div>{observed.configuration.servers.filter(s=>s.host).map(s=><div key={s.slot}><dt>Сервер {s.slot}</dt><dd>{s.host}:{s.port}</dd></div>)}</dl><Button loading={readingUsb} disabled={busy||dirty} onClick={()=>void readUsb()}>Прочитать USB повторно</Button><Button loading={applying} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyUsb()}>Первоначальная настройка по USB</Button>{applying&&<p>Запись и проверка настроек. Не отсоединяйте USB.</p>}</SettingsCard>
|
||||||
|
</>:section==='commands'?<SettingsCard title="Команды и журнал" description="Отправка команд, очередь и история обмена с B2."><Button disabled={working||dirty} onClick={onCommands}>Открыть команды</Button>{dirty&&<p>Сохраните изменения перед переходом к командам.</p>}</SettingsCard>:<EquipmentPolicyFields telemetry={telemetry} observed={observed} hosts={hosts.filter(h=>h.vehicle_ids.includes(target))} section={section} fields={fields} presets={model.connectivity_presets??[]} value={settings} onChange={changeSettings} disabled={busy}/>}
|
||||||
|
{section!=='firmware'&&validation&&<StatusBadge tone="warning">{validation}</StatusBadge>}
|
||||||
|
</div>
|
||||||
|
</FeatureSettingsWindow>
|
||||||
|
<Window open={profileOpen} title="Сохранить профиль" subtitle="Общие настройки для новых трекеров" onClose={()=>{if(!working)setProfileOpen(false);}} closeOnEscape={!working} closeOnBackdrop={false} footer={<WindowFooterActions><Button disabled={working} onClick={()=>setProfileOpen(false)}>Отмена</Button><Button loading={working} disabled={working||!profileName.trim()||!!validation} onClick={()=>void saveProfile()}>Сохранить профиль</Button></WindowFooterActions>}><div className="fleet-form"><TextField label="Название профиля" value={profileName} maxLength={80} disabled={working} onChange={e=>setProfileName(e.target.value)}/><p>Сохранятся параметры работы, выбранный сервер и настройки связи. IMEI, номера SIM, личные пароли и привязка к аппарату не входят в профиль. Настройки уже добавленных устройств не изменятся.</p></div></Window>
|
||||||
|
<ToastStack items={error?[{id:'equipment-settings-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'equipment-profile-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import {useCallback,useEffect,useState,type ReactNode} from 'react';
|
||||||
|
import {Button,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,StatusBadge,ToastStack} from '@nodedc/ui-react';
|
||||||
|
import {equipmentRequest,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||||
|
import {fleetRequest,type Vehicle} from '../../../core/fleet/useFleet';
|
||||||
|
import {EquipmentConnect} from './EquipmentConnect';
|
||||||
|
import {EquipmentSettings} from './EquipmentSettings';
|
||||||
|
import {EquipmentCommandWindow} from './EquipmentCommandWindow';
|
||||||
|
import {hostOnline,telemetryLabel,useTrackerTelemetry,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
|
||||||
|
import {VPSHostSettings} from './VPSHostSettings';
|
||||||
|
import './equipment.css';
|
||||||
|
|
||||||
|
export function IndependentEquipment({vehicle,computer,onRefresh}:{vehicle:Vehicle;computer:ReactNode;onComputer:()=>void;onRefresh:()=>void}){
|
||||||
|
const [devices,setDevices]=useState<IndependentDevice[]|null>(null),[models,setModels]=useState<EquipmentModel[]>([]),[profiles,setProfiles]=useState<EquipmentProfile[]>([]),[vehicles,setVehicles]=useState<Vehicle[]>([]);
|
||||||
|
const [hosts,setHosts]=useState<VPSHost[]>([]),[vpsOpen,setVpsOpen]=useState(false),[selectedHost,setSelectedHost]=useState<VPSHost|undefined>();
|
||||||
|
const telemetry=useTrackerTelemetry(vehicle.id);
|
||||||
|
const [adding,setAdding]=useState(false),[selected,setSelected]=useState<IndependentDevice|null>(null),[error,setError]=useState('');
|
||||||
|
const refresh=useCallback(async()=>{
|
||||||
|
const [items,catalog,policies,fleet,vps]=await Promise.all([equipmentRequest<{items:IndependentDevice[]}>(`/instances?vehicle_id=${encodeURIComponent(vehicle.id)}`),equipmentRequest<{models:EquipmentModel[]}>('/catalog'),equipmentRequest<{items:EquipmentProfile[]}>('/profiles'),fleetRequest<{items:Vehicle[]}>(),vpsRequest<{items:VPSHost[]}>()]);
|
||||||
|
setHosts(vps.items);setDevices(items.items);setModels(catalog.models);setProfiles(policies.items);setVehicles(fleet.items);setError('');
|
||||||
|
},[vehicle.id]);
|
||||||
|
const observe=useCallback((item:IndependentDevice)=>{setSelected(item);void refresh().catch(()=>setError('Не удалось обновить независимое оборудование.'));},[refresh]);
|
||||||
|
const reload=()=>{void refresh().catch(()=>setError('Не удалось обновить независимое оборудование. Повторите запрос.'));};
|
||||||
|
useEffect(()=>{let active=true;void refresh().catch(()=>{if(active)setError('Не удалось получить независимое оборудование.');});return()=>{active=false;};},[refresh]);
|
||||||
|
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await vpsRequest<{items:VPSHost[]}>();if(active)setHosts(value.items);}catch{/* Existing timestamps expire when the connection is unavailable. */}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}void poll();return()=>{active=false;clearTimeout(timer);};},[]);
|
||||||
|
const [commandDevice,setCommandDevice]=useState<IndependentDevice|null>(null);
|
||||||
|
const model=selected&&models.find(m=>m.id===selected.model_id);
|
||||||
|
const selectedTelemetry=telemetry.items.find(t=>t.instance_id===selected?.id);
|
||||||
|
return <>
|
||||||
|
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и независимые устройства</span><div className="sensor-actions"><IconButton label="Подключить независимое устройство" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>{reload();onRefresh();}}><Icon name="refresh"/></IconButton></div></div>
|
||||||
|
{computer}
|
||||||
|
{!devices?<LoadingRegion loading={!error} label="Загрузка независимых устройств"/>:<ResourceList aria-label="Независимые устройства">{devices.map(device=><li key={device.id}><ResourceRow icon={<Icon name="network"/>} title={device.name} description={`${models.find(m=>m.id===device.model_id)?.label??device.model_id} · IMEI …${device.observed.imei_suffix}`} metadata={telemetry.unavailable?'Связь с сервером не проверена':telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={!telemetry.unavailable&&telemetry.items.find(t=>t.instance_id===device.id)?.online?'success':'neutral'} aria-label={telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))}/>} actions={<><IconButton label={`Команды: ${device.name}`} onClick={()=>setCommandDevice(device)}><Icon name="terminal"/></IconButton><IconButton label={`Настройки: ${device.name}`} onClick={()=>setSelected(device)}><Icon name="settings"/></IconButton></>}/></li>)}</ResourceList>}
|
||||||
|
<ResourceList aria-label="VPS Host ARNavi">{hosts.filter(h=>h.vehicle_ids.includes(vehicle.id)).map(host=><li key={host.id}><ResourceRow icon={<Icon name="database"/>} title={host.name} description="VPS Host ARNavi" metadata={`${host.endpoint} · Аппаратов: ${host.vehicle_ids.length}`} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={hostOnline(host)?'success':'neutral'} aria-label={hostOnline(host)?'VPS на связи':'Нет связи с VPS'}/>} actions={<IconButton label={`Настройки: ${host.name}`} onClick={()=>{setSelectedHost(host);setVpsOpen(true);}}><Icon name="settings"/></IconButton>}/></li>)}</ResourceList>
|
||||||
|
{vpsOpen&&<VPSHostSettings host={hosts.find(h=>h.id===selectedHost?.id)} hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={()=>setVpsOpen(false)} onSaved={()=>{setVpsOpen(false);reload();}}/>}
|
||||||
|
{error&&!devices&&<Button onClick={reload}>Повторить</Button>}
|
||||||
|
{adding&&<EquipmentConnect vehicle={vehicle} vehicles={vehicles} models={models} profiles={profiles} hosts={hosts} onClose={()=>setAdding(false)} onComputer={()=>{setAdding(false);onRefresh();}} onVPS={()=>{setAdding(false);reload();}} onAdded={item=>{setAdding(false);if(item.vehicle_id===vehicle.id)setSelected(item);reload();}}/>}
|
||||||
|
{selected&&model&&<EquipmentSettings key={selected.id} device={selected} model={model} hosts={hosts} telemetry={telemetry.unavailable&&selectedTelemetry?{...selectedTelemetry,online:false}:selectedTelemetry} vehicles={vehicles} profiles={profiles} onClose={()=>setSelected(null)} onObserved={observe} onProfile={reload} onCommands={()=>{setCommandDevice(selected);setSelected(null);}}/>}
|
||||||
|
{commandDevice&&<EquipmentCommandWindow key={commandDevice.id} device={commandDevice} telemetry={telemetry.items.find(t=>t.instance_id===commandDevice.id)} onClose={()=>{setCommandDevice(null);reload();}}/>}
|
||||||
|
<ToastStack items={error?[{id:'independent-equipment-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import {Fragment,useEffect,useState} from 'react';
|
||||||
|
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||||
|
|
||||||
|
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||||
|
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'}){
|
||||||
|
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||||
|
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||||
|
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||||
|
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||||
|
</SettingsCard>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import {useEffect,useState} from 'react';
|
||||||
|
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,Switch,TextAreaField,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||||
|
import {hostOnline,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
|
||||||
|
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||||
|
import {InstallerCard} from './InstallerCard';
|
||||||
|
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||||
|
|
||||||
|
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
|
||||||
|
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
|
||||||
|
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
|
||||||
|
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||||
|
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||||
|
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||||
|
const current=host??hosts.find(h=>h.id===existing);
|
||||||
|
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
|
||||||
|
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
|
||||||
|
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
|
||||||
|
const content=<div className="fleet-form">
|
||||||
|
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
|
||||||
|
{!current&&<InstallerCard kind="vps-arnavi"/>}
|
||||||
|
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||||
|
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
|
||||||
|
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
|
||||||
|
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
|
||||||
|
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
|
||||||
|
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
|
||||||
|
</div>;
|
||||||
|
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
.equipment-settings-title { display:flex; align-items:center; flex-wrap:wrap; gap:var(--nodedc-space-4); }
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
.fleet-workspace, .fleet-form { display: flex; flex-direction: column; gap: var(--nodedc-space-4); }
|
.fleet-workspace, .fleet-form { display: flex; flex-direction: column; gap: var(--nodedc-space-4); }
|
||||||
.fleet-workspace { padding: var(--nodedc-space-4); }
|
.fleet-workspace { padding: var(--nodedc-space-4); }
|
||||||
|
.fleet-header-tools { display:flex; align-items:center; gap:var(--nodedc-space-2); }
|
||||||
|
.nodedc-application-panel__titles h1 > .fleet-header-title { font:inherit; color:inherit; letter-spacing:inherit; text-transform:none; }
|
||||||
.fleet-facts { display: grid; gap: var(--nodedc-space-3); }
|
.fleet-facts { display: grid; gap: var(--nodedc-space-3); }
|
||||||
.fleet-facts > div { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr); gap: var(--nodedc-space-3); }
|
.fleet-facts > div { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr); gap: var(--nodedc-space-3); }
|
||||||
.fleet-facts dd { margin: 0; overflow-wrap: anywhere; }
|
.fleet-facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||||
@@ -10,4 +12,6 @@
|
|||||||
|
|
||||||
.fleet-board-actions { display:flex; gap:var(--nodedc-space-3); }
|
.fleet-board-actions { display:flex; gap:var(--nodedc-space-3); }
|
||||||
.fleet-board-actions > * { flex:1; }
|
.fleet-board-actions > * { flex:1; }
|
||||||
|
.fleet-computer-devices { padding-block-start:var(--nodedc-space-4); padding-inline-start:var(--nodedc-space-4); display:grid; gap:var(--nodedc-space-4); }
|
||||||
|
.fleet-form p { font-size:var(--nodedc-font-size-sm); line-height:1.5; color:var(--nodedc-text-secondary); }
|
||||||
@media(max-width:600px) { .fleet-board-actions { flex-wrap:wrap; } }
|
@media(max-width:600px) { .fleet-board-actions { flex-wrap:wrap; } }
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ import {decodeObservationLayout,emptyObservationLayout,moveObservation,orderedOb
|
|||||||
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
|
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
|
||||||
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
|
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
|
||||||
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
||||||
|
import {unboundObservationViews} from '../../../../../../packages/sensor-ui/src/observationCatalog';
|
||||||
|
import {sensorContribution} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||||
|
import {ObservationDeviceSettings} from './ObservationDeviceSettings';
|
||||||
|
import {ObservationPanelHeader} from './ObservationPanelHeader';
|
||||||
import {ObservationDeck,ObservationMount} from './ObservationDeck';
|
import {ObservationDeck,ObservationMount} from './ObservationDeck';
|
||||||
import {ObservationMap} from './ObservationMap';
|
import {ObservationMap} from './ObservationMap';
|
||||||
import {useObservationInventory} from './useObservationInventory';
|
import {useObservationInventory} from './useObservationInventory';
|
||||||
@@ -19,62 +23,66 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
|||||||
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
||||||
const inventory=useObservationInventory(transport),storageKey=`missioncore.observation.v1:${vehicleID}`;
|
const inventory=useObservationInventory(transport),storageKey=`missioncore.observation.v1:${vehicleID}`;
|
||||||
const [layout,setLayout]=useState(()=>{try{return decodeObservationLayout(JSON.parse(localStorage.getItem(storageKey)??'null'));}catch{return emptyObservationLayout();}});
|
const [layout,setLayout]=useState(()=>{try{return decodeObservationLayout(JSON.parse(localStorage.getItem(storageKey)??'null'));}catch{return emptyObservationLayout();}});
|
||||||
const [layersOpen,setLayersOpen]=useState(false),[focused,setFocused]=useState<string|null>(null);
|
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
|
||||||
|
const [layersOpen,setLayersOpen]=useState(false);
|
||||||
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
|
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
|
||||||
const frame=useRef<HTMLDivElement>(null),[portal]=useState(()=>document.createElement('div'));
|
const frame=useRef<HTMLDivElement>(null),[portal]=useState(()=>document.createElement('div'));
|
||||||
useLayoutEffect(()=>{(expanded?document.body:frame.current!).append(portal);return()=>portal.remove();},[expanded,portal]);
|
useLayoutEffect(()=>{(expanded?document.body:frame.current!).append(portal);return()=>portal.remove();},[expanded,portal]);
|
||||||
const mounts=useRef(new Map<string,HTMLElement>()),media=useRef(new Map<string,HTMLElement>()),headers=useRef(new Map<string,ObservationHeaderTargets>());
|
const mounts=useRef(new Map<string,HTMLElement>()),media=useRef(new Map<string,HTMLElement>()),headers=useRef(new Map<string,ObservationHeaderTargets>());
|
||||||
const groups=(inventory?.items??[]).flatMap(device=>{
|
const groups=(inventory?.items??[]).flatMap(device=>{
|
||||||
const contribution=registry.sensorContributions.find(item=>item.kind===device.kind)?.observation;
|
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
|
||||||
const views=contribution?.views(device)??cameraObservationViews(device);
|
const views=contribution?.views(device)??cameraObservationViews(device);
|
||||||
return views.length?[{device,views,Session:contribution?.Session??CameraObservation}]:[];
|
return views.length?[{device,views,Session:contribution?.Session??CameraObservation}]:[];
|
||||||
});
|
});
|
||||||
const sources:{key:string;deviceID?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
|
const sources:{key:string;deviceID?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
|
||||||
|
sources.push(...unboundObservationViews(inventory?.items??[],registry.sensorContributions));
|
||||||
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
|
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
|
||||||
for(const source of sources){if(!mounts.current.has(source.key)){mounts.current.set(source.key,document.createElement('div'));media.current.set(source.key,document.createElement('div'));headers.current.set(source.key,{statusTarget:document.createElement('div'),actionsTarget:document.createElement('div')});mounts.current.get(source.key)!.className='observation-panel-mount';media.current.get(source.key)!.className='observation-media-mount';}}
|
for(const source of sources){if(!mounts.current.has(source.key)){mounts.current.set(source.key,document.createElement('div'));media.current.set(source.key,document.createElement('div'));headers.current.set(source.key,{statusTarget:document.createElement('div'),actionsTarget:document.createElement('div')});mounts.current.get(source.key)!.className='observation-panel-mount';media.current.get(source.key)!.className='observation-media-mount';}}
|
||||||
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id));
|
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id)&&(!sources.find(source=>source.key===id)?.catalog||layout.catalogVisible?.includes(id)));
|
||||||
const effectiveFull=full&&visible.includes(full)?full:null;
|
const effectiveFull=full&&visible.includes(full)?full:null;
|
||||||
const rover=useRoverControl(vehicleID,enabled&&(visible.includes('rover')||visible.includes('telemetry')));
|
const rover=useRoverControl(vehicleID,enabled&&(visible.includes('rover')||visible.includes('telemetry')));
|
||||||
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen;
|
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice;
|
||||||
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
||||||
const active=sources.find(source=>source.key===focused);
|
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
|
||||||
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
|
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
|
||||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||||
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
|
||||||
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
|
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
|
||||||
return <>{headerToolsHost&&createPortal(<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
|
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
|
||||||
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>}<Button onClick={configure}><Icon name="sliders"/>Конфигуратор</Button><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
|
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
|
||||||
|
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
|
||||||
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
|
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
|
||||||
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
|
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
|
||||||
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
|
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
|
||||||
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
|
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
|
||||||
<DropZone id={source.key} className="observation-panel">
|
<DropZone id={source.key} className="observation-panel">
|
||||||
<DraggableItem id={source.key} className="observation-panel-drag">{({handle})=>
|
<DraggableItem id={source.key} className="observation-panel-drag">{({handle})=>
|
||||||
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface">
|
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
|
||||||
<header className="observation-panel__header">
|
<ObservationPanelHeader>
|
||||||
{handle}
|
{handle}
|
||||||
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
|
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
|
||||||
<div className="observation-actions">
|
<div className="observation-actions">
|
||||||
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
|
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
|
||||||
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
|
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
|
||||||
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setFocused(source.key);setLayersOpen(true);}}><Icon name="settings"/></IconButton>}
|
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>setSettingsDevice(source.deviceID!)}><Icon name="settings"/></IconButton>}
|
||||||
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
|
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
|
||||||
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
|
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</ObservationPanelHeader>
|
||||||
<ObservationMount element={media.current.get(source.key)!}/>
|
<ObservationMount element={media.current.get(source.key)!}/>
|
||||||
</GlassSurface>
|
</GlassSurface>
|
||||||
}</DraggableItem>
|
}</DraggableItem>
|
||||||
</DropZone>,mounts.current.get(source.key)!,source.key))}
|
</DropZone>,mounts.current.get(source.key)!,source.key))}
|
||||||
</DragDropRoot>
|
</DragDropRoot>
|
||||||
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
||||||
|
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить в конфигураторе</Button></div></div>,media.current.get(source.key)!,source.key))}
|
||||||
|
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
|
||||||
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
|
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
|
||||||
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
|
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible}/>,media.current.get('rover')!,'rover-session')}
|
||||||
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
|
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
|
||||||
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title={active?active.view.label:'Доступные слои'} size="md"><div className="observation-settings">
|
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
|
||||||
{!active&&<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>}
|
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>
|
||||||
{ids.filter(id=>!active||id===active.key).map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
|
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.label} · Источник не подключён`:source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
|
||||||
{active?.view.layers&&<Select label="Слой источника" value={layerFor(active.key,active.view)} options={active.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[active.key]:value}}))}/>}
|
|
||||||
<Button onClick={()=>{setLayout(emptyObservationLayout());setFull(null);}}>Восстановить расположение</Button>
|
<Button onClick={()=>{setLayout(emptyObservationLayout());setFull(null);}}>Восстановить расположение</Button>
|
||||||
</div></Window>
|
</div></Window>
|
||||||
</section>,portal)}</>;
|
</section>,portal)}</>;
|
||||||
|
|||||||
@@ -14,5 +14,5 @@ export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[
|
|||||||
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
|
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
|
||||||
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
|
||||||
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
|
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
|
||||||
return <SplitPane className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
|
return <SplitPane separatorAppearance="invisible" className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import {useState} from 'react';
|
||||||
|
import {Button,Window} from '@nodedc/ui-react';
|
||||||
|
import {SensorDetail} from '../../../../../../packages/sensor-ui/src/SensorDetail';
|
||||||
|
import {sensorContribution,type SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||||
|
import type {Sensor,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
|
||||||
|
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
|
||||||
|
|
||||||
|
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure}:{device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void}) {
|
||||||
|
const [error,setError]=useState('');
|
||||||
|
const Detail=sensorContribution(contributions,device)?.Detail??SensorDetail;
|
||||||
|
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
|
||||||
|
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
|
||||||
|
{!device.prepared&&<Button onClick={configure}>Подготовить устройство в конфигураторе</Button>}
|
||||||
|
{error&&<p role="alert">{error}</p>}
|
||||||
|
<Detail device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>
|
||||||
|
</Window>;
|
||||||
|
}
|
||||||
@@ -1,23 +1,34 @@
|
|||||||
import {useMemo,useRef,useState} from 'react';
|
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||||
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera} from '@nodedc/map-cesium-react';
|
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
|
||||||
import {Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
|
import {Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
|
||||||
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
|
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||||
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
||||||
import {defaultMapViewDocument} from '../../../core/map/mapView';
|
import {useTrackerTelemetry} from '../../../core/fleet/vps';
|
||||||
|
import {defaultMapViewDocument,encodeMapViewPut} from '../../../core/map/mapView';
|
||||||
|
import {useMapRecovery} from '../../../core/map/useMapRecovery';
|
||||||
import {mapPresentation} from '../../../components/map/mapPresentation';
|
import {mapPresentation} from '../../../components/map/mapPresentation';
|
||||||
|
|
||||||
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
|
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
|
||||||
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
|
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
|
||||||
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
|
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
|
||||||
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
|
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
|
||||||
const [camera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
|
const [camera,setCamera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
|
||||||
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:false});
|
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:true});
|
||||||
const ready=state.phase==='ready';
|
const telemetry=useTrackerTelemetry(vehicleID),centered=useRef(false);
|
||||||
const available=Object.values(state.providers).some(provider=>provider.phase==='ready');
|
const pins=telemetry.items.flatMap(item=>item.position?[{id:item.instance_id,label:`${item.name} · ${item.position_fresh&&!telemetry.unavailable?item.position.source.toUpperCase():new Date(item.position.measured_at*1000).toLocaleTimeString('ru-RU')}`,longitude:item.position.longitude,latitude:item.position.latitude,heading_degrees:item.position.course,speed_meters_per_second:0}]:[]);
|
||||||
|
const presentation=useMemo(()=>(encodeMapViewPut(defaultMapViewDocument()) as {view:{ghost_pins:MapGhostPinLayer}}).view.ghost_pins.presentation,[]);
|
||||||
|
const markers:MapGhostPinLayer={anchor:null,radius_meters:0,simulation_enabled:false,pins,presentation:{...presentation,stem_height_meters:20,head_size_px:12,label_mode:'attributes',label_max_length:80}};
|
||||||
|
function center(){const pin=pins[0];if(pin){setCamera({longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0});setGeneration(v=>v+1);}}
|
||||||
|
useEffect(()=>{if(pins.length&&!centered.current){centered.current=true;center();}},[pins.length]);
|
||||||
|
const latest=telemetry.items.find(item=>item.position);
|
||||||
|
const positionLabel=telemetry.unavailable?'Обновление координат недоступно':latest?.position?`${latest.position.latitude.toFixed(6)}, ${latest.position.longitude.toFixed(6)} · ${latest.position.source.toUpperCase()} · ${latest.position.satellites??'—'} спутников · ${new Date(latest.position.measured_at*1000).toLocaleTimeString('ru-RU')}`:'Ожидание координат трекера';
|
||||||
|
const available=state.phase==='ready'||Object.values(state.providers).some(provider=>provider.phase==='ready');
|
||||||
|
const unavailable=!available&&state.phase!=='loading';
|
||||||
|
useMapRecovery(unavailable,()=>setGeneration(v=>v+1));
|
||||||
return <div className="observation-source">
|
return <div className="observation-source">
|
||||||
<ObservationHeader targets={header} live={ready} label={ready?'Карта доступна':state.phase==='loading'?'Загрузка карты':state.phase==='degraded'?'Часть слоёв недоступна':'Карта недоступна'}><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
|
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
|
||||||
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
|
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
|
||||||
{!available&&state.phase!=='loading'&&<div className="observation-source__notice"><p>Не удалось загрузить картографические слои.</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
|
{unavailable&&<div className="observation-source__notice"><p>Картографические слои недоступны. Проверяем связь с сервером карты.</p><p>{positionLabel}</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
|
||||||
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
|
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
|
||||||
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
|
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import {useLayoutEffect,useRef,type ReactNode} from 'react';
|
||||||
|
|
||||||
|
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
|
||||||
|
export function ObservationPanelHeader({children}:{children:ReactNode}) {
|
||||||
|
const ref=useRef<HTMLElement>(null);
|
||||||
|
useLayoutEffect(()=>{
|
||||||
|
const header=ref.current!;
|
||||||
|
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
|
||||||
|
measure();const observer=new ResizeObserver(measure);observer.observe(header);
|
||||||
|
return()=>observer.disconnect();
|
||||||
|
},[]);
|
||||||
|
return <header ref={ref} className="observation-panel__header">{children}</header>;
|
||||||
|
}
|
||||||
@@ -9,6 +9,9 @@
|
|||||||
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
|
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
|
||||||
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
|
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
|
||||||
.observation-panel__surface > .observation-mount { flex:1; }
|
.observation-panel__surface > .observation-mount { flex:1; }
|
||||||
|
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
|
||||||
|
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
|
||||||
|
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
|
||||||
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
|
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
|
||||||
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
|
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
|
||||||
@@ -21,7 +24,7 @@
|
|||||||
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
|
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
|
||||||
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
|
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
|
||||||
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
|
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
|
||||||
.observation-source__notice { position:absolute; inset:30% var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
|
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
|
||||||
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
|
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
|
||||||
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
|
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
|
||||||
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
|
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
|
||||||
@@ -43,3 +46,5 @@
|
|||||||
.observation-panel__title { min-width:80px; }
|
.observation-panel__title { min-width:80px; }
|
||||||
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
|
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
|
||||||
import {
|
import {
|
||||||
GlassSurface,
|
GlassSurface,
|
||||||
StatusBadge,
|
StatusBadge,
|
||||||
@@ -77,9 +78,7 @@ export function ComputeModulesWorkspace() {
|
|||||||
const node = telemetry?.node ?? null;
|
const node = telemetry?.node ?? null;
|
||||||
const missionCoreRuntimes = telemetry?.runtimes.filter((runtime) => !runtime.external) ?? [];
|
const missionCoreRuntimes = telemetry?.runtimes.filter((runtime) => !runtime.external) ?? [];
|
||||||
const externalRuntimes = telemetry?.runtimes.filter((runtime) => runtime.external) ?? [];
|
const externalRuntimes = telemetry?.runtimes.filter((runtime) => runtime.external) ?? [];
|
||||||
const connected = Boolean(
|
const connectionStatus = workerConnectionStatus(telemetry);
|
||||||
telemetry?.connection.reachable && telemetry.connection.identity_matches && node,
|
|
||||||
);
|
|
||||||
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
|
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
|
||||||
const history = telemetry?.history ?? [];
|
const history = telemetry?.history ?? [];
|
||||||
const cpuPercent = node?.cpu.load_percent;
|
const cpuPercent = node?.cpu.load_percent;
|
||||||
@@ -105,14 +104,13 @@ export function ComputeModulesWorkspace() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="system-workspace__actions">
|
<div className="system-workspace__actions">
|
||||||
<StatusBadge tone={connected ? "success" : "danger"}>
|
<StatusBadge tone={connectionStatus.tone}>
|
||||||
{connected
|
{connectionStatus.label}
|
||||||
? agentTelemetry ? "Агент доступен" : "SSH-диагностика"
|
|
||||||
: "Нет свежих данных"}
|
|
||||||
</StatusBadge>
|
</StatusBadge>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
|
||||||
{error ? (
|
{error ? (
|
||||||
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
|
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
|
||||||
<StatusBadge tone="warning">{error}</StatusBadge>
|
<StatusBadge tone="warning">{error}</StatusBadge>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
|
||||||
import {
|
import {
|
||||||
GlassSurface,
|
GlassSurface,
|
||||||
StatusBadge,
|
StatusBadge,
|
||||||
@@ -31,6 +32,7 @@ export function NetworkWorkspace() {
|
|||||||
const connected = Boolean(
|
const connected = Boolean(
|
||||||
telemetry?.connection.reachable && telemetry.connection.identity_matches,
|
telemetry?.connection.reachable && telemetry.connection.identity_matches,
|
||||||
);
|
);
|
||||||
|
const connectionStatus = workerConnectionStatus(telemetry);
|
||||||
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
|
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
|
||||||
const runtimeOnline = telemetry?.runtimes.some(
|
const runtimeOnline = telemetry?.runtimes.some(
|
||||||
(runtime) => !runtime.external && runtime.state === "running",
|
(runtime) => !runtime.external && runtime.state === "running",
|
||||||
@@ -43,17 +45,18 @@ export function NetworkWorkspace() {
|
|||||||
<span className="section-eyebrow">СИСТЕМА / СЕТЬ</span>
|
<span className="section-eyebrow">СИСТЕМА / СЕТЬ</span>
|
||||||
<h2>{selectedContour?.display_name ?? "Контур не выбран"}</h2>
|
<h2>{selectedContour?.display_name ?? "Контур не выбран"}</h2>
|
||||||
<p>
|
<p>
|
||||||
Фактический локальный маршрут и сетевые счётчики выбранного вычислительного
|
Фактический маршрут и сетевые счётчики выбранного вычислительного
|
||||||
контура. Адрес, транспорт и установка агента находятся в настройках контура.
|
контура. Адрес, транспорт и установка агента находятся в настройках контура.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="system-workspace__actions">
|
<div className="system-workspace__actions">
|
||||||
<StatusBadge tone={connected ? "success" : "danger"}>
|
<StatusBadge tone={connectionStatus.tone}>
|
||||||
{connected ? "Маршрут доступен" : "Нет свежих данных"}
|
{connectionStatus.label}
|
||||||
</StatusBadge>
|
</StatusBadge>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
|
||||||
{error ? (
|
{error ? (
|
||||||
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
|
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
|
||||||
<StatusBadge tone="warning">{error}</StatusBadge>
|
<StatusBadge tone="warning">{error}</StatusBadge>
|
||||||
@@ -109,7 +112,7 @@ export function NetworkWorkspace() {
|
|||||||
<small>127.0.0.1:8000</small>
|
<small>127.0.0.1:8000</small>
|
||||||
</div>
|
</div>
|
||||||
<i aria-hidden="true" data-state="online" />
|
<i aria-hidden="true" data-state="online" />
|
||||||
<div data-state={agentTelemetry ? "online" : "offline"}>
|
<div data-state={connected ? "online" : "unknown"}>
|
||||||
<span>Telemetry plane</span>
|
<span>Telemetry plane</span>
|
||||||
<strong>{agentTelemetry ? "Mosquitto + Timescale" : "SSH diagnostic"}</strong>
|
<strong>{agentTelemetry ? "Mosquitto + Timescale" : "SSH diagnostic"}</strong>
|
||||||
<small>
|
<small>
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import {after,before,test} from 'node:test';
|
import {after,before,test} from 'node:test';
|
||||||
import {createServer} from 'vite';
|
import {createServer} from 'vite';
|
||||||
let server,layout,source,fanout;
|
let server,layout,source,fanout,catalog;
|
||||||
before(async()=>{
|
before(async()=>{
|
||||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||||
layout=await server.ssrLoadModule('/src/core/fleet/observationLayout.ts');
|
layout=await server.ssrLoadModule('/src/core/fleet/observationLayout.ts');
|
||||||
source=await server.ssrLoadModule('../../packages/sensor-ui/src/observation.ts');
|
source=await server.ssrLoadModule('../../packages/sensor-ui/src/observation.ts');
|
||||||
|
catalog=await server.ssrLoadModule('../../packages/sensor-ui/src/observationCatalog.ts');
|
||||||
({observationRerun:fanout}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/observationRerun.ts'));
|
({observationRerun:fanout}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/observationRerun.ts'));
|
||||||
});
|
});
|
||||||
after(async()=>{await server?.close();});
|
after(async()=>{await server?.close();});
|
||||||
@@ -41,3 +42,21 @@ test('two Rerun views share bytes, apply independent blueprints once and dispose
|
|||||||
assert.equal(sent[0].length,2);assert.deepEqual(started,[0,1]);host.dispose();assert.deepEqual(closed,[0,1]);
|
assert.equal(sent[0].length,2);assert.deepEqual(started,[0,1]);host.dispose();assert.deepEqual(closed,[0,1]);
|
||||||
}finally{globalThis.fetch=fetchBefore;}
|
}finally{globalThis.fetch=fetchBefore;}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test('known offline D455 remains selectable; connected capabilities override the catalog',()=>{
|
||||||
|
const offline={name:'RealSense D455',model:'RealSense D455',online:false,layers:[]};
|
||||||
|
assert.deepEqual(source.cameraObservationViews(offline)[0].layers.map(v=>v.value),['color','depth','infrared1','infrared2','points','motion']);
|
||||||
|
assert.deepEqual(source.cameraObservationViews({...offline,online:true,layers:['depth']})[0].layers.map(v=>v.value),['depth']);
|
||||||
|
assert.deepEqual(source.cameraObservationViews({...offline,model:'unknown'}),[]);
|
||||||
|
});
|
||||||
|
test('unbound catalog views have no device authority; connected instances replace templates without aliasing',()=>{
|
||||||
|
const plugin={kind:'k1',observation:{catalog:{label:'K1',views:[{id:'points',label:'Points'},{id:'camera',label:'Camera'}]}}};
|
||||||
|
const entries=catalog.unboundObservationViews([],[plugin]);
|
||||||
|
assert.equal(entries.length,2);assert.notEqual(entries[0].key,entries[1].key);
|
||||||
|
assert.equal(entries[0].deviceID,undefined);assert.equal(entries[0].device,undefined);
|
||||||
|
assert.deepEqual(catalog.unboundObservationViews([{id:'one',kind:'k1'}],[plugin]),[]);
|
||||||
|
assert.deepEqual(catalog.unboundObservationViews([],[plugin,plugin]),[]);
|
||||||
|
const persisted=layout.decodeObservationLayout({...layout.emptyObservationLayout(),catalogVisible:[entries[0].key,entries[0].key,null]});
|
||||||
|
assert.deepEqual(persisted.catalogVisible,[entries[0].key]);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {readFileSync} from 'node:fs';
|
||||||
|
import ts from 'typescript';
|
||||||
|
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/cellular.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||||
|
const {cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularModemLabel,cellularSlotView,cellularSimOptions,cellularSimCurrent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
test('SIM freshness rejects old, future and missing observations independently',()=>{
|
||||||
|
assert.equal(cellularFresh(undefined,100),false);
|
||||||
|
assert.equal(cellularFresh({measured_at:11},100),true);
|
||||||
|
assert.equal(cellularFresh({measured_at:10},100),false);
|
||||||
|
assert.equal(cellularFresh({measured_at:101},100),false);
|
||||||
|
});
|
||||||
|
test('missing country code cannot identify a carrier from MNC alone',()=>{
|
||||||
|
assert.equal(cellularNetworkLabel({mcc:null,mnc:2}),'Оператор не определён');
|
||||||
|
assert.equal(cellularNetworkLabel({mcc:250,mnc:2}),'МегаФон · 250-02');
|
||||||
|
assert.equal(cellularNetworkLabel({mcc:250,mnc:1}),'МТС · 250-01');
|
||||||
|
assert.equal(cellularNetworkLabel({mcc:310,mnc:260}),'Оператор не определён · код 310-260');
|
||||||
|
assert.equal(cellularNetworkLabel(undefined),'Оператор не определён');
|
||||||
|
});
|
||||||
|
test('unknown registration and modem states never imply data service',()=>{
|
||||||
|
assert.equal(cellularSimLabel(undefined),'Нет сведений');
|
||||||
|
assert.equal(cellularSimLabel(0),'SIM не обнаружена');
|
||||||
|
assert.equal(cellularSimLabel(6),'Ошибка PIN');
|
||||||
|
assert.equal(cellularSimLabel(7),'Нет сведений');
|
||||||
|
assert.equal(cellularModemLabel(4),'GPRS подключён');
|
||||||
|
assert.equal(cellularModemLabel(7),'Нет сведений о модеме');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registered second SIM is not presented as another internet connection',()=>{
|
||||||
|
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
|
||||||
|
assert.equal(cellularSlotView(t,'1',100).role,'Используется для интернета');
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).role,'Не выбрана для интернета');
|
||||||
|
assert.equal(cellularNetworkLabel(cellularSlotView(t,'2',100).network),'Оператор не определён · код 250-00');
|
||||||
|
t.cellular.status.active_sim=2;
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).internet,true);
|
||||||
|
assert.equal(cellularSlotView(t,'1',100).internet,false);
|
||||||
|
t.online=false;
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).role,'Последнее полученное состояние');
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).internet,false);
|
||||||
|
});
|
||||||
|
test('removed SIM does not retain a current operator or internet badge',()=>{
|
||||||
|
const t={online:true,cellular:{status:{active_sim:2,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'2':{mcc:250,mnc:1,measured_at:98}}}};
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).role,'SIM не обнаружена');
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).network,undefined);
|
||||||
|
assert.equal(cellularSlotView(t,'2',100).internet,false);
|
||||||
|
assert.equal(cellularSlotView(t,'1',200).role,'Последнее полученное состояние');
|
||||||
|
assert.equal(cellularSlotView(undefined,'1',100).internet,false);
|
||||||
|
assert.equal(cellularNetworkLabel({mcc:250,mnc:99}),'Билайн · 250-99');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('target selector lists installed SIMs and resolves labels anew after swaps',()=>{
|
||||||
|
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:1,measured_at:99}}}};
|
||||||
|
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'}]);
|
||||||
|
t.cellular.status.sim_states['2']=1;
|
||||||
|
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'},{value:'2',label:'SIM 2 (МТС)'}]);
|
||||||
|
[t.cellular.networks['1'],t.cellular.networks['2']]=[t.cellular.networks['2'],t.cellular.networks['1']];
|
||||||
|
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МТС)'},{value:'2',label:'SIM 2 (МегаФон)'}]);
|
||||||
|
t.cellular.networks['2'].mnc=99;
|
||||||
|
assert.equal(cellularSimOptions(t,100)[1].label,'SIM 2 (Билайн)');
|
||||||
|
t.cellular.status.sim_states['1']=0;
|
||||||
|
assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн)'}]);
|
||||||
|
assert.deepEqual(cellularSimOptions(t,200),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
|
||||||
|
assert.equal(cellularSimCurrent(t,2,200),false);
|
||||||
|
assert.equal(cellularSimCurrent(t,2,100),true);
|
||||||
|
t.online=false;assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
|
||||||
|
assert.equal(cellularSimCurrent(t,2,100),false);
|
||||||
|
assert.deepEqual(cellularSimOptions(undefined,100),[]);
|
||||||
|
});
|
||||||
|
test('target selector never carries an old operator into stale, searching or unknown evidence',()=>{
|
||||||
|
const t={online:true,cellular:{status:{sim_states:{'1':2,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
|
||||||
|
assert.deepEqual(cellularSimOptions(t,100).map(o=>o.label),['SIM 1 (оператор не определён)','SIM 2 (оператор не определён)']);
|
||||||
|
t.cellular.status.sim_states['1']=1;t.cellular.networks['1'].measured_at=1;
|
||||||
|
assert.equal(cellularSimOptions(t,100)[0].label,'SIM 1 (оператор не определён)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('qualified card home operator follows current binding even when serving MNC is unavailable',()=>{
|
||||||
|
const t={online:true,cellular:{status:{measured_at:100,sim_states:{'1':1,'2':1}},networks:{}},sim_identity:{slots:{'1':{binding_current:true,known_card:{home_network:'25002'}},'2':{binding_current:true,known_card:{home_network:'25001'}}}}};
|
||||||
|
assert.deepEqual(cellularSimOptions(t,101).map(x=>x.label),['SIM 1 (МегаФон)','SIM 2 (МТС)']);
|
||||||
|
t.sim_identity.slots['2'].binding_current=false;
|
||||||
|
assert.equal(cellularSimOptions(t,101)[1].label,'SIM 2 (оператор не определён)');
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {readFileSync} from 'node:fs';
|
||||||
|
import test from 'node:test';
|
||||||
|
import ts from 'typescript';
|
||||||
|
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/commandRuntime.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||||
|
const {mergeCommands,commandPending,commandTracked,commandStatus,commandTone,commandDate,commandDuration,commandReceipt,commandEntryStatus}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
test('runtime retains loaded history and merges a changing operation by immutable id',()=>{
|
||||||
|
const a={id:'a',sequence:10,state:'waiting'},b={id:'b',sequence:9,state:'device_confirmed'};
|
||||||
|
const entries=mergeCommands([a,b],[{...a,state:'dispatched'},{id:'c',sequence:11,state:'queued'}]);
|
||||||
|
assert.deepEqual(entries.map(x=>[x.id,x.state]),[['c','queued'],['a','dispatched'],['b','device_confirmed']]);
|
||||||
|
assert.equal(a.state,'waiting');
|
||||||
|
});
|
||||||
|
test('a delayed polling response cannot roll a completed command back to pending',()=>{
|
||||||
|
const current={id:'a',sequence:10,state:'device_confirmed',updated_at:20};
|
||||||
|
assert.equal(mergeCommands([current],[{...current,state:'dispatched',updated_at:10}])[0].state,'device_confirmed');
|
||||||
|
});
|
||||||
|
test('runtime makes expiry, no confirmation and receipt distinct; none claim actuator execution',()=>{
|
||||||
|
for(const state of ['waiting','submitting','queued','dispatched'])assert.equal(commandPending(state),true);
|
||||||
|
for(const state of ['expired','cancelled','unconfirmed','uncertain','device_confirmed'])assert.equal(commandPending(state),false);
|
||||||
|
assert.equal(commandTone('device_confirmed'),'success');
|
||||||
|
assert.equal(commandTone('unconfirmed'),'warning');
|
||||||
|
assert.notEqual(commandStatus('expired'),commandStatus('unconfirmed'));
|
||||||
|
assert.doesNotMatch(commandStatus('device_confirmed'),/исполнено|выполнено/i);
|
||||||
|
assert.equal(commandDuration(undefined),'—');assert.equal(commandDuration(0.01234),'0.012 с');assert.equal(commandDate(undefined),'—');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unresolved results remain tracked after timeout without blocking the command queue',()=>{
|
||||||
|
const unknown={id:'a',sequence:1,state:'uncertain',reconcile_pending:true,updated_at:10};
|
||||||
|
assert.equal(commandPending(unknown.state),false);
|
||||||
|
assert.equal(commandTracked(unknown),true);
|
||||||
|
const final={...unknown,state:'device_confirmed',reconcile_pending:false,updated_at:20};
|
||||||
|
assert.equal(commandTracked(final),false);
|
||||||
|
assert.deepEqual(mergeCommands([unknown],[final]),[final]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tracker ACK is visible without pretending that execution finished',()=>{
|
||||||
|
const ack={state:'dispatched',device_code:6,device_accepted_at:10};
|
||||||
|
assert.equal(commandPending(ack.state),true);
|
||||||
|
assert.equal(commandEntryStatus(ack),'Принято B2, выполняется');
|
||||||
|
assert.equal(commandReceipt(ack),'B2 принял команду; требуется время на выполнение');
|
||||||
|
assert.equal(commandReceipt({device_code:0,kind:'restart'}),'B2 принял команду перезапуска');
|
||||||
|
assert.equal(commandEntryStatus({...ack,state:'device_confirmed'}),'Подтверждено B2');
|
||||||
|
assert.equal(commandReceipt({device_code:5}),'B2 сообщил об ошибке выполнения');
|
||||||
|
assert.equal(commandReceipt({device_code:7}),'Очередь команд B2 заполнена');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('durable jobs show recovery independently of a single attempt and stop request',()=>{
|
||||||
|
const entry={state:'queued',durable:true,device_accepted_at:10};
|
||||||
|
assert.equal(commandEntryStatus({...entry,runtime_phase:'retry-wait'}),'Ожидает следующей попытки');
|
||||||
|
assert.equal(commandEntryStatus({...entry,runtime_phase:'reconciling'}),'Уточнение результата у VPS');
|
||||||
|
assert.equal(commandEntryStatus({...entry,stop_requested:true}),'Остановка повторов');
|
||||||
|
assert.equal(commandPending('accepted'),false);
|
||||||
|
assert.equal(commandPending('stopped'),false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {before,after,test} from 'node:test';
|
||||||
|
import {createServer} from 'vite';
|
||||||
|
|
||||||
|
let server,readContourSnapshot,contourSummary,workerAvailable;
|
||||||
|
before(async()=>{
|
||||||
|
server=await createServer({server:{middlewareMode:true,hmr:false},optimizeDeps:{noDiscovery:true,include:[]},appType:'custom'});
|
||||||
|
({readContourSnapshot,contourSummary,workerAvailable}=await server.ssrLoadModule('/src/core/system/contourHealth.ts'));
|
||||||
|
});
|
||||||
|
after(async()=>{await server?.close();});
|
||||||
|
|
||||||
|
const core={ok:true,service:'mission-core-control-plane',version:'test',plugin_runtimes:{ready:1,total:1}};
|
||||||
|
const contour={contour_id:'test-compute',display_name:'Test compute',expected_node_id:'test-node'};
|
||||||
|
const worker={schema_version:'missioncore.worker-telemetry/v1',profile:{},connection:{reachable:true,identity_matches:true},node:{node_id:'test-node'},runtimes:[],pipeline:{},network:{},history:[]};
|
||||||
|
const vehicle={id:'test-vehicle',name:'Test rover',enrollment:'paired',connectivity:'offline'};
|
||||||
|
function installFetch(t,{failed=[],data={}}={}){
|
||||||
|
const calls=[];
|
||||||
|
t.mock.method(globalThis,'fetch',async url=>{
|
||||||
|
calls.push(url);
|
||||||
|
if(failed.includes(url))throw new Error('unavailable');
|
||||||
|
const defaults={
|
||||||
|
'/api/health':core,
|
||||||
|
'/api/v1/system/contours':{schema_version:'missioncore.compute-contour-catalog/v1',contours:[contour]},
|
||||||
|
'/api/v1/system/contours/test-compute/telemetry?history=90':worker,
|
||||||
|
'/api/v1/fleet':{items:[vehicle]},
|
||||||
|
};
|
||||||
|
assert.ok(url in defaults,`Unexpected probe: ${url}`);
|
||||||
|
return new Response(JSON.stringify(url in data?data[url]:defaults[url]));
|
||||||
|
});
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
test('actual registries determine node count and offline boards prevent all-online status',async t=>{
|
||||||
|
const calls=installFetch(t);
|
||||||
|
const snapshot=await readContourSnapshot(new AbortController().signal);
|
||||||
|
assert.equal(snapshot.workers[0].contour.display_name,'Test compute');
|
||||||
|
assert.deepEqual(contourSummary(snapshot),{tone:'warning',label:'Часть узлов не в сети',online:2,total:3});
|
||||||
|
assert.equal(calls.length,4);
|
||||||
|
});
|
||||||
|
test('failed checks discard previous online data and distinguish unknown from empty',async t=>{
|
||||||
|
installFetch(t,{failed:['/api/v1/fleet','/api/v1/system/contours/test-compute/telemetry?history=90']});
|
||||||
|
const snapshot=await readContourSnapshot(new AbortController().signal);
|
||||||
|
assert.equal(snapshot.vehicles,null);
|
||||||
|
assert.equal(snapshot.workers[0].telemetry,null);
|
||||||
|
assert.equal(snapshot.errors.length,2);
|
||||||
|
assert.deepEqual(contourSummary(snapshot),{tone:'warning',label:'Проверка неполная',online:1,total:null});
|
||||||
|
});
|
||||||
|
test('invalid health never becomes reachable; identity mismatch and stale worker are not online',async t=>{
|
||||||
|
installFetch(t,{data:{'/api/health':{ok:true}}});
|
||||||
|
const snapshot=await readContourSnapshot(new AbortController().signal);
|
||||||
|
assert.equal(snapshot.core,null);
|
||||||
|
assert.equal(workerAvailable({...worker,connection:{reachable:true,identity_matches:false}}),false);
|
||||||
|
assert.equal(workerAvailable({...worker,connection:{reachable:false,identity_matches:true}}),false);
|
||||||
|
assert.equal(workerAvailable({...worker,node:null}),false);
|
||||||
|
});
|
||||||
|
test('an empty configured contour contains only the operator, with no fabricated worker',async t=>{
|
||||||
|
installFetch(t,{data:{'/api/v1/system/contours':{schema_version:'missioncore.compute-contour-catalog/v1',contours:[]},'/api/v1/fleet':{items:[]}}});
|
||||||
|
assert.deepEqual(contourSummary(await readContourSnapshot(new AbortController().signal)),{tone:'success',label:'Все узлы в сети',online:1,total:1});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('receiver failure leaves worker unknown instead of declaring it offline',async t=>{
|
||||||
|
installFetch(t,{data:{'/api/v1/system/contours/test-compute/telemetry?history=90':{...worker,node:null,connection:{reachable:false,identity_matches:false,error_code:'telemetry-receiver-unavailable'}}}});
|
||||||
|
const snapshot=await readContourSnapshot(new AbortController().signal);
|
||||||
|
assert.equal(contourSummary(snapshot).label,'Состояние части узлов не подтверждено');
|
||||||
|
const {workerConnectionStatus}=await server.ssrLoadModule('/src/core/system/workerConnectionStatus.ts');
|
||||||
|
const status=workerConnectionStatus(snapshot.workers[0].telemetry);
|
||||||
|
assert.equal(status.state,'unknown');
|
||||||
|
assert.equal(status.label,'Не в сети');
|
||||||
|
assert.equal(workerConnectionStatus({...worker,node:null,connection:{reachable:false,error_code:'telemetry-agent-stale'}}).label,'Не в сети');
|
||||||
|
assert.equal(workerConnectionStatus(worker).state,'online');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a responding Core with recording capacity pressure remains reachable',async t=>{
|
||||||
|
installFetch(t,{data:{'/api/health':{...core,ok:false,components:{recording_cache:{status:'capacity-pressure'}}}}});
|
||||||
|
const snapshot=await readContourSnapshot(new AbortController().signal);
|
||||||
|
assert.equal(contourSummary(snapshot).online,2);
|
||||||
|
assert.equal(contourSummary(snapshot).label,'Mission Core работает с ограничениями');
|
||||||
|
});
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {readFileSync} from 'node:fs';
|
||||||
|
import ts from 'typescript';
|
||||||
|
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/equipment.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||||
|
const {emptyEquipmentPolicy,policyError,equipmentRequest,selectInternetSim,networkOperationMessage,equipmentPolicyEqual}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const fields=[{key:'25',min:0,max:65535,label:'Интервал'}];
|
||||||
|
test('SIM choice creates explicit activation without copying another APN or legacy preset',()=>{
|
||||||
|
for(const connectivity of [
|
||||||
|
{strategy:'operator',sim_slot:2,preset_id:'ru-megafon-public-v1',apn1:'',apn2:''},
|
||||||
|
{strategy:'sim',sim_slot:1,apn:'test.apn',apn1:'',apn2:''},
|
||||||
|
{strategy:'preserve',apn1:'',apn2:''},
|
||||||
|
]){
|
||||||
|
const policy={...emptyEquipmentPolicy(),parameters:{'25':60},connectivity};
|
||||||
|
const next=selectInternetSim(policy,2);
|
||||||
|
assert.deepEqual(next.connectivity,{strategy:'sim',sim_slot:2,activate:true,automatic:true,apn:null,apn1:'',apn2:'',preset_id:null});
|
||||||
|
assert.equal(next.parameters,policy.parameters);assert.equal(policy.connectivity,connectivity);
|
||||||
|
}
|
||||||
|
const current=selectInternetSim(emptyEquipmentPolicy(),2);current.connectivity.apn='custom';
|
||||||
|
assert.equal(selectInternetSim(current,2).connectivity.apn,'custom');
|
||||||
|
assert.equal(selectInternetSim(current,1).connectivity.apn,null);
|
||||||
|
});
|
||||||
|
test('blank policy preserves settings; explicit zero remains present',()=>{
|
||||||
|
const value=emptyEquipmentPolicy();assert.equal(policyError(value,fields),'');assert.deepEqual(value.parameters,{});
|
||||||
|
value.parameters['25']=0;assert.equal(policyError(value,fields),'');
|
||||||
|
value.parameters['25']=0.5;assert.notEqual(policyError(value,fields),'');
|
||||||
|
});
|
||||||
|
test('endpoint and APN must be concrete before saving',()=>{
|
||||||
|
const value=emptyEquipmentPolicy();value.endpoint={host:'',port:0,slot:1};assert.notEqual(policyError(value,fields),'');
|
||||||
|
value.endpoint={host:'track.example.test',port:9023,slot:2};assert.equal(policyError(value,fields),'');
|
||||||
|
value.connectivity.strategy='manual';assert.notEqual(policyError(value,fields),'');
|
||||||
|
value.connectivity.apn1='iot.example';assert.equal(policyError(value,fields),'');
|
||||||
|
});
|
||||||
|
test('equipment request has independent route, no Node identity, and preserves server errors',async()=>{
|
||||||
|
const original=globalThis.fetch;const calls=[];
|
||||||
|
try{
|
||||||
|
globalThis.fetch=async(url,options)=>{calls.push({url,options});return new Response(JSON.stringify({detail:'Конфликт'}),{status:409});};
|
||||||
|
await assert.rejects(equipmentRequest('/instances','POST',{candidate_id:'synthetic'}),/Конфликт/);
|
||||||
|
assert.equal(calls[0].url,'/api/v1/fleet/equipment/instances');assert.equal(calls[0].options.cache,'no-store');
|
||||||
|
}finally{globalThis.fetch=original;}
|
||||||
|
});
|
||||||
|
test('operator connectivity requires a selected preset and a valid SIM slot',()=>{
|
||||||
|
const value=emptyEquipmentPolicy();value.connectivity={strategy:'operator',apn1:'',apn2:'',preset_id:null,sim_slot:2};
|
||||||
|
assert.notEqual(policyError(value,fields),'');
|
||||||
|
value.connectivity.preset_id='ru-mts-public-v1';assert.equal(policyError(value,fields),'');
|
||||||
|
value.connectivity.sim_slot=3;assert.notEqual(policyError(value,fields),'');
|
||||||
|
});
|
||||||
|
test('network status distinguishes observed endpoint from verified write and whole profile',async()=>{
|
||||||
|
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
assert.match(networkOperationMessage({id:'x',state:'verified',scope:'server1',verified_at:1,server1:{host:'example.test',port:9922}}),/Сервер 1 подтверждён/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',state:'uncertain',scope:'server1'}),/не подтверждён/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',state:'observed',scope:'server1',server1:{host:'example.test',port:9922}}),/прочитан/);
|
||||||
|
});
|
||||||
|
test('command receipt never claims a relay transition or a settings write',async()=>{
|
||||||
|
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
for(const state of ['submitting','queued','dispatched','device_confirmed','device_rejected','expired','unconfirmed','uncertain']){
|
||||||
|
const message=networkOperationMessage({id:'x',scope:'command',state});
|
||||||
|
assert.doesNotMatch(message,/записи|адреса сервера|реле включено|реле выключено/i);
|
||||||
|
}
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'command',state:'device_confirmed'}),/подтвердил приём/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'command',state:'unconfirmed'}),/не подтверждено/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'command',state:'uncertain'}),/повторения не будет/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('full configuration distinguishes progress, readback and unchanged profile',async()=>{
|
||||||
|
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
for(const state of ['queued','dispatched','uncertain','unconfirmed','expired','rejected'])assert.doesNotMatch(networkOperationMessage({id:'x',scope:'configuration',state,stage:'write'}),/записаны.*подтверждены/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'observed',record_count:207}),/207 параметров/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified'}),/повторным чтением/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified',unchanged:true}),/уже совпадают/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('restart status requires fresh reconnection and never claims a hardware reset from ACK',async()=>{
|
||||||
|
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const op={id:'x',scope:'command',command:{kind:'restart'}};
|
||||||
|
assert.match(networkOperationMessage({...op,state:'dispatched'}),/Ожидаем свежие данные/);
|
||||||
|
assert.match(networkOperationMessage({...op,state:'reconnected'}),/свежие данные по новому соединению/);
|
||||||
|
assert.doesNotMatch(networkOperationMessage({...op,state:'device_confirmed'}),/перезапущен|снова в сети|свежие данные/);
|
||||||
|
assert.match(networkOperationMessage({...op,state:'unconfirmed'}),/повторения не будет/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deadline stops progress without releasing the write interlock or inventing success',async()=>{
|
||||||
|
const {networkOperationProgress}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const op={id:'x',scope:'configuration',state:'dispatched',stage:'preflight',created_at:100,expires_at:280};
|
||||||
|
assert.deepEqual(networkOperationProgress(op,200),{pending:true,overdue:false,waiting:true,remaining:80});
|
||||||
|
assert.deepEqual(networkOperationProgress(op,280),{pending:true,overdue:true,waiting:false,remaining:0});
|
||||||
|
assert.equal(networkOperationProgress({...op,state:'unconfirmed'},300).pending,false);
|
||||||
|
assert.equal(networkOperationProgress({...op,expires_at:undefined},340).overdue,true);
|
||||||
|
assert.equal(networkOperationProgress(undefined,300).waiting,false);
|
||||||
|
});
|
||||||
|
test('only a terminal preflight timeout proves that configuration writing never began',async()=>{
|
||||||
|
const {networkOperationMessage,configurationWriteNotStarted}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const op={id:'x',scope:'configuration',state:'unconfirmed',stage:'preflight',read_only:false};
|
||||||
|
assert.equal(configurationWriteNotStarted(op),true);
|
||||||
|
assert.match(networkOperationMessage(op),/Запись настроек не началась/);
|
||||||
|
for(const change of [{state:'dispatched'},{state:'uncertain'},{stage:'write'},{stage:'verify'},{read_only:true},{scope:'command'}]){
|
||||||
|
assert.equal(configurationWriteNotStarted({...op,...change}),false);
|
||||||
|
assert.doesNotMatch(networkOperationMessage({...op,...change}),/Запись настроек не началась/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('SIM result requires modem confirmation and exposes restart wait',()=>{
|
||||||
|
const op={id:'x',scope:'sim-selection',sim_slot:2};
|
||||||
|
assert.match(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/ждём интернет через SIM 2/);
|
||||||
|
assert.match(networkOperationMessage({...op,state:'uncertain',stage:'restart'}),/не подтверждён/);
|
||||||
|
assert.match(networkOperationMessage({...op,state:'sim_selected',active_sim:2}),/SIM 2 подключена/);
|
||||||
|
assert.match(networkOperationMessage({...op,state:'unconfirmed',stage:'preflight'}),/Запись настроек не началась/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saved settings are clean despite server key ordering and default expansion',()=>{
|
||||||
|
const draft=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15,'50':7}},2);
|
||||||
|
const server={schema_version:1,endpoint:null,connectivity:{strategy:'sim',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:2,activate:true,automatic:true},parameters:{'50':7,'25':15}};
|
||||||
|
assert.equal(equipmentPolicyEqual(draft,server),true);
|
||||||
|
assert.equal(equipmentPolicyEqual(emptyEquipmentPolicy(),{...emptyEquipmentPolicy(),connectivity:{strategy:'preserve',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:1,activate:false}}),true);
|
||||||
|
assert.equal(equipmentPolicyEqual(draft,selectInternetSim(server,1)),false);
|
||||||
|
assert.equal(equipmentPolicyEqual(draft,{...server,parameters:{'50':7,'25':16}}),false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('explicit SIM intent survives unchanged settings but unrelated edits do not reselect',async()=>{
|
||||||
|
const {simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const saved=selectInternetSim(emptyEquipmentPolicy(),1);
|
||||||
|
assert.equal(simSelectionIntent(saved,saved,false),false);
|
||||||
|
assert.equal(simSelectionIntent({...saved,parameters:{'25':16}},saved,false),false);
|
||||||
|
assert.equal(simSelectionIntent(saved,saved,true),true);
|
||||||
|
assert.equal(simSelectionIntent(selectInternetSim(saved,2),saved,false),true);
|
||||||
|
assert.equal(simSelectionIntent({...saved,connectivity:{...saved.connectivity,apn:'new.apn'}},saved,false),true);
|
||||||
|
assert.equal(simSelectionIntent(emptyEquipmentPolicy(),saved,true),false);
|
||||||
|
});
|
||||||
|
|
||||||
|
for(const withoutApn of [false,true])test(`both-SIM permission (empty APN: ${withoutApn}) remains an explicit intent`,async()=>{
|
||||||
|
const {allowBothInternetSims,simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||||
|
const before=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15}},2);
|
||||||
|
const both=allowBothInternetSims(before,withoutApn);
|
||||||
|
assert.deepEqual(both.connectivity,{strategy:withoutApn?'native':'both',apn1:'',apn2:''});
|
||||||
|
assert.equal(both.parameters,before.parameters);
|
||||||
|
assert.equal(simSelectionIntent(both,before,false),true);
|
||||||
|
assert.equal(simSelectionIntent(both,both,false),false);
|
||||||
|
assert.equal(simSelectionIntent({...both,parameters:{'25':16}},both,false),false);
|
||||||
|
assert.equal(simSelectionIntent(both,both,true),true);
|
||||||
|
assert.equal(policyError(both,fields),'');
|
||||||
|
const op={id:'x',scope:'sim-selection',sim_policy:'both',state:'sim_selected',active_sim:2};
|
||||||
|
assert.match(networkOperationMessage(op),/Обе SIM разрешены/);
|
||||||
|
assert.match(networkOperationMessage(op),/SIM 2/);
|
||||||
|
assert.doesNotMatch(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/undefined/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('durable SIM restart shows reconnect phase instead of generic command wait',()=>{
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',sim_policy:'both',state:'dispatched',durable:true,runtime_phase:'executing',stage:'restart'}),/свежую связь после перезапуска/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('automatic internet is an explicit profile choice and waiting identity is not success',()=>{
|
||||||
|
const policy=selectInternetSim(emptyEquipmentPolicy(),1);
|
||||||
|
assert.equal(policy.connectivity.automatic,true);
|
||||||
|
assert.equal(equipmentPolicyEqual(policy,{...policy,connectivity:{...policy.connectivity,automatic:false}}),false);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'queued',durable:true,runtime_phase:'waiting-identity'}),/Ожидаем подтверждение карты/);
|
||||||
|
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'rejected',reason:'sim_card_changed'}),/Карта.*изменилась/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import {build} from 'esbuild';
|
||||||
|
const result=await build({entryPoints:[new URL('../src/core/roverScene/sceneDocument.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||||
|
const {defaultScene,environmentFields,changeField,fieldDisabled,parseScene,createMaterial,assignMaterial}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||||
|
test('all donor camera and environment fields remain exposed, frame styling excluded',t=>{
|
||||||
|
const source=new URL('../../../../NODEDC_ENGINE_INFRA/nodedc-source/src/driveinspector/nodes/ThreeDAsset.definition.ts',import.meta.url);
|
||||||
|
if(!fs.existsSync(source)){t.skip('Donor checkout not installed; pinned catalog remains in repo');return;}
|
||||||
|
const donor=fs.readFileSync(source,'utf8');
|
||||||
|
const keys=[...donor.matchAll(/key: '(postFx\.[^']+|cameraZoomStrength|cameraAutoRotate|cameraResetTs)'/g)].map(m=>m[1]);
|
||||||
|
assert.equal(keys.length,109);
|
||||||
|
for(const key of keys)assert.ok(environmentFields.some(f=>f.key===key),key);
|
||||||
|
assert.ok(!environmentFields.some(f=>f.key==='nodeName'));
|
||||||
|
});
|
||||||
|
test('documents are independent, scene edits preserve material texture references',()=>{
|
||||||
|
const a=defaultScene(),b=defaultScene();a.materials['rover/body'].color='#123456';assert.notEqual(a.materials['rover/body'].color,b.materials['rover/body'].color);
|
||||||
|
const edited=changeField(a,'postFx.lighting.exposure',1.5);assert.equal(edited.postFx.lighting.exposure,1.5);assert.equal(a.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure);assert.equal(edited.materials,a.materials);
|
||||||
|
});
|
||||||
|
test('numeric enums, bounds, invalid color and unknown paths are validated',()=>{
|
||||||
|
const a=defaultScene();assert.equal(changeField(a,'postFx.rendering.toneMapping','3').postFx.rendering.toneMapping,3);
|
||||||
|
assert.equal(changeField(a,'postFx.grid.step',0).postFx.grid.step,.01);
|
||||||
|
for(const [key,value] of [['__proto__.x',1],['postFx.grid.step',NaN],['postFx.grid.colorMain','red'],['postFx.rendering.fog','invalid']])assert.equal(changeField(a,key,value),a);
|
||||||
|
});
|
||||||
|
test('fog interval, atlas/skybox exclusion and field availability stay coherent',()=>{
|
||||||
|
let a=changeField(defaultScene(),'postFx.rendering.fogRange',[18,3]);assert.deepEqual(a.postFx.rendering.fogRange,[3,18]);assert.equal(a.postFx.rendering.fogStart,3);assert.equal(a.postFx.rendering.fogEnd,18);
|
||||||
|
a=changeField(a,'postFx.skybox.enabled',true);assert.equal(a.postFx.envAtlas.enabled,false);
|
||||||
|
assert.equal(fieldDisabled(a,environmentFields.find(f=>f.key==='postFx.envAtlas.enabled')),true);
|
||||||
|
});
|
||||||
|
test('scene JSON round trips materials, texture data and environment without authority',()=>{
|
||||||
|
const a=defaultScene();a.materials['rover/box'].textures.diffuse={name:'test.png',data:'data:image/png;base64,YWJj'};a.materials['rover/box'].roughness=.28;
|
||||||
|
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(a))),a);
|
||||||
|
assert.throws(()=>parseScene({schema:'other'}));
|
||||||
|
assert.throws(()=>parseScene({...a,model:'wrong'}));
|
||||||
|
assert.equal('armed' in a,false);
|
||||||
|
});
|
||||||
|
test('import rejects texture URLs and normalizes out-of-range PBR values',()=>{
|
||||||
|
const a=defaultScene();a.materials['rover/box'].roughness=20;assert.equal(parseScene(a).materials['rover/box'].roughness,1);
|
||||||
|
a.materials['rover/box'].textures.normal={name:'remote',data:'https://unknown/texture'};assert.throws(()=>parseScene(a));
|
||||||
|
});
|
||||||
|
test('editing excludes drive bindings and key controls without changing arm authority',()=>{
|
||||||
|
const view=fs.readFileSync(new URL('../src/components/rover/RoverView.tsx',import.meta.url),'utf8');
|
||||||
|
assert.match(view,/if\(!c.ready\|\|!active\|\|open\|\|editing/);assert.match(view,/c.ready&&!editing/);assert.match(view,/c.pauseInput\(\);setHeld/);
|
||||||
|
const editor=fs.readFileSync(new URL('../src/components/rover/editor/RoverScene.tsx',import.meta.url),'utf8');assert.doesNotMatch(editor,/\.arm\(|setDemand|\/api\/v1\/fleet/);
|
||||||
|
});
|
||||||
|
test('export manifest retains complete geometry and all editable material groups',()=>{
|
||||||
|
const manifest=JSON.parse(fs.readFileSync(new URL('../public/rover-scene/dcd006-v020.json',import.meta.url),'utf8'));
|
||||||
|
assert.equal(manifest.source_object_count,1426);assert.equal(manifest.render_mesh_count,9);assert.equal(manifest.source_saved,false);assert.match(manifest.uv,/cube/);
|
||||||
|
assert.deepEqual(Object.keys(manifest.materials).sort(),Object.keys(defaultScene().materials).map(k=>k.replace('rover/','')).sort());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('named custom materials and assignments survive JSON and reject unknown groups',()=>{
|
||||||
|
let a=createMaterial(defaultScene(),'custom/example');
|
||||||
|
a.materials['custom/example'].name='Мой металл';a=assignMaterial(a,'rover/body','custom/example');
|
||||||
|
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(a))),a);
|
||||||
|
assert.equal(assignMaterial(a,'unknown','custom/example'),a);
|
||||||
|
assert.equal(assignMaterial(a,'rover/body','missing'),a);
|
||||||
|
assert.equal(createMaterial(a,'__proto__'),a);
|
||||||
|
const legacy=defaultScene();delete legacy.assignments;assert.deepEqual(parseScene(legacy).assignments,{});
|
||||||
|
});
|
||||||
|
test('default environment is the original NodeDC preset without neutral overrides',()=>{
|
||||||
|
const a=defaultScene();assert.equal(a.postFx.chromaticAberration.enabled,true);
|
||||||
|
assert.equal(a.postFx.rendering.backgroundColor,'#111113');
|
||||||
|
assert.equal(a.postFx.lighting.ambientIntensity,0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {build} from 'esbuild';
|
||||||
|
const bundle=await build({stdin:{contents:"export * from './src/core/roverScene/sceneDocument'; export * from './src/core/roverScene/sceneMigration';",resolveDir:process.cwd()},bundle:true,write:false,platform:'node',format:'esm'});
|
||||||
|
const {defaultScene,loadStoredScene,parseScene}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
|
||||||
|
// Historical settings released by the first editor, independent of migration code.
|
||||||
|
function savedFirstEditor(){
|
||||||
|
const d=defaultScene();delete d.environmentVersion;
|
||||||
|
d.postFx={...d.postFx,
|
||||||
|
lighting:{exposure:1.1,skyBoxIntensity:1,ambientIntensity:.22},
|
||||||
|
envAtlas:{...d.postFx.envAtlas,reflectionIntensity:1,brightness:1.2},
|
||||||
|
rendering:{...d.postFx.rendering,backgroundColor:'#202227',fog:'none',toneMapping:4},
|
||||||
|
grid:{...d.postFx.grid,colorMain:'#747982',colorX:'#93969c',colorZ:'#93969c',alphaMain:.25,alphaX:.35,alphaZ:.35,fadeStart:2,fadeEnd:5,step:.5,diameter:12},
|
||||||
|
chromaticAberration:{...d.postFx.chromaticAberration,enabled:false},vignette:{...d.postFx.vignette,enabled:false},grading:{...d.postFx.grading,enabled:false},bloom:{...d.postFx.bloom,enabled:false},
|
||||||
|
directionalLight:{...d.postFx.directionalLight,intensity:1.8,azimuth:135,elevation:45},shadowCatcher:{...d.postFx.shadowCatcher,size:4,lightIntensity:.5,shadowIntensity:.25}
|
||||||
|
};
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
test('previous saved neutral preset migrates to NodeDC while retaining material work',()=>{
|
||||||
|
const raw=savedFirstEditor();raw.materials['rover/body'].name='Мой корпус';raw.materials['rover/body'].roughness=.73;raw.materials['rover/body'].textures.diffuse={name:'my.png',data:'data:image/png;base64,YWJj'};
|
||||||
|
raw.assignments['rover/box']='rover/body';raw.cameraZoomStrength=.1;
|
||||||
|
const original=structuredClone(raw),r=loadStoredScene(raw);
|
||||||
|
assert.equal(r.restoredEnvironment,true);assert.equal(r.updated,true);
|
||||||
|
assert.deepEqual(r.document.postFx,defaultScene().postFx);
|
||||||
|
assert.deepEqual(r.document.materials,raw.materials);assert.deepEqual(r.document.assignments,raw.assignments);assert.equal(r.document.cameraZoomStrength,.1);
|
||||||
|
assert.deepEqual(raw,original,'backup must retain the exact input');
|
||||||
|
assert.equal(loadStoredScene(r.document).updated,false,'migration runs once');
|
||||||
|
});
|
||||||
|
test('a single custom environment edit prevents a destructive reset',()=>{
|
||||||
|
const raw=savedFirstEditor();raw.postFx.lighting.exposure=1.3;
|
||||||
|
const r=loadStoredScene(raw);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx);
|
||||||
|
});
|
||||||
|
test('a deliberate new gray scene and explicit JSON imports retain their appearance',()=>{
|
||||||
|
const raw=savedFirstEditor();raw.environmentVersion=2;
|
||||||
|
assert.equal(loadStoredScene(raw).restoredEnvironment,false);
|
||||||
|
delete raw.environmentVersion;
|
||||||
|
const imported=parseScene(raw);assert.equal(imported.environmentVersion,2);assert.deepEqual(imported.postFx,raw.postFx);
|
||||||
|
assert.equal(loadStoredScene(imported).restoredEnvironment,false);
|
||||||
|
});
|
||||||
|
test('already restored legacy NodeDC scene is only versioned, not altered',()=>{
|
||||||
|
const raw=defaultScene();delete raw.environmentVersion;const r=loadStoredScene(raw);
|
||||||
|
assert.equal(r.updated,true);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx);
|
||||||
|
});
|
||||||
@@ -0,0 +1,447 @@
|
|||||||
|
# NODE.DC Mission VPS Host 0.1.41
|
||||||
|
|
||||||
|
Version 0.1.41 completes the extracted transport observation batch before a
|
||||||
|
socket closure cancels its sender. Closing a stream can no longer abandon a
|
||||||
|
pending observation commit. All monitoring commands now wait for device input
|
||||||
|
on their selected socket no older than five seconds, as configuration commands
|
||||||
|
already did. Empty send queues alone are insufficient evidence of a live path.
|
||||||
|
The pending intent and original attempt deadlines are preserved; device input
|
||||||
|
wakes the sender without an extra probing command. This mitigates stale-stream
|
||||||
|
dispatch but does not guarantee delivery on a cellular network.
|
||||||
|
|
||||||
|
Version 0.1.40 persists command transport observations separately from B2
|
||||||
|
execution: prepared, written, TCP acknowledged, or unconfirmed with a reason.
|
||||||
|
The Linux send-queue watchdog records when the complete command prefix was
|
||||||
|
acknowledged; it never promotes the command to executed. Socket closure, expiry
|
||||||
|
and process restart preserve uncertainty. Observations are available on command
|
||||||
|
and operation APIs and attempt history, including late observations after a
|
||||||
|
device reply. No payload, password, modem address or SIM identity is logged.
|
||||||
|
Existing deadlines, retry policy and Core-to-VPS polling direction are unchanged.
|
||||||
|
|
||||||
|
|
||||||
|
Version 0.1.39 adds engineering-only `probe-diagnostic-mode` (INTERNAL
|
||||||
|
SERVER_COM `01 00`) for model 231 / firmware 0.01. A separately armed,
|
||||||
|
authenticated observation ID is mandatory; exactly one command may consume
|
||||||
|
each observation. Dispatch is restricted to an existing admitted connection,
|
||||||
|
expires within three seconds, and is never replayed across reconnect/restart.
|
||||||
|
Closing the observation prevents a queued dispatch. There is no raw-command
|
||||||
|
input and this action is absent from the operator catalogue/durable operations.
|
||||||
|
The 180-second lease bounds capture/dispatch, **not** the device's mode lifetime.
|
||||||
|
A token receipt does not establish a mode change or fresh SIM identity.
|
||||||
|
Physical qualification and termination semantics are recorded separately.
|
||||||
|
|
||||||
|
Version 0.1.35 publishes imported state with a single same-filesystem rename.
|
||||||
|
A failed staging copy cannot expose a partial host identity, and restoration
|
||||||
|
does not need a second full-size journal copy.
|
||||||
|
|
||||||
|
Version 0.1.34 adds portable, quiesced state export and empty-host import.
|
||||||
|
The source stays fenced across service/OS restarts. TLS identity, ownership,
|
||||||
|
registered devices and the entire durable journal move together. Import uses
|
||||||
|
the exact matching installer and preserves the configured endpoint.
|
||||||
|
|
||||||
|
Version 0.1.33 makes service-code directory traversal independent of the root
|
||||||
|
installer caller's umask. Private credentials and state retain their restricted
|
||||||
|
permissions. It otherwise preserves the 0.1.32 durable maintenance runtime.
|
||||||
|
|
||||||
|
Version 0.1.31 accepts matching binary command token receipts through either
|
||||||
|
admitted monitoring connection of the same B2, including a reconnected stream.
|
||||||
|
ACK (code 6) remains distinct from a final result. Text replies, revoked devices,
|
||||||
|
unknown sessions and other trackers cannot confirm a binary command.
|
||||||
|
|
||||||
|
Version 0.1.30 resumes only independent readback of a committed `configure-all`
|
||||||
|
image after a VPS process restart or a new B2 connection, preserving its ID, target, original
|
||||||
|
deadline and stage pacing. No image, SIM switch, restart or output action replays.
|
||||||
|
Fresh readback can establish the target, the predecessor or an unknown image;
|
||||||
|
an unavailable device still ends with an uncertain outcome. This is recovery of
|
||||||
|
verification, not proof that the B2 modem can recover autonomously.
|
||||||
|
|
||||||
|
Version 0.1.29 additionally defers configuration commands on a silent monitoring
|
||||||
|
stream until the B2 sends fresh input (within five monotonic seconds). A drained
|
||||||
|
TCP queue alone does not prove a live cellular path. The original operation
|
||||||
|
deadline is retained; dispatched stages never replay. Position/output command
|
||||||
|
policy is unchanged. This is a transport admission guard, not a cellular latency
|
||||||
|
guarantee.
|
||||||
|
|
||||||
|
Version 0.1.28 answers the observed empty HTTP opcode-7 request with current Unix
|
||||||
|
UTC seconds from the owner's VPS, using the reference-qualified u32be envelope.
|
||||||
|
Only an admitted model-231/0.01 identity with an active matching modem peer can
|
||||||
|
receive it. It does not change settings, complete an operation or extend its
|
||||||
|
deadline. The host clock must be correct. Device dialogue/repeated configuration
|
||||||
|
acceptance is recorded separately; a clock response alone is not that acceptance.
|
||||||
|
|
||||||
|
Version 0.1.27 admits a new command only when the selected Linux socket has
|
||||||
|
no unacknowledged kernel bytes or pending asyncio bytes. Among eligible streams
|
||||||
|
the most recently active one wins. Blocked streams cannot steal a command from
|
||||||
|
a drained stream; deadlines remain unchanged and dispatched commands never
|
||||||
|
replay. Transport readiness does not confirm execution.
|
||||||
|
|
||||||
|
Version 0.1.26 adds immutable request deadlines for idempotent Core delivery,
|
||||||
|
a durable bounded wait for undispatched position requests, and event-driven idle
|
||||||
|
senders. Terminal operation history is indexed out of the packet/dispatch path.
|
||||||
|
Commands already dispatched to a tracker are never automatically replayed.
|
||||||
|
|
||||||
|
The engineering `qualify_faults.py` harness checks crash recovery, lost HTTP
|
||||||
|
responses, immutable expiry and no replay using the installed package with
|
||||||
|
temporary SQLite and loopback sockets. It does not use production state or
|
||||||
|
physical hardware. See [fault qualification](../../docs/arnavi_b2/FAULT_RECOVERY_20260927.md).
|
||||||
|
|
||||||
|
Version 0.1.25 bounds command bytes in the Linux TCP queue to the earlier of
|
||||||
|
the operation deadline and 30 seconds after dispatch. HTTP settings replies
|
||||||
|
have a 12-second transport bound, capped by the operation deadline. Monotonic
|
||||||
|
watchdogs account for both asyncio and kernel buffers; abortive close prevents
|
||||||
|
queued data from lingering after disconnect. TCP acknowledgement only releases
|
||||||
|
the transport watchdog, never confirms device execution. Interrupted or expired
|
||||||
|
actions are never replayed. Already received commands cannot be cancelled.
|
||||||
|
|
||||||
|
Version 0.1.24 adds exclusive SIM selection on qualified B2 model 231 / firmware
|
||||||
|
0.01: fresh configuration preflight, one image write, exact readback, one restart,
|
||||||
|
and fresh type-1 DS2 evidence of GPRS on the requested SIM over a new connection.
|
||||||
|
The operation has a 360-second bound. Field 72 bits 10/20 prohibit data on the
|
||||||
|
other SIM; this is not automatic failover. APNs and access credentials are kept
|
||||||
|
unless explicitly edited. Interrupted writes/restarts are never replayed.
|
||||||
|
Full cellular-only physical qualification is recorded separately in the ledger.
|
||||||
|
|
||||||
|
|
||||||
|
Version 0.1.23 retains the independently registered numeric-ID reply, but removes
|
||||||
|
the experimental empty settings response: physical 0.1.22 evidence showed an
|
||||||
|
ID/settings loop, not completion. A settings image is still sent only during
|
||||||
|
an explicit, bounded write. Startup qualification remains open.
|
||||||
|
|
||||||
|
Version 0.1.22 qualifies the continuous startup exchange: reply with the
|
||||||
|
independently enrolled numeric device ID, then an empty settings response when
|
||||||
|
no explicit image write is pending. Numeric IDs are immutable per IMEI and
|
||||||
|
never inferred from its digits. Unknown IDs and unadmitted peers fail closed.
|
||||||
|
An explicit pending write retains its single-image dispatch/readback contract.
|
||||||
|
Physical qualification of the combined exchange is required before publication.
|
||||||
|
|
||||||
|
Version 0.1.21 admits the captured ten-byte command-1 response in a one-shot
|
||||||
|
engineering lease. Its four-byte payload equals the independently known device
|
||||||
|
ID. Product behavior is unchanged pending a fresh, unchanged device upload.
|
||||||
|
|
||||||
|
Version 0.1.20 admits one exact empty reply to the observed empty command-1
|
||||||
|
request in the engineering observation lease. This follows the physical 2→1
|
||||||
|
transition after an empty command-2 reply. No firmware image can be supplied,
|
||||||
|
and normal product parsing remains closed until the exchange is qualified.
|
||||||
|
|
||||||
|
Version 0.1.19 admits one exact, zero-payload command-2 response only in
|
||||||
|
the bounded engineering observation lease for no-image-response qualification.
|
||||||
|
No product-channel behavior changes before physical verification.
|
||||||
|
|
||||||
|
Version 0.1.18 adds an engineering-only binary encoding of the documented
|
||||||
|
read-only settings upload request (0109), to qualify post-restart behavior.
|
||||||
|
It does not change the qualified product settings transport or retry writes.
|
||||||
|
|
||||||
|
Version 0.1.17 adds the qualified-model restart request (B2 manual §10, binary
|
||||||
|
0107). Dispatch expires after three seconds; the request is never replayed.
|
||||||
|
A token ACK is recorded separately. Only fresh type-1 telemetry measured after
|
||||||
|
dispatch on a newly opened connection records return, with a 180-second deadline.
|
||||||
|
This is observed network return, not proof of a hardware power cycle. Old sessions,
|
||||||
|
archive packets and replies alone cannot complete the operation.
|
||||||
|
|
||||||
|
Version 0.1.16 spaces full-configuration stages and successive operations by
|
||||||
|
15 seconds after each HTTP image exchange. The bench sometimes ignored a new
|
||||||
|
SERV request shortly after an upload despite TCP acknowledgment. This pacing
|
||||||
|
does not affect position/output commands or replay a settings write.
|
||||||
|
|
||||||
|
Version 0.1.15 adds complete configuration reads and profile writes on the
|
||||||
|
qualified B2 model 231 / firmware 0.01 HTTP settings channel. It reads the
|
||||||
|
current image before writing, requires an exact predecessor, preserves recovery
|
||||||
|
channels, sends the image once and verifies by an independent full readback.
|
||||||
|
Command-5 ACK is the captured seven-byte response with payload 01. Restart or
|
||||||
|
timeout after dispatch does not silently replay a write. No manufacturer API
|
||||||
|
is contacted by this runtime.
|
||||||
|
|
||||||
|
Version 0.1.14 chooses the active TCP session with the most recent incoming data
|
||||||
|
for command dispatch. A half-open predecessor left by a device configuration
|
||||||
|
reload cannot take a new command while a fresher session exists. It also allows
|
||||||
|
a bounded engineering upload-ACK qualification using the observed reply-envelope
|
||||||
|
structure, matching the complete validated upload body. Up to 64 observation
|
||||||
|
leases are retained (four 16-KiB captures each); raw evidence remains private.
|
||||||
|
|
||||||
|
Version 0.1.13 qualifies the observed configuration reply framing with the
|
||||||
|
shared B2 CRC/TLV codec. An engineering observation lease can serve a validated
|
||||||
|
configuration once to a byte-identical admitted B2 settings request. Explicit
|
||||||
|
close disarms the lease while retaining evidence. This is a real write path:
|
||||||
|
prepare an exact baseline and rollback image and verify a fresh device upload;
|
||||||
|
dispatch alone never establishes successful application. No vendor HTTP calls.
|
||||||
|
|
||||||
|
Version 0.1.12 additionally permits the documented `SERV*1.8` configuration
|
||||||
|
download request for protocol qualification. It can apply a configuration from
|
||||||
|
the device's configured endpoint; that endpoint must be owned and its payload
|
||||||
|
qualified before use. The current observation lease serves only a captured
|
||||||
|
identity answer, never a configuration. No firmware/erase/reset commands exist.
|
||||||
|
|
||||||
|
Version 0.1.11 adds an engineering-only, allowlisted B2 settings upload request
|
||||||
|
(`SERV*1.9`), preserving active-session expiry and no replay. It also permits one
|
||||||
|
captured seven-byte configuration identity answer to the exact corresponding
|
||||||
|
21-byte request, under an authenticated 180-second observation lease. The device
|
||||||
|
must be admitted; expiry, byte mismatch, duplicate HTTP framing and repeat
|
||||||
|
dispatch fail closed. This is bounded protocol qualification, not a general
|
||||||
|
proxy or full configuration support. The service never contacts a vendor.
|
||||||
|
|
||||||
|
Version 0.1.10 adds explicit `set-output` using the B2 manual section 10 FC
|
||||||
|
command `password*SERV*8.PIN.STATE`. PIN4..6 only, strict boolean `enabled`,
|
||||||
|
model 231 / firmware 0.01, instance password required. This sets a persistent
|
||||||
|
output state; it is not a timed pulse or a physical-contact confirmation.
|
||||||
|
It uses the existing active-session, three-second dispatch expiry and no-replay
|
||||||
|
contract. Unknown fields and arbitrary commands are rejected. Bench operators
|
||||||
|
must verify manual output mode and deliberately restore the observed baseline.
|
||||||
|
|
||||||
|
Version 0.1.9 adds the documented FC text encoding for the same bounded
|
||||||
|
`pulse-output` operation: PIN4..6, 1..5 seconds, model 231 / firmware 0.01.
|
||||||
|
An explicit `encoding: text` requires the instance's six-digit password; the
|
||||||
|
generated command remains private. No arbitrary text is accepted. This format
|
||||||
|
has no token-correlated confirmation: the receipt stays unconfirmed even when
|
||||||
|
unrelated token or text replies arrive. Dispatch still requires a current
|
||||||
|
session and expires after three seconds; commands never replay after restart.
|
||||||
|
A text PIN5 pulse produced an operator- and subsequently camera-observed LED
|
||||||
|
on/off transition. Earlier binary PIN4/PIN5 pulses had no visible effect.
|
||||||
|
A token ACK alone is not relay feedback; other outputs require qualification.
|
||||||
|
|
||||||
|
Headless receiver owned by Mission Core, independently of any rover's onboard PC.
|
||||||
|
Supported installation profile: **Ubuntu Server 24.04 amd64, Python 3.12,
|
||||||
|
OpenSSL 3, systemd**. Other OS/architectures fail preflight. No pip, Docker, GUI,
|
||||||
|
Node.js, compiler or vendor cloud is required. Minimal images missing OS
|
||||||
|
prerequisites are rejected with the missing capability; no blind system repair.
|
||||||
|
|
||||||
|
## Reproduce
|
||||||
|
|
||||||
|
From this repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
.venv/bin/python scripts/build_vps_host.py --output /tmp/ndc-mission-vps.tar
|
||||||
|
```
|
||||||
|
|
||||||
|
The builder produces both a `.tar` engineering archive and a single `.pyz`
|
||||||
|
operator installer. Mission Core serves an explicitly published, checksum-verified
|
||||||
|
`.pyz` in Equipment → root plus → VPS Host ARNavi. The same window contains the
|
||||||
|
supported OS, installation instructions and pairing-key field. The installer
|
||||||
|
carries no tracker identities, SIM data, address, keys or private evidence.
|
||||||
|
|
||||||
|
Copy the downloaded file to the VPS and run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --host trackers.example.org
|
||||||
|
```
|
||||||
|
|
||||||
|
Use the actual downloaded filename. Omitting `--host` prompts for the public
|
||||||
|
address. The wrapper runs the same preflight/plan/apply engine, with an exact
|
||||||
|
plan digest; it does not require a separate installer GUI. The engineering tar
|
||||||
|
retains the explicit plan/apply interface:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 ndc-mission-vps/install.py plan --host trackers.example.org
|
||||||
|
python3 ndc-mission-vps/install.py apply --host trackers.example.org --expect PLAN_SHA256
|
||||||
|
```
|
||||||
|
|
||||||
|
Run apply as root. The exact current plan hash is required. DNS/IP is an install
|
||||||
|
parameter, never source code. Use stable DNS so a VPS migration does not require
|
||||||
|
rewriting thousands of trackers. Default ports: TCP 9922 (B2 INTERNAL), TLS 19443
|
||||||
|
(Mission Core). Cloud firewall must allow these exact ports. The installer preserves existing services, including DeviceCore on 443/9921.
|
||||||
|
For the detected legacy NODE.DC `nodedc_b2_vps` nftables policy it adds two
|
||||||
|
comment-owned allow rules and a persistent include, checks predecessor hashes,
|
||||||
|
and records a bounded rollback. It never flushes rules. Unknown firewall
|
||||||
|
policies remain external and require public endpoint acceptance.
|
||||||
|
Existing listener/foreign installation conflicts stop first install.
|
||||||
|
|
||||||
|
Installation paths:
|
||||||
|
|
||||||
|
- `/opt/nodedc-mission-vps/current`: immutable release selected by content digest.
|
||||||
|
- **`/opt/nodedc-mission-vps/connect.key`**: fixed root-level pairing file,
|
||||||
|
symlink to protected state; read as root.
|
||||||
|
- `/var/lib/ndc-mission-vps`: host identity, TLS key, owner and durable journal,
|
||||||
|
mode 0700, files 0600, owned by dedicated system user `ndc-mission-vps`.
|
||||||
|
- `/etc/systemd/system/ndc-mission-vps.service`: versioned managed system unit.
|
||||||
|
|
||||||
|
Open an apparatus → Equipment → top plus → VPS Host ARNavi. Paste the key, choose a
|
||||||
|
name and served apparatuses. It expires after 24 hours and is consumed once.
|
||||||
|
The same VPS appears under every assigned rover. To attach an existing VPS to
|
||||||
|
another rover, choose it in the connection dialog, or change the host's apparatus
|
||||||
|
list in settings. One host retains one identity and one Mission Core owner.
|
||||||
|
|
||||||
|
An unused expired key can be renewed with the shipped CLI:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /opt/nodedc-mission-vps/current
|
||||||
|
sudo -u ndc-mission-vps /usr/bin/python3 -m ndc_vps invitation
|
||||||
|
```
|
||||||
|
|
||||||
|
Paired hosts cannot silently regenerate/reassign ownership. Back up the whole
|
||||||
|
private state directory and Mission Core fleet state. A new host has a new key.
|
||||||
|
An update retains the same identity and queue. Applying the current release is
|
||||||
|
a health-checking no-op. Failed updates restore the previous release and unit.
|
||||||
|
Explicit rollback preserves private state and the journal:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 ndc-mission-vps/install.py rollback --host trackers.example.org --expect INSTALLED_ARTIFACT_DIGEST
|
||||||
|
```
|
||||||
|
|
||||||
|
For the first release rollback disables the new service; it does not delete
|
||||||
|
identities, evidence or any unrelated service. Schema v1 updates are additive;
|
||||||
|
a future incompatible migration must supply its own reversible migration.
|
||||||
|
|
||||||
|
## Clean product reinstallation
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --fresh
|
||||||
|
```
|
||||||
|
|
||||||
|
This explicitly replaces this product's installation and identity. First the
|
||||||
|
installer stops its own unit and creates a private, hash-recorded backup under
|
||||||
|
`/var/backups/ndc-mission-vps/`. It preserves original application/state trees,
|
||||||
|
then installs empty product state and creates a new pairing key. A failed fresh
|
||||||
|
installation restores the backup and health-checks the old service. Foreign
|
||||||
|
services and unrelated files are preserved. This is not an OS reimage.
|
||||||
|
|
||||||
|
In the Core admission form select the previous record under «После переустановки»
|
||||||
|
and paste the new key. Replacement is explicit: duplicate live host records at
|
||||||
|
the same endpoint are refused. The former record and telemetry journal remain
|
||||||
|
in private history; only the newly paired identity is synchronized.
|
||||||
|
|
||||||
|
To restore a selected backup with the same installer:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --restore /var/backups/ndc-mission-vps/BACKUP_ID
|
||||||
|
```
|
||||||
|
|
||||||
|
After a successful new pairing, restoring the server alone does not restore the
|
||||||
|
Core's host registration. Restore a matching private Core fleet backup as part
|
||||||
|
of disaster recovery; do not substitute identities or disclose tokens manually.
|
||||||
|
|
||||||
|
## Publish qualified downloads
|
||||||
|
|
||||||
|
The operator runtime keeps installers under its private fleet root, outside Git.
|
||||||
|
Publishing a release only changes the download; it never installs on a board or
|
||||||
|
VPS. Run the publisher with the exact SHA from the accepted build receipt:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
.venv/bin/python scripts/publish_fleet_installer.py \
|
||||||
|
--fleet-root /path/to/operator/fleet --kind vps-arnavi \
|
||||||
|
--file /path/to/qualified-vps.pyz --version 0.1.3 --sha256 ACCEPTED_SHA256
|
||||||
|
```
|
||||||
|
|
||||||
|
For the onboard computer use `--kind node` and the version/SHA of the already
|
||||||
|
qualified owner installer. Copy the finished installer back from the build host
|
||||||
|
before publishing it. A source-build bundle is not an owner installer. Publishing
|
||||||
|
the Node archive does not update the board. Catalog and download endpoints verify
|
||||||
|
size and SHA; a missing or changed archive is unavailable instead of silently
|
||||||
|
falling back to an older build.
|
||||||
|
|
||||||
|
## Tracker admission and delivery
|
||||||
|
|
||||||
|
Register/read a B2 over USB in Mission Core, select the registered VPS in its
|
||||||
|
connection settings, save, then apply over USB. Slot 2 is initially proposed to
|
||||||
|
preserve an existing slot 1. Profiles contain common settings, not IMEI/ICCID,
|
||||||
|
SIM phone number or assignment. Firmware-qualified writer performs backup,
|
||||||
|
identity/config preconditions, acknowledgement and independent readback.
|
||||||
|
|
||||||
|
Core synchronizes an allowlist of registered IMEIs assigned to that host's
|
||||||
|
apparatuses and configured endpoint. Unknown devices receive no telemetry ACK.
|
||||||
|
**IMEI is a claimed identity, not cryptographic tracker authentication**: legacy
|
||||||
|
INTERNAL is plaintext. For untrusted deployments use an operator private APN or
|
||||||
|
network protection; this release does not claim end-to-end tracker encryption.
|
||||||
|
|
||||||
|
VPS ACKs a B2 package only after a SQLite FULL commit. Core pulls a bounded batch,
|
||||||
|
stores raw evidence, derives valid coordinates and advances its cursor in the
|
||||||
|
same transaction, then acknowledges the VPS queue. Replays are idempotent;
|
||||||
|
package sequence reuse cannot replace content. Header-time and package ACKs
|
||||||
|
follow the published INTERNAL framing. No arbitrary tracker command API exists.
|
||||||
|
|
||||||
|
The authenticated VPS API also qualifies the allowlisted, read-only `GETP`
|
||||||
|
command over an existing tracker TCP session. Commands have durable IDs and
|
||||||
|
bounded expiry; a dispatched command is never automatically replayed after a
|
||||||
|
restart. A text response means `reply_received`, not «settings applied».
|
||||||
|
Version 0.1.6 adds the bounded `configure-server1` operation for B2 model 231 /
|
||||||
|
firmware 0.01. Fresh GETP must match the expected primary endpoint and show this
|
||||||
|
VPS as the secondary server. Only documented SETP #1 host/port is changed; a
|
||||||
|
separate GETP must verify the endpoint and preservation of every other group.
|
||||||
|
Operations bind to one TCP session, reject stale/duplicate responses, expire
|
||||||
|
after 120 seconds and never replay writes after restart. Reversal is a separate
|
||||||
|
preconditioned operation. FC has no correlation token: timestamp/session checks
|
||||||
|
bound freshness but do not create cryptographic command attribution.
|
||||||
|
Device clock skew is bounded to 10 seconds behind / 5 seconds ahead of VPS time;
|
||||||
|
successive operation stages require strictly increasing device timestamps.
|
||||||
|
After a dispatched SETP the host waits at least 15 seconds before its separate
|
||||||
|
GETP. Only this read may bind to a new TCP session after tracker reconnection;
|
||||||
|
SET P is never resent. Verification also runs when SETP's acknowledgement is lost.
|
||||||
|
The 0.1.4 experiment stopped before writing because its timestamp comparison
|
||||||
|
incorrectly required synchronized clocks; the measured B2 was about 4 s behind.
|
||||||
|
|
||||||
|
Full profiles, APN/active-channel migration, other server slots and disabling the
|
||||||
|
vendor configurator remain unqualified. The authenticated API is private: raw
|
||||||
|
GETP replies contain credentials and must never be proxied into the browser.
|
||||||
|
See [network configuration audit](../../docs/arnavi_b2/NETWORK_CONFIGURATION.md).
|
||||||
|
|
||||||
|
The VPS queue has a 512 MiB budget and preserves a 256 MiB disk reserve. When
|
||||||
|
full/unwritable it withholds ACK, never drops unconsumed packages. Receipts retain
|
||||||
|
retransmission deduplication for seven days. Core must remain available often
|
||||||
|
enough to drain the queue. Capacity for thousands of simultaneously active
|
||||||
|
trackers has **not** been load-qualified; the first profile caps 256 connections
|
||||||
|
and service memory at 192 MiB. Scale/retention qualification is a separate gate.
|
||||||
|
|
||||||
|
Core API uses TLS 1.3 with certificate fingerprint verified **before** sending a
|
||||||
|
pairing secret or bearer token. Invitation is obtained through the owner's SSH
|
||||||
|
channel. DNS resolves only to public IPv4. Redirects/ambient HTTP proxies are
|
||||||
|
not followed. Node's private-network pairing contract is unchanged.
|
||||||
|
|
||||||
|
Coordinates are derived from valid packet tags. Missing/invalid/zero coordinates
|
||||||
|
are not invented. Device measurement time and reception time remain separate;
|
||||||
|
an older replay cannot move the map backwards in time. UI shows freshness and
|
||||||
|
last contact, independently of the onboard computer.
|
||||||
|
|
||||||
|
## Acceptance boundary
|
||||||
|
|
||||||
|
`tests/test_vps_host.py` covers framing, partial TCP reads, checksum rejection,
|
||||||
|
one-time enrollment, retry identity, admission, durable delivery, deduplication,
|
||||||
|
Core cursor transaction, stale data and shared rover reassignment. Hardware and
|
||||||
|
operator VPS acceptance are recorded separately in a private deployment ledger.
|
||||||
|
A successful install on the existing Ubuntu VPS is not clean-image qualification.
|
||||||
|
|
||||||
|
## Portable transfer to a clean VPS
|
||||||
|
|
||||||
|
Use the same qualified installer file on both hosts. Upgrade the source to it
|
||||||
|
first. Then on the source:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --export-state /root/mission-vps-state.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
This stops this service and persistently fences it before taking the snapshot.
|
||||||
|
The source remains stopped, including after reboot. Export prints the archive's
|
||||||
|
SHA-256. The archive contains credentials and the SQLite journal: keep it private
|
||||||
|
and transfer it through the owner's SSH channel together with the installer.
|
||||||
|
No executable, system unit, account ID or firewall configuration crosses hosts.
|
||||||
|
A failure after fencing leaves the source stopped and preserves its state.
|
||||||
|
|
||||||
|
On the clean supported Ubuntu VPS:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256
|
||||||
|
```
|
||||||
|
|
||||||
|
Import checks the exact archive SHA, complete file manifest, matching installer
|
||||||
|
release, TLS key/certificate identity and SQLite integrity before installation.
|
||||||
|
Existing product paths are refused. It creates the system account, code and unit
|
||||||
|
through the same installer and verifies service health. TLS identity and Core
|
||||||
|
pairing survive; commands retain IDs, attempts, deadlines and stop markers.
|
||||||
|
The normal runtime reconciles interrupted attempts; a snapshot is not proof of
|
||||||
|
tracker execution. No old live TCP session is restored.
|
||||||
|
|
||||||
|
Keep the existing DNS name and ports, then direct that DNS name to the target
|
||||||
|
after its health and external reachability checks. For an endpoint configured
|
||||||
|
as a literal IP, this operation alone does not migrate Core or tracker addresses;
|
||||||
|
a transferable IP or a separately verified endpoint change is required. Provider
|
||||||
|
firewalls and DNS changes require their owner's controls/API and are not inferred
|
||||||
|
from guest installation success. The receiving installation needs 2.25 GiB of
|
||||||
|
free staging space; portable state is capped at 2 GiB.
|
||||||
|
|
||||||
|
To abandon migration, **stop the target first**, then explicitly resume the source:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 ndc-mission-vps.pyz --resume-source
|
||||||
|
```
|
||||||
|
|
||||||
|
The source cannot observe the target across an outage. The installer therefore
|
||||||
|
never resumes it automatically. Retain the private archive and exact installer
|
||||||
|
for recovery. Do not run both identities simultaneously. A stale archive also
|
||||||
|
cannot contain commands or confirmations recorded after its snapshot.
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""Bounded migration of the observed NODE.DC B2 nftables policy; no flush."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
CONFIG = Path("/etc/nftables.conf")
|
||||||
|
FRAGMENT = Path("/etc/nftables.d/ndc-mission-vps.nft")
|
||||||
|
BACKUP = Path("/opt/nodedc-mission-vps/firewall-before.json")
|
||||||
|
INCLUDE = 'include "/etc/nftables.d/ndc-mission-vps.nft"'
|
||||||
|
MARKER = "ndc-mission-vps-v1"
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args, **kwargs):
|
||||||
|
return subprocess.run(args, check=True, capture_output=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def plan():
|
||||||
|
if not CONFIG.exists() or "table inet nodedc_b2_vps" not in CONFIG.read_text():
|
||||||
|
# A clean host can use its own provider firewall. Unknown local policies
|
||||||
|
# are not rewritten; public endpoint acceptance remains mandatory.
|
||||||
|
return {"mode": "external", "config_sha256": None}
|
||||||
|
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
||||||
|
chain = next(x["chain"] for x in live["nftables"] if "chain" in x)
|
||||||
|
if chain.get("policy") != "drop" or chain.get("hook") != "input":
|
||||||
|
raise ValueError("unsupported legacy firewall policy")
|
||||||
|
if FRAGMENT.exists() and MARKER not in FRAGMENT.read_text():
|
||||||
|
raise ValueError("foreign firewall fragment conflict")
|
||||||
|
return {
|
||||||
|
"mode": "nodedc-b2-v1",
|
||||||
|
"config_sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def rules(api, tracker):
|
||||||
|
return (
|
||||||
|
f"add rule inet nodedc_b2_vps input tcp dport {api} ct state new "
|
||||||
|
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-api"\n'
|
||||||
|
f"add rule inet nodedc_b2_vps input tcp dport {tracker} ct state new "
|
||||||
|
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-tracker"\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def removal():
|
||||||
|
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
||||||
|
commands = []
|
||||||
|
for item in live["nftables"]:
|
||||||
|
rule = item.get("rule", {})
|
||||||
|
if rule.get("comment") in (MARKER + "-api", MARKER + "-tracker"):
|
||||||
|
commands.append(f"delete rule inet nodedc_b2_vps input handle {int(rule['handle'])}\n")
|
||||||
|
return "".join(commands)
|
||||||
|
|
||||||
|
|
||||||
|
def apply(proposal, api, tracker, atomic):
|
||||||
|
if proposal["mode"] != "nodedc-b2-v1":
|
||||||
|
return False
|
||||||
|
if plan() != proposal:
|
||||||
|
raise ValueError("firewall changed after plan")
|
||||||
|
content = rules(api, tracker)
|
||||||
|
if INCLUDE in CONFIG.read_text():
|
||||||
|
if not FRAGMENT.exists() or FRAGMENT.read_text() != content:
|
||||||
|
raise ValueError("managed firewall drift")
|
||||||
|
# Reconcile only our named live rules if nftables was reloaded.
|
||||||
|
run("nft", "-f", "-", input=(removal() + content).encode())
|
||||||
|
return False
|
||||||
|
original = CONFIG.read_text()
|
||||||
|
desired = original.rstrip() + "\n\n" + INCLUDE + "\n"
|
||||||
|
backup = {
|
||||||
|
"before": original,
|
||||||
|
"after_sha256": hashlib.sha256(desired.encode()).hexdigest(),
|
||||||
|
"fragment_sha256": hashlib.sha256(content.encode()).hexdigest(),
|
||||||
|
}
|
||||||
|
atomic(BACKUP, json.dumps(backup).encode())
|
||||||
|
FRAGMENT.parent.mkdir(mode=0o755, exist_ok=True)
|
||||||
|
# Validate the live transaction before modifying persistent files.
|
||||||
|
run("nft", "-c", "-f", "-", input=(removal() + content).encode())
|
||||||
|
atomic(FRAGMENT, content.encode(), 0o644)
|
||||||
|
atomic(CONFIG, desired.encode(), 0o644)
|
||||||
|
run("nft", "-f", "-", input=(removal() + content).encode())
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def rollback(atomic):
|
||||||
|
record = json.loads(BACKUP.read_text())
|
||||||
|
if (
|
||||||
|
hashlib.sha256(CONFIG.read_bytes()).hexdigest() != record["after_sha256"]
|
||||||
|
or hashlib.sha256(FRAGMENT.read_bytes()).hexdigest() != record["fragment_sha256"]
|
||||||
|
):
|
||||||
|
raise ValueError("firewall changed; rollback will not overwrite foreign edits")
|
||||||
|
commands = removal()
|
||||||
|
if commands:
|
||||||
|
run("nft", "-f", "-", input=commands.encode())
|
||||||
|
atomic(CONFIG, record["before"].encode(), 0o644)
|
||||||
|
FRAGMENT.unlink()
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Versioned Ubuntu 24.04 amd64 installer. Run plan, then apply its exact digest."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import pwd
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import firewall
|
||||||
|
|
||||||
|
ROOT = Path("/opt/nodedc-mission-vps")
|
||||||
|
STATE = Path("/var/lib/ndc-mission-vps")
|
||||||
|
UNIT = Path("/etc/systemd/system/ndc-mission-vps.service")
|
||||||
|
USER = "ndc-mission-vps"
|
||||||
|
SOURCE = Path(__file__).resolve().parent
|
||||||
|
SERVICE = """# Managed by NODE.DC Mission VPS installer v1
|
||||||
|
[Unit]
|
||||||
|
Description=NODE.DC Mission VPS Host
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=ndc-mission-vps
|
||||||
|
Group=ndc-mission-vps
|
||||||
|
WorkingDirectory=/opt/nodedc-mission-vps/current
|
||||||
|
ExecStart=/usr/bin/python3 -m ndc_vps serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
UMask=0077
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ReadWritePaths=/var/lib/ndc-mission-vps
|
||||||
|
MemoryMax=192M
|
||||||
|
TasksMax=96
|
||||||
|
LimitNOFILE=2048
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args, **kwargs):
|
||||||
|
return subprocess.run(args, check=True, capture_output=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def digest():
|
||||||
|
manifest = json.loads((SOURCE / "manifest.json").read_text())
|
||||||
|
for name, expected in manifest["files"].items():
|
||||||
|
if name.startswith("/") or ".." in Path(name).parts:
|
||||||
|
raise ValueError("invalid manifest")
|
||||||
|
if hashlib.sha256((SOURCE / name).read_bytes()).hexdigest() != expected:
|
||||||
|
raise ValueError("artifact integrity mismatch")
|
||||||
|
return hashlib.sha256((SOURCE / "manifest.json").read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def predecessor():
|
||||||
|
return os.readlink(ROOT / "current") if (ROOT / "current").is_symlink() else None
|
||||||
|
|
||||||
|
|
||||||
|
def plan(args):
|
||||||
|
osrelease = dict(
|
||||||
|
line.split("=", 1)
|
||||||
|
for line in Path("/etc/os-release").read_text().splitlines()
|
||||||
|
if "=" in line
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
osrelease.get("ID", "").strip('"') != "ubuntu"
|
||||||
|
or osrelease.get("VERSION_ID", "").strip('"') != "24.04"
|
||||||
|
or platform.machine() != "x86_64"
|
||||||
|
):
|
||||||
|
raise ValueError("supported environment: Ubuntu Server 24.04 amd64 only")
|
||||||
|
if sys.version_info[:2] != (3, 12):
|
||||||
|
raise ValueError("Python 3.12 required")
|
||||||
|
for command in ("openssl", "systemctl", "useradd", "runuser"):
|
||||||
|
if not shutil.which(command):
|
||||||
|
raise ValueError("missing OS prerequisite: " + command)
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,48}", args.host):
|
||||||
|
raise ValueError("public DNS name or IPv4 required (max 49 characters for B2)")
|
||||||
|
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
|
||||||
|
raise ValueError("foreign service conflict")
|
||||||
|
if ROOT.exists() and not (ROOT / "installed.json").exists():
|
||||||
|
raise ValueError("foreign installation root conflict")
|
||||||
|
if STATE.exists() and not (STATE / "host.json").exists():
|
||||||
|
raise ValueError("foreign state directory conflict")
|
||||||
|
if (ROOT / "migration-fence.json").exists():
|
||||||
|
raise ValueError("source fenced for migration; resume explicitly only with target stopped")
|
||||||
|
old = predecessor()
|
||||||
|
for port in (args.api_port, args.tracker_port):
|
||||||
|
if port < 1024 or port > 65535:
|
||||||
|
raise ValueError("ports must be 1024..65535")
|
||||||
|
if not old:
|
||||||
|
with socket.socket() as sock:
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
sock.bind(("0.0.0.0", port))
|
||||||
|
if args.api_port == args.tracker_port:
|
||||||
|
raise ValueError("ports must differ")
|
||||||
|
configuration = {
|
||||||
|
"public_host": args.host,
|
||||||
|
"api_port": args.api_port,
|
||||||
|
"tracker": {"host": args.host, "port": args.tracker_port},
|
||||||
|
}
|
||||||
|
if STATE.exists():
|
||||||
|
existing = json.loads((STATE / "host.json").read_text())
|
||||||
|
if any(existing[key] != val for key, val in configuration.items()):
|
||||||
|
raise ValueError(
|
||||||
|
"endpoint migration requires a separate planned operation; use stable DNS"
|
||||||
|
)
|
||||||
|
data = {
|
||||||
|
"schema": "missioncore.vps-install-plan/v1",
|
||||||
|
"firewall": firewall.plan(),
|
||||||
|
"artifact": digest(),
|
||||||
|
"previous": old,
|
||||||
|
"configuration": configuration,
|
||||||
|
"unit_sha256": hashlib.sha256(UNIT.read_bytes()).hexdigest() if UNIT.exists() else None,
|
||||||
|
"environment": "ubuntu-24.04-amd64",
|
||||||
|
"service": str(UNIT),
|
||||||
|
"root": str(ROOT),
|
||||||
|
"key_file": str(ROOT / "connect.key"),
|
||||||
|
}
|
||||||
|
data["plan_sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def atomic(path, value, mode=0o600):
|
||||||
|
temporary = path.with_name(path.name + ".new")
|
||||||
|
temporary.write_bytes(value)
|
||||||
|
temporary.chmod(mode)
|
||||||
|
os.replace(temporary, path)
|
||||||
|
|
||||||
|
|
||||||
|
def select_release(release):
|
||||||
|
temporary = ROOT / ".current"
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
temporary.symlink_to(release)
|
||||||
|
os.replace(temporary, ROOT / "current")
|
||||||
|
|
||||||
|
|
||||||
|
def healthy():
|
||||||
|
for _ in range(20):
|
||||||
|
if subprocess.run(["systemctl", "is-active", "--quiet", "ndc-mission-vps"]).returncode == 0:
|
||||||
|
try:
|
||||||
|
config = json.loads((STATE / "host.json").read_text())
|
||||||
|
ctx = ssl.create_default_context(cafile=str(STATE / "tls.crt"))
|
||||||
|
ctx.check_hostname = False
|
||||||
|
with (
|
||||||
|
socket.create_connection(("127.0.0.1", config["api_port"]), 2) as sock,
|
||||||
|
ctx.wrap_socket(sock) as secure,
|
||||||
|
):
|
||||||
|
secure.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n")
|
||||||
|
if b"200 Result" in secure.recv(4096):
|
||||||
|
return
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
time.sleep(0.5)
|
||||||
|
raise ValueError("service health check failed")
|
||||||
|
|
||||||
|
|
||||||
|
def apply(args, proposal):
|
||||||
|
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"]:
|
||||||
|
raise ValueError("root and exact current plan digest required")
|
||||||
|
old = proposal["previous"]
|
||||||
|
installed = ROOT / "installed.json"
|
||||||
|
if (
|
||||||
|
old
|
||||||
|
and Path(old).name == proposal["artifact"]
|
||||||
|
and installed.exists()
|
||||||
|
and json.loads(installed.read_text()).get("status") == "healthy"
|
||||||
|
):
|
||||||
|
healthy()
|
||||||
|
print(json.dumps({"status": "already_current", "artifact": proposal["artifact"]}))
|
||||||
|
return
|
||||||
|
release = ROOT / "releases" / proposal["artifact"]
|
||||||
|
ROOT.mkdir(mode=0o755, exist_ok=True)
|
||||||
|
(ROOT / "releases").mkdir(mode=0o755, exist_ok=True)
|
||||||
|
# mkdir's mode is filtered by the caller's umask. The unprivileged service
|
||||||
|
# must traverse these owned code directories even under root's umask 0077.
|
||||||
|
ROOT.chmod(0o755)
|
||||||
|
(ROOT / "releases").chmod(0o755)
|
||||||
|
old_unit = UNIT.read_bytes() if UNIT.exists() else None
|
||||||
|
# Pre-create the ownership record: a failed first install can be inspected/retried.
|
||||||
|
if not (ROOT / "installed.json").exists():
|
||||||
|
atomic(
|
||||||
|
ROOT / "installed.json",
|
||||||
|
json.dumps({"schema": "missioncore.vps-install/v1", "status": "preparing"}).encode(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
pwd.getpwnam(USER)
|
||||||
|
except KeyError:
|
||||||
|
run("useradd", "--system", "--home-dir", str(STATE), "--shell", "/usr/sbin/nologin", USER)
|
||||||
|
user = pwd.getpwnam(USER)
|
||||||
|
if not release.exists():
|
||||||
|
shutil.copytree(SOURCE, release, ignore=shutil.ignore_patterns("__pycache__"))
|
||||||
|
release.chmod(0o755)
|
||||||
|
for item in release.rglob("*"):
|
||||||
|
item.chmod(0o755 if item.is_dir() else 0o644)
|
||||||
|
if not STATE.exists():
|
||||||
|
STATE.mkdir(mode=0o700)
|
||||||
|
configuration = proposal["configuration"].copy()
|
||||||
|
run(
|
||||||
|
"openssl",
|
||||||
|
"req",
|
||||||
|
"-x509",
|
||||||
|
"-newkey",
|
||||||
|
"ed25519",
|
||||||
|
"-nodes",
|
||||||
|
"-days",
|
||||||
|
"3650",
|
||||||
|
"-subj",
|
||||||
|
"/CN=NODE.DC Mission VPS Host",
|
||||||
|
"-keyout",
|
||||||
|
str(STATE / "tls.key"),
|
||||||
|
"-out",
|
||||||
|
str(STATE / "tls.crt"),
|
||||||
|
)
|
||||||
|
certificate = ssl.PEM_cert_to_DER_cert((STATE / "tls.crt").read_text())
|
||||||
|
fingerprint = hashlib.sha256(certificate).hexdigest()
|
||||||
|
configuration.update(
|
||||||
|
fingerprint=fingerprint,
|
||||||
|
host_id="vps_" + fingerprint,
|
||||||
|
endpoint=f"https://{args.host}:{args.api_port}",
|
||||||
|
)
|
||||||
|
atomic(STATE / "host.json", json.dumps(configuration, indent=2).encode())
|
||||||
|
os.chown(STATE, user.pw_uid, user.pw_gid)
|
||||||
|
for item in STATE.iterdir():
|
||||||
|
item.chmod(0o600)
|
||||||
|
os.chown(item, user.pw_uid, user.pw_gid)
|
||||||
|
if not (ROOT / "connect.key").is_symlink():
|
||||||
|
(ROOT / "connect.key").symlink_to(STATE / "connect.key")
|
||||||
|
firewall_added = False
|
||||||
|
try:
|
||||||
|
firewall_added = firewall.apply(
|
||||||
|
proposal["firewall"], args.api_port, args.tracker_port, atomic
|
||||||
|
)
|
||||||
|
select_release(release)
|
||||||
|
if not (STATE / "connect.key").exists():
|
||||||
|
run(
|
||||||
|
"runuser",
|
||||||
|
"-u",
|
||||||
|
USER,
|
||||||
|
"--",
|
||||||
|
"/usr/bin/python3",
|
||||||
|
"-m",
|
||||||
|
"ndc_vps",
|
||||||
|
"invitation",
|
||||||
|
cwd=release,
|
||||||
|
)
|
||||||
|
atomic(UNIT, SERVICE.encode(), 0o644)
|
||||||
|
run("systemctl", "daemon-reload")
|
||||||
|
run("systemctl", "enable", "ndc-mission-vps.service")
|
||||||
|
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||||
|
healthy()
|
||||||
|
atomic(
|
||||||
|
ROOT / "installed.json",
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
**proposal,
|
||||||
|
"status": "healthy",
|
||||||
|
"firewall_added": firewall_added,
|
||||||
|
"installed_at": time.time(),
|
||||||
|
},
|
||||||
|
indent=2,
|
||||||
|
).encode(),
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"status": "healthy",
|
||||||
|
"artifact": proposal["artifact"],
|
||||||
|
"key_file": str(ROOT / "connect.key"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
if firewall_added:
|
||||||
|
firewall.rollback(atomic)
|
||||||
|
if old:
|
||||||
|
select_release(old)
|
||||||
|
if old_unit:
|
||||||
|
atomic(UNIT, old_unit, 0o644)
|
||||||
|
run("systemctl", "daemon-reload")
|
||||||
|
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||||
|
healthy()
|
||||||
|
else:
|
||||||
|
subprocess.run(
|
||||||
|
["systemctl", "disable", "--now", "ndc-mission-vps.service"], capture_output=True
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def rollback(args):
|
||||||
|
record = json.loads((ROOT / "installed.json").read_text())
|
||||||
|
if os.geteuid() != 0 or args.expect != record["artifact"]:
|
||||||
|
raise ValueError("root and installed artifact digest required")
|
||||||
|
if record.get("firewall_added"):
|
||||||
|
firewall.rollback(atomic)
|
||||||
|
previous = record["previous"]
|
||||||
|
if previous:
|
||||||
|
path = Path(previous)
|
||||||
|
if path.parent != ROOT / "releases" or not path.is_dir():
|
||||||
|
raise ValueError("previous release unavailable")
|
||||||
|
select_release(path)
|
||||||
|
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||||
|
healthy()
|
||||||
|
else:
|
||||||
|
run("systemctl", "disable", "--now", "ndc-mission-vps.service")
|
||||||
|
# Preserve state, keys and journal even when uninstalling the first release.
|
||||||
|
atomic(ROOT / "installed.json", json.dumps({**record, "status": "rolled_back"}).encode())
|
||||||
|
print(json.dumps({"status": "rolled_back", "state_preserved": True}))
|
||||||
|
|
||||||
|
|
||||||
|
BACKUPS = Path("/var/backups/ndc-mission-vps")
|
||||||
|
|
||||||
|
|
||||||
|
def restore(backup):
|
||||||
|
if os.geteuid() != 0 or backup.parent != BACKUPS or backup.is_symlink():
|
||||||
|
raise ValueError("root and an installer-owned backup required")
|
||||||
|
if (ROOT / "migration-fence.json").exists():
|
||||||
|
raise ValueError("source fenced for migration")
|
||||||
|
record = json.loads((backup / "backup.json").read_text())
|
||||||
|
if record.get("schema") != "missioncore.vps-backup/v1":
|
||||||
|
raise ValueError("invalid backup")
|
||||||
|
# Verify before stopping anything. Never overwrite a foreign service.
|
||||||
|
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
|
||||||
|
raise ValueError("foreign service conflict")
|
||||||
|
for name, expected in record["files"].items():
|
||||||
|
file = backup / name
|
||||||
|
if ".." in Path(name).parts or file.is_symlink():
|
||||||
|
raise ValueError("invalid backup file")
|
||||||
|
if hashlib.sha256(file.read_bytes()).hexdigest() != expected:
|
||||||
|
raise ValueError("backup integrity mismatch")
|
||||||
|
run("systemctl", "stop", "ndc-mission-vps.service")
|
||||||
|
recovery = backup / ("replaced-" + uuid.uuid4().hex)
|
||||||
|
recovery.mkdir(mode=0o700)
|
||||||
|
for name, target in (("root", ROOT), ("state", STATE), ("unit", UNIT)):
|
||||||
|
if target.exists():
|
||||||
|
shutil.move(str(target), recovery / name)
|
||||||
|
source = backup / name
|
||||||
|
if source.is_dir():
|
||||||
|
shutil.copytree(source, target, symlinks=True)
|
||||||
|
else:
|
||||||
|
shutil.copy2(source, target)
|
||||||
|
user = pwd.getpwnam(USER)
|
||||||
|
os.chown(STATE, user.pw_uid, user.pw_gid)
|
||||||
|
for file in STATE.iterdir():
|
||||||
|
os.chown(file, user.pw_uid, user.pw_gid)
|
||||||
|
run("systemctl", "daemon-reload")
|
||||||
|
run("systemctl", "enable", "ndc-mission-vps.service")
|
||||||
|
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||||
|
healthy()
|
||||||
|
print(json.dumps({"status": "restored", "backup": str(backup)}))
|
||||||
|
|
||||||
|
|
||||||
|
def fresh(args, proposal):
|
||||||
|
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"] or not proposal["previous"]:
|
||||||
|
raise ValueError("fresh replacement requires an exact plan of an installed product")
|
||||||
|
BACKUPS.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
backup = BACKUPS / (time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:8])
|
||||||
|
backup.mkdir(mode=0o700)
|
||||||
|
run("systemctl", "stop", "ndc-mission-vps.service")
|
||||||
|
try:
|
||||||
|
for name, path in (("root", ROOT), ("state", STATE)):
|
||||||
|
shutil.copytree(path, backup / name, symlinks=True)
|
||||||
|
shutil.copy2(UNIT, backup / "unit")
|
||||||
|
files = {
|
||||||
|
str(p.relative_to(backup)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||||
|
for p in backup.rglob("*")
|
||||||
|
if p.is_file() and not p.is_symlink()
|
||||||
|
}
|
||||||
|
atomic(
|
||||||
|
backup / "backup.json",
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"schema": "missioncore.vps-backup/v1",
|
||||||
|
"created_at": time.time(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
"files": files,
|
||||||
|
}
|
||||||
|
).encode(),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
run("systemctl", "start", "ndc-mission-vps.service")
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
# Complete verified private copy exists; move original trees too, never wildcard-delete.
|
||||||
|
shutil.move(str(ROOT), backup / "original-root")
|
||||||
|
shutil.move(str(STATE), backup / "original-state")
|
||||||
|
shutil.move(str(UNIT), backup / "original-unit")
|
||||||
|
new_plan = plan(args)
|
||||||
|
args.expect = new_plan["plan_sha256"]
|
||||||
|
apply(args, new_plan)
|
||||||
|
except Exception:
|
||||||
|
restore(backup)
|
||||||
|
raise
|
||||||
|
print(json.dumps({"status": "fresh_install", "backup": str(backup)}))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("action", choices=("plan", "apply", "rollback"))
|
||||||
|
parser.add_argument("--host", required=True)
|
||||||
|
parser.add_argument("--api-port", type=int, default=19443)
|
||||||
|
parser.add_argument("--tracker-port", type=int, default=9922)
|
||||||
|
parser.add_argument("--expect")
|
||||||
|
args = parser.parse_args()
|
||||||
|
try:
|
||||||
|
if args.action == "rollback":
|
||||||
|
rollback(args)
|
||||||
|
else:
|
||||||
|
proposal = plan(args)
|
||||||
|
if args.action == "plan":
|
||||||
|
print(json.dumps(proposal, indent=2))
|
||||||
|
else:
|
||||||
|
apply(args, proposal)
|
||||||
|
except Exception as error:
|
||||||
|
print("Installation stopped: " + str(error), file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Headless NODE.DC Mission VPS Host; Python 3.12 standard library only."""
|
||||||
|
|
||||||
|
VERSION = "0.1.41"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
|
from .service import Service
|
||||||
|
from .store import Store
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("action", choices=("serve", "invitation", "status"))
|
||||||
|
parser.add_argument("--state", default="/var/lib/ndc-mission-vps")
|
||||||
|
args = parser.parse_args()
|
||||||
|
store = Store(args.state)
|
||||||
|
if args.action == "serve":
|
||||||
|
asyncio.run(Service(store).run())
|
||||||
|
elif args.action == "invitation":
|
||||||
|
store.invitation()
|
||||||
|
print("Invitation ready in /opt/nodedc-mission-vps/connect.key (valid 24 hours).")
|
||||||
|
else:
|
||||||
|
print(json.dumps(store.status()))
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""B2 manual §10 + INTERNAL SERVER_COM token envelope; no arbitrary commands."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
KINDS = {
|
||||||
|
"request-position",
|
||||||
|
"restart",
|
||||||
|
"pulse-output",
|
||||||
|
"set-output",
|
||||||
|
"upload-configuration",
|
||||||
|
"download-configuration",
|
||||||
|
"probe-diagnostic-mode",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(body):
|
||||||
|
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||||
|
raise ValueError("unqualified action firmware")
|
||||||
|
allowed = {"id", "imei", "kind", "model", "firmware"}
|
||||||
|
if body["kind"] == "probe-diagnostic-mode":
|
||||||
|
# INTERNAL SERVER_COM 01 00. Engineering qualification only: neither
|
||||||
|
# a SIM read nor a promise about this firmware's mode/termination.
|
||||||
|
# Admission additionally requires an explicit live observation lease.
|
||||||
|
allowed.add("observation_id")
|
||||||
|
if not isinstance(body.get("observation_id"), str) or not re.fullmatch(
|
||||||
|
r"[a-f0-9]{32}", body["observation_id"]
|
||||||
|
):
|
||||||
|
raise ValueError("diagnostic probe requires observation")
|
||||||
|
command = b"\x01\x00"
|
||||||
|
elif body["kind"] == "request-position":
|
||||||
|
command = b"\x01\x01"
|
||||||
|
elif body["kind"] == "restart":
|
||||||
|
# B2 manual §10. A token receipt is not proof of a completed restart.
|
||||||
|
command = b"\x01\x07"
|
||||||
|
elif body["kind"] == "upload-configuration" and body.get("encoding") == "binary":
|
||||||
|
# Documented read-only counterpart to SERV*1.9; no image is written.
|
||||||
|
allowed.add("encoding")
|
||||||
|
command = b"\x01\x09"
|
||||||
|
elif body["kind"] in ("upload-configuration", "download-configuration"):
|
||||||
|
allowed.add("password")
|
||||||
|
password = body.get("password")
|
||||||
|
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||||
|
raise ValueError("invalid password")
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown action fields")
|
||||||
|
# B2 manual §10: synchronize with the configured web endpoint. Download
|
||||||
|
# may apply settings: the endpoint owns staged data and readback checks.
|
||||||
|
number = 9 if body["kind"] == "upload-configuration" else 8
|
||||||
|
return {"encoding": "text", "binary": f"{password}*SERV*1.{number}".encode().hex()}
|
||||||
|
elif body["kind"] == "set-output":
|
||||||
|
allowed |= {"pin", "enabled", "encoding", "password"}
|
||||||
|
pin = body.get("pin")
|
||||||
|
enabled = body.get("enabled")
|
||||||
|
if type(pin) is not int or pin not in (4, 5, 6):
|
||||||
|
raise ValueError("unsupported output")
|
||||||
|
if type(enabled) is not bool:
|
||||||
|
raise ValueError("enabled must be boolean")
|
||||||
|
if body.get("encoding", "text") != "text":
|
||||||
|
raise ValueError("set-output requires text encoding")
|
||||||
|
password = body.get("password")
|
||||||
|
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||||
|
raise ValueError("invalid password")
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown action fields")
|
||||||
|
# B2 manual section 10: explicit, persistent low-side output state.
|
||||||
|
# The caller must request both transitions; there is no implicit retry.
|
||||||
|
return {
|
||||||
|
"encoding": "text",
|
||||||
|
"binary": f"{password}*SERV*8.{pin}.{int(enabled)}".encode("ascii").hex(),
|
||||||
|
}
|
||||||
|
elif body["kind"] == "pulse-output":
|
||||||
|
allowed |= {"pin", "seconds", "encoding"}
|
||||||
|
pin, seconds = body["pin"], body["seconds"]
|
||||||
|
if type(pin) is not int or pin not in (4, 5, 6):
|
||||||
|
raise ValueError("unsupported output")
|
||||||
|
if type(seconds) is not int or not 1 <= seconds <= 5:
|
||||||
|
raise ValueError("pulse must be 1..5 seconds")
|
||||||
|
command = bytes((0x18, pin, 0, seconds))
|
||||||
|
encoding = body.get("encoding", "binary")
|
||||||
|
if encoding not in ("binary", "text"):
|
||||||
|
raise ValueError("unsupported action encoding")
|
||||||
|
if encoding == "text":
|
||||||
|
allowed.add("password")
|
||||||
|
password = body.get("password")
|
||||||
|
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||||
|
raise ValueError("invalid password")
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown action fields")
|
||||||
|
# B2 manual §10: FC text has no token envelope. A reply to an
|
||||||
|
# unrelated command must never turn this into confirmed actuation.
|
||||||
|
return {
|
||||||
|
"encoding": "text",
|
||||||
|
"binary": f"{password}*SERV*24.{pin}.0.{seconds}".encode("ascii").hex(),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
raise ValueError("unsupported action")
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown action fields")
|
||||||
|
result = {"token": secrets.randbits(32), "binary": command.hex()}
|
||||||
|
if body["kind"] == "probe-diagnostic-mode":
|
||||||
|
result["observation_id"] = body["observation_id"]
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def frame(value):
|
||||||
|
if value.get("encoding") == "text":
|
||||||
|
raw = bytes.fromhex(value["binary"])
|
||||||
|
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
|
||||||
|
raw = b"\xff" + value["token"].to_bytes(4, "little") + bytes.fromhex(value["binary"])
|
||||||
|
return bytes((0x7B, len(raw), 0xFF, sum(raw) % 256)) + raw + b"}"
|
||||||
|
|
||||||
|
|
||||||
|
def confirmations(raw):
|
||||||
|
offset = 2
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
if raw[offset] == 9 and size == 5:
|
||||||
|
yield raw[offset + 7], int.from_bytes(raw[offset + 8 : offset + 12], "little")
|
||||||
|
offset += size + 8
|
||||||
@@ -0,0 +1,585 @@
|
|||||||
|
"""Durable allowlisted B2 operations; no firmware or arbitrary text commands."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import actions, configuration, full_configuration, restart, sim_guard, sim_selection
|
||||||
|
from .delivery import MAX_DELIVERY_SECONDS
|
||||||
|
from .observation import Observation
|
||||||
|
from .transport_evidence import TransportEvidence
|
||||||
|
from .web_protocol import decode_request, numeric_id_reply, time_reply
|
||||||
|
|
||||||
|
COMMAND_SESSION_MAX_IDLE = 5
|
||||||
|
CONFIGURATION_KINDS = full_configuration.KINDS | {
|
||||||
|
"read-settings",
|
||||||
|
"configure-server1",
|
||||||
|
"upload-configuration",
|
||||||
|
"download-configuration",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def frame(text):
|
||||||
|
raw = text.encode("cp1251")
|
||||||
|
if not 1 <= len(raw) <= 255:
|
||||||
|
raise ValueError("command length")
|
||||||
|
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
|
||||||
|
|
||||||
|
|
||||||
|
class Commands:
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
self.transport = TransportEvidence(store)
|
||||||
|
self.sim_guard = sim_guard.SimGuard(store)
|
||||||
|
self.sessions = {}
|
||||||
|
self.session_started = {}
|
||||||
|
self.session_activity = {}
|
||||||
|
self.session_peers = {}
|
||||||
|
self.session_ready = {}
|
||||||
|
with store.db() as db:
|
||||||
|
db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS commands(id TEXT PRIMARY KEY, imei TEXT NOT NULL, "
|
||||||
|
"digest TEXT NOT NULL, body TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
db.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS commands_active "
|
||||||
|
"ON commands(imei,json_extract(body,'$.state'))"
|
||||||
|
)
|
||||||
|
# Effectful stages never replay. A committed full-image write may
|
||||||
|
# resume its independent readback within the original deadline.
|
||||||
|
for identifier, body in db.execute(
|
||||||
|
"SELECT id,body FROM commands "
|
||||||
|
"WHERE json_extract(body,'$.state') IN ('queued','dispatched')"
|
||||||
|
).fetchall():
|
||||||
|
value = json.loads(body)
|
||||||
|
value = self.settle(db, identifier, value)
|
||||||
|
if self.verification_recoverable(value):
|
||||||
|
self.recover_verification(value)
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
elif (
|
||||||
|
value["kind"] in actions.KINDS - {"request-position"}
|
||||||
|
and value["state"] == "queued"
|
||||||
|
):
|
||||||
|
value.update(state="expired", reason="host_restarted")
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
elif (
|
||||||
|
value["state"] == "dispatched"
|
||||||
|
or value.get("stage") in ("write", "verify", "restart")
|
||||||
|
and value["state"] == "queued"
|
||||||
|
):
|
||||||
|
value.update(state="uncertain", reason="host_restarted")
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def verification_recoverable(value):
|
||||||
|
return (
|
||||||
|
value["kind"] == "configure-all"
|
||||||
|
and value.get("stage") == "verify"
|
||||||
|
and bool(value.get("write_reply_sent_at"))
|
||||||
|
and value["state"] in ("queued", "dispatched")
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def recover_verification(value):
|
||||||
|
value.update(
|
||||||
|
state="queued",
|
||||||
|
recovery_verification=True,
|
||||||
|
recovery_at=time.time(),
|
||||||
|
recovery_count=value.get("recovery_count", 0) + 1,
|
||||||
|
not_before=max(value.get("not_before", 0), value.get("dispatched_at", 0) + 15),
|
||||||
|
)
|
||||||
|
value.pop("session", None)
|
||||||
|
|
||||||
|
def submit(self, body):
|
||||||
|
# The original absolute deadline survives a lost HTTP reply and retry.
|
||||||
|
# Keep it in the idempotency digest, outside the device command payload.
|
||||||
|
original = body
|
||||||
|
body = dict(body)
|
||||||
|
not_after = body.pop("not_after", None)
|
||||||
|
if not_after is not None and (
|
||||||
|
type(not_after) not in (int, float) or not math.isfinite(not_after) or not_after <= 0
|
||||||
|
):
|
||||||
|
raise ValueError("invalid command deadline")
|
||||||
|
identifier, imei = body["id"], body["imei"]
|
||||||
|
kind = body["kind"]
|
||||||
|
password = body.get("password", "")
|
||||||
|
if (
|
||||||
|
not re.fullmatch(r"[a-f0-9]{32}", identifier)
|
||||||
|
or kind
|
||||||
|
not in actions.KINDS | full_configuration.KINDS | {"read-settings", "configure-server1"}
|
||||||
|
or not self.store.admitted(imei)
|
||||||
|
):
|
||||||
|
raise ValueError("unsupported command")
|
||||||
|
if kind not in actions.KINDS and not re.fullmatch(r"[0-9]{6}", password):
|
||||||
|
raise ValueError("invalid password")
|
||||||
|
allowed = {"id", "imei", "password", "kind"}
|
||||||
|
details = {}
|
||||||
|
if kind in actions.KINDS:
|
||||||
|
details = actions.prepare(body)
|
||||||
|
allowed = set(body)
|
||||||
|
elif kind in full_configuration.KINDS:
|
||||||
|
details = full_configuration.prepare(body)
|
||||||
|
allowed = set(body)
|
||||||
|
elif kind == "configure-server1":
|
||||||
|
allowed |= {"expected", "target", "model", "firmware"}
|
||||||
|
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||||
|
raise ValueError("unqualified firmware")
|
||||||
|
details = {
|
||||||
|
"expected": configuration.endpoint(body["expected"]),
|
||||||
|
"target": configuration.endpoint(body["target"]),
|
||||||
|
"stage": "preflight",
|
||||||
|
}
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown command fields")
|
||||||
|
payload = password + "*GETP"
|
||||||
|
digest = hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest()
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
previous = db.execute(
|
||||||
|
"SELECT digest,body FROM commands WHERE id=?", (identifier,)
|
||||||
|
).fetchone()
|
||||||
|
if previous:
|
||||||
|
if previous[0] != digest:
|
||||||
|
raise ValueError("idempotency conflict")
|
||||||
|
value = self.public(self.settle(db, identifier, json.loads(previous[1])))
|
||||||
|
value["transport"] = self.transport.read(db, identifier)
|
||||||
|
return value
|
||||||
|
if not_after is not None and not_after > time.time() + 600:
|
||||||
|
raise ValueError("command deadline too distant")
|
||||||
|
expired = not_after is not None and not_after <= time.time()
|
||||||
|
if (
|
||||||
|
not expired
|
||||||
|
and kind in (actions.KINDS | full_configuration.KINDS) - {"request-position"}
|
||||||
|
and not self.sessions.get(imei)
|
||||||
|
):
|
||||||
|
raise ValueError("device has no active session")
|
||||||
|
last_configuration_at = 0
|
||||||
|
for (encoded,) in db.execute("SELECT body FROM commands WHERE imei=?", (imei,)):
|
||||||
|
pending = json.loads(encoded)
|
||||||
|
if pending["kind"] in full_configuration.KINDS:
|
||||||
|
last_configuration_at = max(
|
||||||
|
last_configuration_at,
|
||||||
|
pending.get("configuration_received_at", 0),
|
||||||
|
pending.get("write_reply_sent_at", 0),
|
||||||
|
)
|
||||||
|
if not expired and self.active(db, imei):
|
||||||
|
raise ValueError("command already pending")
|
||||||
|
value = {
|
||||||
|
"id": identifier,
|
||||||
|
"kind": kind,
|
||||||
|
**details,
|
||||||
|
"state": "queued",
|
||||||
|
"payload": payload,
|
||||||
|
"password": password,
|
||||||
|
"created_at": time.time(),
|
||||||
|
"expires_at": time.time() + 120,
|
||||||
|
"replies": [],
|
||||||
|
"response_hashes": [],
|
||||||
|
}
|
||||||
|
if kind in actions.KINDS:
|
||||||
|
value.update(expires_at=time.time() + 30, dispatch_deadline=time.time() + 3)
|
||||||
|
if kind == "request-position":
|
||||||
|
# A read may wait for reconnection until its original expiry.
|
||||||
|
# Once dispatched it is never replayed, even after a crash.
|
||||||
|
value["dispatch_deadline"] = value["expires_at"]
|
||||||
|
if kind == "restart":
|
||||||
|
value["expires_at"] = time.time() + 180
|
||||||
|
value["allowed_sessions"] = list(self.sessions.get(imei, ()))
|
||||||
|
value.pop("payload")
|
||||||
|
value.pop("password")
|
||||||
|
elif kind in full_configuration.KINDS:
|
||||||
|
value["expires_at"] = time.time() + (360 if kind == "select-sim" else 180)
|
||||||
|
value["not_before"] = last_configuration_at + 15
|
||||||
|
if not_after is not None:
|
||||||
|
value["expires_at"] = min(value["expires_at"], not_after)
|
||||||
|
if "dispatch_deadline" in value:
|
||||||
|
value["dispatch_deadline"] = min(value["dispatch_deadline"], not_after)
|
||||||
|
if expired:
|
||||||
|
value.update(state="expired", reason="request_deadline")
|
||||||
|
elif kind == "probe-diagnostic-mode":
|
||||||
|
lease_end = Observation.diagnostic_lease(
|
||||||
|
db, value["observation_id"], identifier, bind_imei=imei
|
||||||
|
)
|
||||||
|
value["expires_at"] = min(value["expires_at"], lease_end)
|
||||||
|
value["dispatch_deadline"] = min(value["dispatch_deadline"], lease_end)
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO commands VALUES(?,?,?,?)",
|
||||||
|
(identifier, imei, digest, json.dumps(value)),
|
||||||
|
)
|
||||||
|
return self.public(value)
|
||||||
|
|
||||||
|
def settle(self, db, identifier, value):
|
||||||
|
state = self.public(value)["state"]
|
||||||
|
if state != value["state"]:
|
||||||
|
value = {**value, "state": state}
|
||||||
|
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
return value
|
||||||
|
|
||||||
|
def active(self, db, imei):
|
||||||
|
# Terminal history never enters the per-packet/per-session hot path.
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT id,body FROM commands WHERE imei=? "
|
||||||
|
"AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid",
|
||||||
|
(imei,),
|
||||||
|
).fetchall()
|
||||||
|
result = []
|
||||||
|
for identifier, encoded in rows:
|
||||||
|
value = self.settle(db, identifier, json.loads(encoded))
|
||||||
|
if value["state"] in ("queued", "dispatched"):
|
||||||
|
result.append((identifier, value))
|
||||||
|
return result
|
||||||
|
|
||||||
|
def wait_delay(self, imei):
|
||||||
|
with self.store.db() as db:
|
||||||
|
# Idle senders sleep until admission, a packet or a new command.
|
||||||
|
# Active staged operations retain their existing bounded timers.
|
||||||
|
return 1 if self.active(db, imei) else None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def public(value):
|
||||||
|
value = dict(value)
|
||||||
|
if (
|
||||||
|
value["state"] == "queued"
|
||||||
|
and value.get("dispatch_deadline", float("inf")) < time.time()
|
||||||
|
):
|
||||||
|
value["state"] = "expired"
|
||||||
|
if value["expires_at"] < time.time() and value["state"] in ("queued", "dispatched"):
|
||||||
|
value["state"] = (
|
||||||
|
"uncertain"
|
||||||
|
if value.get("write_reply_sent_at") or value.get("stage") == "restart"
|
||||||
|
else "expired"
|
||||||
|
if value["state"] == "queued"
|
||||||
|
else "unconfirmed"
|
||||||
|
)
|
||||||
|
hidden = {
|
||||||
|
"payload",
|
||||||
|
"password",
|
||||||
|
"before",
|
||||||
|
"after",
|
||||||
|
"response_hashes",
|
||||||
|
"session",
|
||||||
|
"binary",
|
||||||
|
"token",
|
||||||
|
"allowed_sessions",
|
||||||
|
"restart_sessions",
|
||||||
|
"target_configuration",
|
||||||
|
"before_configuration",
|
||||||
|
"sim_guard",
|
||||||
|
}
|
||||||
|
return {**{k: v for k, v in value.items() if k not in hidden}, "transport": []}
|
||||||
|
|
||||||
|
def get(self, identifier):
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
row = db.execute("SELECT body FROM commands WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("unknown command")
|
||||||
|
value = self.public(self.settle(db, identifier, json.loads(row[0])))
|
||||||
|
value["transport"] = self.transport.read(db, identifier)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def take(self, imei, session="test"):
|
||||||
|
delivery = self.take_delivery(imei, session)
|
||||||
|
return delivery[0] if delivery else None
|
||||||
|
|
||||||
|
def take_delivery(self, imei, session, *, with_receipt=False):
|
||||||
|
# A configuration reload can leave half-open old sockets beside the new
|
||||||
|
# live ones. Never let whichever sender wakes first steal the command.
|
||||||
|
active = tuple(self.sessions.get(imei, ()))
|
||||||
|
eligible = [s for s in active if self.session_ready.get((imei, s), True)]
|
||||||
|
if active and session not in eligible:
|
||||||
|
return None
|
||||||
|
observed = [s for s in eligible if (imei, s) in self.session_activity]
|
||||||
|
if observed and session != max(
|
||||||
|
observed, key=lambda s: (self.session_activity.get((imei, s), 0), s)
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
for identifier, value in self.active(db, imei):
|
||||||
|
if (
|
||||||
|
self.verification_recoverable(value)
|
||||||
|
and value["state"] == "dispatched"
|
||||||
|
and session != value.get("session")
|
||||||
|
and self.session_started.get((imei, session), 0) > value.get("monotonic", 0)
|
||||||
|
):
|
||||||
|
# A new B2 connection can outlive a half-open predecessor.
|
||||||
|
# Only the independent read migrates, never the image write.
|
||||||
|
self.recover_verification(value)
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
value["state"] == "queued"
|
||||||
|
and value.get("dispatch_deadline", float("inf")) < time.time()
|
||||||
|
):
|
||||||
|
value["state"] = "expired"
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
value["kind"] == "configure-server1"
|
||||||
|
and value.get("stage") == "write"
|
||||||
|
and value["state"] == "dispatched"
|
||||||
|
and time.time() - value["dispatched_at"] >= 15
|
||||||
|
):
|
||||||
|
# SETP may reconnect before its reply. Read-only verification can
|
||||||
|
# move to a new TCP session; the write itself is never resent.
|
||||||
|
value.update(stage="verify", state="queued")
|
||||||
|
value.pop("session", None)
|
||||||
|
if (
|
||||||
|
value["state"] != "queued"
|
||||||
|
or value["expires_at"] < time.time()
|
||||||
|
or value.get("not_before", 0) > time.time()
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if value.get("session") and value["session"] != session:
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
value["kind"] in actions.KINDS - {"request-position"}
|
||||||
|
and session not in value["allowed_sessions"]
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if value["kind"] == "request-position" and session not in active:
|
||||||
|
continue
|
||||||
|
if value["kind"] in CONFIGURATION_KINDS and active:
|
||||||
|
last_input = self.session_activity.get((imei, session))
|
||||||
|
if last_input is None or not (
|
||||||
|
0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
|
||||||
|
):
|
||||||
|
# A drained but silent TCP stream may already be dead.
|
||||||
|
# Await fresh device input; retain the original deadline
|
||||||
|
# and never replay a previously dispatched stage.
|
||||||
|
continue
|
||||||
|
if not self.store.admitted(imei):
|
||||||
|
return None
|
||||||
|
if value["kind"] == "probe-diagnostic-mode":
|
||||||
|
try:
|
||||||
|
Observation.diagnostic_lease(db, value["observation_id"], identifier)
|
||||||
|
except ValueError:
|
||||||
|
value.update(state="expired", reason="observation_closed")
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
if value.get("sim_guard") and value.get("stage") in ("write", "restart"):
|
||||||
|
guard = self.sim_guard.check(imei, value["sim_guard"], db=db)
|
||||||
|
if guard != "matched":
|
||||||
|
if guard == "changed":
|
||||||
|
value.update(state="rejected", reason="sim_card_changed")
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?",
|
||||||
|
(json.dumps(value), identifier),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
value.update(
|
||||||
|
state="dispatched",
|
||||||
|
dispatched_at=time.time(),
|
||||||
|
monotonic=time.monotonic(),
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
restarting = value["kind"] == "restart" or (
|
||||||
|
value["kind"] == "select-sim" and value.get("stage") == "restart"
|
||||||
|
)
|
||||||
|
if restarting:
|
||||||
|
value["restart_sessions"] = list(self.sessions.get(imei, ()))
|
||||||
|
if value["kind"] == "configure-server1":
|
||||||
|
value["payload"] = configuration.payload(value)
|
||||||
|
if value["stage"] == "write":
|
||||||
|
value["write_dispatched_at"] = time.time()
|
||||||
|
elif value["kind"] in full_configuration.KINDS and not restarting:
|
||||||
|
value["payload"] = full_configuration.payload(value)
|
||||||
|
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
data = (
|
||||||
|
actions.frame(value)
|
||||||
|
if value["kind"] in actions.KINDS or restarting
|
||||||
|
else frame(value["payload"])
|
||||||
|
)
|
||||||
|
deadline = value["monotonic"] + min(
|
||||||
|
MAX_DELIVERY_SECONDS, max(0, value["expires_at"] - value["dispatched_at"])
|
||||||
|
)
|
||||||
|
if with_receipt:
|
||||||
|
ticket = self.transport.prepare(db, identifier, value.get("stage", "execute"))
|
||||||
|
return data, deadline, ticket
|
||||||
|
return data, deadline
|
||||||
|
return None
|
||||||
|
|
||||||
|
def web_receive(self, raw, peer, *, with_deadline=False):
|
||||||
|
"""Qualified B2 HTTP channel, scoped to an admitted active modem peer."""
|
||||||
|
expires = time.time() + 12
|
||||||
|
|
||||||
|
def result(reply):
|
||||||
|
if reply is None or not with_deadline:
|
||||||
|
return reply
|
||||||
|
return reply, time.monotonic() + max(0, expires - time.time())
|
||||||
|
|
||||||
|
imei, command, payload = decode_request(raw)
|
||||||
|
if not self.store.admitted(imei) or not any(
|
||||||
|
self.session_peers.get((imei, s)) == peer for s in tuple(self.sessions.get(imei, ()))
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
reply = bytes.fromhex("5b00030006025d") if command == 6 else None
|
||||||
|
if command == 1:
|
||||||
|
number = self.store.numeric_id(imei)
|
||||||
|
return result(numeric_id_reply(number) if number is not None else None)
|
||||||
|
if command == 7:
|
||||||
|
# A clock request is independent of a settings transaction. It
|
||||||
|
# cannot advance its stage, confirm a write or extend its deadline.
|
||||||
|
return result(time_reply(int(time.time())))
|
||||||
|
if command == 5:
|
||||||
|
reply = bytes.fromhex("5b00030005015d")
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
for identifier, value in self.active(db, imei):
|
||||||
|
if (
|
||||||
|
value["kind"] not in full_configuration.KINDS
|
||||||
|
or value["state"] != "dispatched"
|
||||||
|
or value["expires_at"] <= time.time()
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if command == 5 and value["stage"] in ("preflight", "verify"):
|
||||||
|
full_configuration.upload(value, payload)
|
||||||
|
elif command == 2 and value["stage"] == "write":
|
||||||
|
guard = self.sim_guard.check(imei, value.get("sim_guard"), db=db)
|
||||||
|
if guard != "matched":
|
||||||
|
# No image bytes leave the process for a missing/replaced card.
|
||||||
|
value.update(
|
||||||
|
state="rejected" if guard == "changed" else "unconfirmed",
|
||||||
|
reason="sim_card_changed"
|
||||||
|
if guard == "changed"
|
||||||
|
else "sim_identity_unavailable",
|
||||||
|
)
|
||||||
|
reply = None
|
||||||
|
else:
|
||||||
|
reply = full_configuration.download(value)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
expires = min(expires, value["expires_at"])
|
||||||
|
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
break
|
||||||
|
return result(reply)
|
||||||
|
|
||||||
|
def receive(self, imei, raw, session="test"):
|
||||||
|
self.sim_guard.observe(imei, raw)
|
||||||
|
self.receive_actions(imei, raw, session)
|
||||||
|
started = self.session_started.get((imei, session))
|
||||||
|
if started is not None:
|
||||||
|
with self.store.db(write=True) as db:
|
||||||
|
for identifier, value in self.active(db, imei):
|
||||||
|
matched = (
|
||||||
|
self.sim_guard.check(
|
||||||
|
imei, value.get("sim_guard"), after=value.get("dispatched_at"), db=db
|
||||||
|
)
|
||||||
|
== "matched"
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
restart.observe(value, raw, session, started)
|
||||||
|
or matched
|
||||||
|
and sim_selection.observe(value, raw, session, started)
|
||||||
|
):
|
||||||
|
if value.get("sim_guard") and value["state"] == "sim_selected":
|
||||||
|
value["sim_guard_verified"] = True
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
# Preserve text response evidence privately, never interpret receipt as settings applied.
|
||||||
|
offset, replies = 2, []
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
if raw[offset] == 3:
|
||||||
|
replies.append(
|
||||||
|
(
|
||||||
|
int.from_bytes(raw[offset + 3 : offset + 7], "little"),
|
||||||
|
raw[offset + 7 : offset + 7 + size].decode("cp1251", errors="replace"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
offset += size + 8
|
||||||
|
if not replies:
|
||||||
|
return
|
||||||
|
with self.store.db(write=True) as db:
|
||||||
|
for identifier, value in self.active(db, imei):
|
||||||
|
if (
|
||||||
|
value["kind"] in actions.KINDS | full_configuration.KINDS
|
||||||
|
or value["state"] != "dispatched"
|
||||||
|
or value["expires_at"] < time.time()
|
||||||
|
or value.get("session") != session
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
accepted = []
|
||||||
|
for measured, reply in replies:
|
||||||
|
digest = hashlib.sha256(f"{measured}:{reply}".encode()).hexdigest()
|
||||||
|
if (
|
||||||
|
# This B2 timestamps text about 4 s behind the VPS clock.
|
||||||
|
# Bound skew and require strictly newer evidence at every stage.
|
||||||
|
measured < int(value["dispatched_at"]) - 10
|
||||||
|
or measured > time.time() + 5
|
||||||
|
or measured <= value.get("last_response_measured", 0)
|
||||||
|
or digest in value.get("response_hashes", [])
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
value.setdefault("response_hashes", []).append(digest)
|
||||||
|
if value["kind"] == "configure-server1":
|
||||||
|
if configuration.response(value, reply, self.store.config["tracker"]):
|
||||||
|
accepted.append(reply)
|
||||||
|
break # Never use two messages from one packet for separate stages.
|
||||||
|
elif reply.startswith("#1="):
|
||||||
|
accepted.append(reply)
|
||||||
|
if not accepted:
|
||||||
|
continue
|
||||||
|
value["last_response_measured"] = measured
|
||||||
|
if value["kind"] == "read-settings":
|
||||||
|
value.update(state="reply_received", replies=accepted)
|
||||||
|
elif value["stage"] == "verify" and value["state"] == "queued":
|
||||||
|
value.pop("session", None)
|
||||||
|
value["not_before"] = max(
|
||||||
|
value.get("not_before", 0), value["write_dispatched_at"] + 15
|
||||||
|
)
|
||||||
|
value.update(received_at=time.time())
|
||||||
|
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
|
||||||
|
def receive_actions(self, imei, raw, session):
|
||||||
|
replies = list(actions.confirmations(raw))
|
||||||
|
# B2 publishes the same token receipt through both monitoring streams.
|
||||||
|
# Correlate the device and token, not the socket that carried the request.
|
||||||
|
# Text commands still have no such correlation and are excluded below.
|
||||||
|
if (
|
||||||
|
not replies
|
||||||
|
or session not in self.sessions.get(imei, ())
|
||||||
|
or not self.store.admitted(imei)
|
||||||
|
):
|
||||||
|
return
|
||||||
|
with self.store.db(write=True) as db:
|
||||||
|
for identifier, value in self.active(db, imei):
|
||||||
|
if (
|
||||||
|
value["kind"] not in actions.KINDS
|
||||||
|
or value.get("encoding") == "text"
|
||||||
|
or value["state"] != "dispatched"
|
||||||
|
or value["expires_at"] < time.time()
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
for code, token in replies:
|
||||||
|
if token != value["token"] or code > 9:
|
||||||
|
continue
|
||||||
|
value.update(
|
||||||
|
received_at=time.time(),
|
||||||
|
roundtrip_seconds=time.monotonic() - value["monotonic"],
|
||||||
|
device_code=code,
|
||||||
|
reply_via_alternate_session=session != value.get("session"),
|
||||||
|
)
|
||||||
|
if code == 6 or value["kind"] == "restart" and code == 0:
|
||||||
|
value.setdefault("device_accepted_at", time.time())
|
||||||
|
else:
|
||||||
|
value["state"] = "device_confirmed" if code == 0 else "device_rejected"
|
||||||
|
db.execute(
|
||||||
|
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||||
|
)
|
||||||
|
break
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""B2 231 / 0.01: documented SETP #1 only, with a surviving secondary uplink.
|
||||||
|
|
||||||
|
Never translate USB field numbers into SETP groups. No generic command escape.
|
||||||
|
GETP contains secrets; only the explicit endpoint projection may reach Core UI.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def endpoint(value):
|
||||||
|
if not isinstance(value, dict) or set(value) != {"host", "port"}:
|
||||||
|
raise ValueError("invalid endpoint")
|
||||||
|
host, port = value["host"], value["port"]
|
||||||
|
if (
|
||||||
|
not isinstance(host, str)
|
||||||
|
or not 1 <= len(host) <= 32
|
||||||
|
or not re.fullmatch(r"[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*", host)
|
||||||
|
or type(port) is not int
|
||||||
|
or not 1 <= port <= 65535
|
||||||
|
):
|
||||||
|
raise ValueError("invalid endpoint")
|
||||||
|
return {"host": host, "port": port}
|
||||||
|
|
||||||
|
|
||||||
|
def groups(reply):
|
||||||
|
if not isinstance(reply, str) or not reply.startswith("#") or len(reply) > 4096:
|
||||||
|
raise ValueError("invalid GETP")
|
||||||
|
result = {}
|
||||||
|
for part in reply.split("#")[1:]:
|
||||||
|
key, sep, value = part.partition("=")
|
||||||
|
if not sep or not key.isdecimal() or key in result:
|
||||||
|
raise ValueError("invalid GETP group")
|
||||||
|
result[key] = value
|
||||||
|
if not {"1", "2", "5", "7", "26"} <= result.keys():
|
||||||
|
raise ValueError("incomplete GETP")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def server(value):
|
||||||
|
parts = value.split(",")
|
||||||
|
# Preserve the undocumented fifth value, accept only the qualified empty form.
|
||||||
|
if len(parts) != 5 or parts[2:] != ["0", "0", ""]:
|
||||||
|
raise ValueError("unsupported server settings")
|
||||||
|
return endpoint({"host": parts[0], "port": int(parts[1])})
|
||||||
|
|
||||||
|
|
||||||
|
def response(operation, reply, tracker):
|
||||||
|
"""Advance only from complete, scoped read evidence. Caller persists atomically."""
|
||||||
|
try:
|
||||||
|
actual = groups(reply)
|
||||||
|
primary, secondary = server(actual["1"]), server(actual["26"])
|
||||||
|
except (ValueError, KeyError):
|
||||||
|
return False
|
||||||
|
stage = operation["stage"]
|
||||||
|
if stage == "preflight":
|
||||||
|
if primary != operation["expected"] or secondary != endpoint(tracker):
|
||||||
|
operation.update(state="rejected", reason="configuration_changed")
|
||||||
|
elif primary == operation["target"]:
|
||||||
|
operation.update(state="verified", verified_at=time.time(), server1=primary)
|
||||||
|
else:
|
||||||
|
operation.update(before=actual, stage="write", state="queued")
|
||||||
|
elif stage == "write":
|
||||||
|
# SETP acknowledgement is never enough: issue a separate GETP after a drain interval.
|
||||||
|
operation.update(stage="verify", state="queued", not_before=time.time() + 3)
|
||||||
|
elif stage == "verify":
|
||||||
|
before = operation["before"]
|
||||||
|
preserved = {k: v for k, v in actual.items() if k != "1"} == {
|
||||||
|
k: v for k, v in before.items() if k != "1"
|
||||||
|
}
|
||||||
|
operation["after"] = actual
|
||||||
|
if primary == operation["target"] and preserved:
|
||||||
|
operation.update(state="verified", verified_at=time.time(), server1=primary)
|
||||||
|
elif actual == before:
|
||||||
|
operation.update(state="not_applied", reason="settings_unchanged")
|
||||||
|
else:
|
||||||
|
operation.update(state="uncertain", reason="readback_mismatch")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def payload(operation):
|
||||||
|
if operation["stage"] == "write":
|
||||||
|
target = operation["target"]
|
||||||
|
return f"{operation['password']}*SETP*#1={target['host']},{target['port']}"
|
||||||
|
return operation["password"] + "*GETP"
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""Bound the lifetime of command bytes in a Linux TCP send queue.
|
||||||
|
|
||||||
|
TCP acknowledgement is transport evidence only, never command confirmation.
|
||||||
|
All writes on the guarded stream must pass through write(), including ACKs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import fcntl
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import termios
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
MAX_DELIVERY_SECONDS = 30
|
||||||
|
|
||||||
|
|
||||||
|
def queued_bytes(sock):
|
||||||
|
if sys.platform != "linux":
|
||||||
|
# Production is qualified on Ubuntu only. Other platforms conservatively
|
||||||
|
# retain the deadline, without claiming TCP acknowledgement evidence.
|
||||||
|
return None
|
||||||
|
return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0]
|
||||||
|
|
||||||
|
|
||||||
|
class Delivery:
|
||||||
|
def __init__(self, writer):
|
||||||
|
self.writer = writer
|
||||||
|
self.sock = writer.get_extra_info("socket")
|
||||||
|
# Also abort queued kernel data on EOF, task cancellation and shutdown.
|
||||||
|
# transport.abort() alone discards only asyncio's own write buffer.
|
||||||
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
|
||||||
|
if sys.platform == "linux":
|
||||||
|
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000)
|
||||||
|
self.written = 0
|
||||||
|
self.pending = deque()
|
||||||
|
self.timer = None
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
"""Do not enqueue a new command behind an unacknowledged stream prefix.
|
||||||
|
|
||||||
|
This is Linux transport admission, not device execution confirmation.
|
||||||
|
Non-Linux engineering tests retain their conservative expiry watchdog.
|
||||||
|
"""
|
||||||
|
if self.writer.is_closing() or self.writer.transport.get_write_buffer_size():
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
queued = queued_bytes(self.sock)
|
||||||
|
return queued is None or queued == 0
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def write(self, data, deadline=None, observe=None):
|
||||||
|
started = time.monotonic()
|
||||||
|
|
||||||
|
def note(phase, reason=None):
|
||||||
|
if observe is not None:
|
||||||
|
observe(phase, time.time(), time.monotonic() - started, reason)
|
||||||
|
|
||||||
|
if deadline is not None and deadline <= time.monotonic():
|
||||||
|
note("unconfirmed", "expired_before_write")
|
||||||
|
self.abort()
|
||||||
|
raise TimeoutError("command delivery expired before write")
|
||||||
|
try:
|
||||||
|
self.writer.write(data)
|
||||||
|
except (OSError, RuntimeError):
|
||||||
|
note("unconfirmed", "write_failed")
|
||||||
|
raise
|
||||||
|
note("written")
|
||||||
|
self.written += len(data)
|
||||||
|
if deadline is not None:
|
||||||
|
self.pending.append((self.written, deadline, note))
|
||||||
|
self.check()
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.cancel_timer()
|
||||||
|
if not self.pending:
|
||||||
|
return
|
||||||
|
if self.writer.is_closing():
|
||||||
|
self.abort()
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
queued = queued_bytes(self.sock)
|
||||||
|
if queued is not None:
|
||||||
|
acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size()
|
||||||
|
while self.pending and self.pending[0][0] <= acknowledged:
|
||||||
|
self.pending.popleft()[2]("tcp_acknowledged")
|
||||||
|
if self.pending:
|
||||||
|
remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
self.abort("delivery_deadline")
|
||||||
|
else:
|
||||||
|
self.timer = asyncio.get_running_loop().call_later(
|
||||||
|
min(0.25, remaining), self.check
|
||||||
|
)
|
||||||
|
except OSError:
|
||||||
|
self.abort("socket_error")
|
||||||
|
|
||||||
|
def cancel_timer(self):
|
||||||
|
if self.timer is not None:
|
||||||
|
self.timer.cancel()
|
||||||
|
self.timer = None
|
||||||
|
|
||||||
|
def abort(self, reason="connection_closed"):
|
||||||
|
self.cancel_timer()
|
||||||
|
while self.pending:
|
||||||
|
self.pending.popleft()[2]("unconfirmed", reason)
|
||||||
|
self.writer.transport.abort()
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""Whole-image B2 transactions: fresh preflight, one write, independent readback."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import sim_guard, sim_selection
|
||||||
|
from .usb_protocol import decode_configuration
|
||||||
|
from .web_protocol import settings_reply
|
||||||
|
|
||||||
|
KINDS = {"read-configuration", "configure-all", "select-sim"}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(body):
|
||||||
|
allowed = {"id", "imei", "kind", "password", "model", "firmware"}
|
||||||
|
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||||
|
raise ValueError("unqualified configuration firmware")
|
||||||
|
result = {"stage": "preflight"}
|
||||||
|
if body["kind"] in ("configure-all", "select-sim"):
|
||||||
|
allowed |= {"expected_sha256", "target_configuration"}
|
||||||
|
if not re.fullmatch(r"[a-f0-9]{64}", body["expected_sha256"]):
|
||||||
|
raise ValueError("invalid predecessor")
|
||||||
|
raw = bytes.fromhex(body["target_configuration"])
|
||||||
|
config = decode_configuration(raw)
|
||||||
|
settings_reply(config) # transport-size admission, without a write
|
||||||
|
result.update(expected_sha256=body["expected_sha256"], target_configuration=raw.hex())
|
||||||
|
if "sim_guard" in body:
|
||||||
|
allowed.add("sim_guard")
|
||||||
|
result["sim_guard"] = sim_guard.prepare(body["sim_guard"])
|
||||||
|
if body["kind"] != "select-sim" or body.get("sim_slot") != result["sim_guard"]["slot"]:
|
||||||
|
raise ValueError("SIM guard requires exclusive selection of the same slot")
|
||||||
|
if body["kind"] == "select-sim":
|
||||||
|
allowed |= {"sim_slot", "sim_policy"}
|
||||||
|
mask = (1 << 10) | (1 << 20)
|
||||||
|
policy = body.get("sim_policy", "exclusive")
|
||||||
|
if policy == "both":
|
||||||
|
if "sim_slot" in body or config.integer(72, 4) & mask:
|
||||||
|
raise ValueError("both SIMs must be permitted without an exclusive slot")
|
||||||
|
result["sim_policy"] = policy
|
||||||
|
elif policy == "exclusive":
|
||||||
|
slot = body.get("sim_slot")
|
||||||
|
if type(slot) is not int or slot not in (1, 2):
|
||||||
|
raise ValueError("invalid SIM slot")
|
||||||
|
if config.integer(72, 4) & mask != 1 << (20 if slot == 1 else 10):
|
||||||
|
raise ValueError("SIM flags do not match requested slot")
|
||||||
|
result["sim_slot"] = slot
|
||||||
|
else:
|
||||||
|
raise ValueError("invalid SIM policy")
|
||||||
|
if set(body) - allowed:
|
||||||
|
raise ValueError("unknown configuration fields")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def payload(value):
|
||||||
|
number = 8 if value["stage"] == "write" else 9
|
||||||
|
return value["password"] + f"*SERV*1.{number}"
|
||||||
|
|
||||||
|
|
||||||
|
def upload(value, raw):
|
||||||
|
config = decode_configuration(raw)
|
||||||
|
digest = hashlib.sha256(raw).hexdigest()
|
||||||
|
value.update(
|
||||||
|
configuration=raw.hex(), configuration_sha256=digest, configuration_received_at=time.time()
|
||||||
|
)
|
||||||
|
if value["kind"] == "read-configuration":
|
||||||
|
value.update(state="observed", verified_at=time.time())
|
||||||
|
elif value["stage"] == "preflight":
|
||||||
|
value["before_configuration"] = raw.hex()
|
||||||
|
target = decode_configuration(bytes.fromhex(value["target_configuration"]))
|
||||||
|
# Preserve every unknown field and the recovery channels. Core controls
|
||||||
|
# the reviewed profile fields; network migration of these requires its
|
||||||
|
# own destination-admission transaction, not a blind full-image write.
|
||||||
|
critical = (3, 4, 5, 8, 70, 71)
|
||||||
|
if (
|
||||||
|
digest != value["expected_sha256"]
|
||||||
|
or [r.number for r in config.records] != [r.number for r in target.records]
|
||||||
|
or any(config.value(n) != target.value(n) for n in critical)
|
||||||
|
):
|
||||||
|
value.update(state="rejected", reason="configuration_predecessor_mismatch")
|
||||||
|
elif raw.hex() == value["target_configuration"]:
|
||||||
|
value.update(state="verified", verified_at=time.time(), unchanged=True)
|
||||||
|
if value["kind"] == "select-sim":
|
||||||
|
sim_selection.queue_restart(value)
|
||||||
|
else:
|
||||||
|
value.update(state="queued", stage="write", not_before=time.time() + 15)
|
||||||
|
value.pop("session", None)
|
||||||
|
elif value["stage"] == "verify":
|
||||||
|
state = (
|
||||||
|
"verified"
|
||||||
|
if raw.hex() == value["target_configuration"]
|
||||||
|
else "not_applied"
|
||||||
|
if raw.hex() == value["before_configuration"]
|
||||||
|
else "uncertain"
|
||||||
|
)
|
||||||
|
value.update(state=state, verified_at=time.time())
|
||||||
|
if state == "verified" and value["kind"] == "select-sim":
|
||||||
|
sim_selection.queue_restart(value)
|
||||||
|
|
||||||
|
|
||||||
|
def download(value):
|
||||||
|
"""Call only inside the durable transaction, before writing the HTTP socket."""
|
||||||
|
if value.get("write_reply_sent_at"):
|
||||||
|
return None
|
||||||
|
raw = settings_reply(decode_configuration(bytes.fromhex(value["target_configuration"])))
|
||||||
|
value.update(
|
||||||
|
write_reply_sent_at=time.time(),
|
||||||
|
write_reply_sha256=hashlib.sha256(raw).hexdigest(),
|
||||||
|
stage="verify",
|
||||||
|
state="queued",
|
||||||
|
not_before=time.time() + 15,
|
||||||
|
)
|
||||||
|
value.pop("session", None)
|
||||||
|
return raw
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
"""Explicit, bounded interoperability evidence on the owned socket.
|
||||||
|
|
||||||
|
Disabled unless the authenticated owner arms a 180-second lease. Unknown traffic
|
||||||
|
is never treated as telemetry. A captured identity reply may be replayed once,
|
||||||
|
only to the byte-identical request of an admitted device. No vendor connection.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .web_protocol import decode_request, decode_settings_reply
|
||||||
|
|
||||||
|
|
||||||
|
class Observation:
|
||||||
|
@staticmethod
|
||||||
|
def diagnostic_lease(db, identifier, command_id, *, bind_imei=None):
|
||||||
|
"""One fixed diagnostic command per explicitly armed evidence window.
|
||||||
|
|
||||||
|
Expiry bounds our dispatch/capture, not the device's service mode.
|
||||||
|
No repeated toggle, arbitrary payload, or automatic device restart.
|
||||||
|
"""
|
||||||
|
if not db.execute(
|
||||||
|
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='observations'"
|
||||||
|
).fetchone():
|
||||||
|
raise ValueError("diagnostic observation unavailable")
|
||||||
|
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("diagnostic observation unavailable")
|
||||||
|
value = json.loads(row[0])
|
||||||
|
if value["expires_at"] <= time.time() or value.get("reference"):
|
||||||
|
raise ValueError("diagnostic observation unavailable")
|
||||||
|
bound = value.get("diagnostic_command_id")
|
||||||
|
if bound not in (None, command_id) or bind_imei is None and bound != command_id:
|
||||||
|
raise ValueError("diagnostic observation already used")
|
||||||
|
if bind_imei is not None:
|
||||||
|
value.update(diagnostic_command_id=command_id, diagnostic_imei=bind_imei)
|
||||||
|
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
return value["expires_at"]
|
||||||
|
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
with store.db() as db:
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS observations(id TEXT PRIMARY KEY, body TEXT)")
|
||||||
|
db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS observation_data(lease TEXT, sequence INTEGER, "
|
||||||
|
"raw BLOB, metadata TEXT, PRIMARY KEY(lease,sequence))"
|
||||||
|
)
|
||||||
|
|
||||||
|
def arm(self, body):
|
||||||
|
if set(body) not in ({"id"}, {"id", "reference"}) or not re.fullmatch(
|
||||||
|
r"[a-f0-9]{32}", body["id"]
|
||||||
|
):
|
||||||
|
raise ValueError("invalid observation")
|
||||||
|
reference = body.get("reference")
|
||||||
|
if "reference" in body:
|
||||||
|
if not isinstance(reference, dict) or set(reference) != {"request", "response"}:
|
||||||
|
raise ValueError("invalid reference")
|
||||||
|
request = bytes.fromhex(reference["request"])
|
||||||
|
response = bytes.fromhex(reference["response"])
|
||||||
|
imei, command, _ = decode_request(request, observe_empty_check=True)
|
||||||
|
if not self.store.admitted(imei):
|
||||||
|
raise ValueError("unqualified reference exchange")
|
||||||
|
if command == 6 and response == bytes.fromhex("5b00030006025d"):
|
||||||
|
pass
|
||||||
|
elif command == 1 and (
|
||||||
|
response == bytes.fromhex("5b000200015d")
|
||||||
|
or (
|
||||||
|
len(response) == 10
|
||||||
|
and response[:5] == bytes.fromhex("5b00060001")
|
||||||
|
and response[-1:] == b"]"
|
||||||
|
and int.from_bytes(response[5:9], "big") > 0
|
||||||
|
)
|
||||||
|
):
|
||||||
|
# The captured four-byte response equals the bench's numeric
|
||||||
|
# device ID. Qualify its exact replay once; no image payload.
|
||||||
|
pass
|
||||||
|
elif command == 2:
|
||||||
|
if response != bytes.fromhex("5b000200025d"):
|
||||||
|
decode_settings_reply(response)
|
||||||
|
# Bounded qualification of a zero-payload no-image response.
|
||||||
|
# Not admitted in the normal product channel until physically
|
||||||
|
# verified; no CRC image or device configuration is supplied.
|
||||||
|
elif command == 5 and response == bytes.fromhex("5b00030005015d"):
|
||||||
|
# Byte-exact command-5 reply captured from the manufacturer
|
||||||
|
# for the owner-approved return of its own configuration.
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise ValueError("unqualified reference exchange")
|
||||||
|
now = time.time()
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
if db.execute("SELECT 1 FROM observations WHERE id=?", (body["id"],)).fetchone():
|
||||||
|
previous = json.loads(
|
||||||
|
db.execute(
|
||||||
|
"SELECT body FROM observations WHERE id=?", (body["id"],)
|
||||||
|
).fetchone()[0]
|
||||||
|
)
|
||||||
|
if previous.get("reference") != reference:
|
||||||
|
raise ValueError("observation idempotency conflict")
|
||||||
|
return self.get(body["id"])
|
||||||
|
if any(
|
||||||
|
json.loads(r[0])["expires_at"] > now
|
||||||
|
for r in db.execute("SELECT body FROM observations")
|
||||||
|
):
|
||||||
|
raise ValueError("observation already armed")
|
||||||
|
if db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] >= 64:
|
||||||
|
raise ValueError("observation evidence capacity reached")
|
||||||
|
value = {"id": body["id"], "created_at": now, "expires_at": now + 180}
|
||||||
|
if reference is not None:
|
||||||
|
value["reference"] = reference
|
||||||
|
db.execute("INSERT INTO observations VALUES(?,?)", (body["id"], json.dumps(value)))
|
||||||
|
return self.get(body["id"])
|
||||||
|
|
||||||
|
def get(self, identifier):
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("unknown observation")
|
||||||
|
value = json.loads(row[0])
|
||||||
|
value.pop("reference", None)
|
||||||
|
value.pop("diagnostic_imei", None)
|
||||||
|
value["captures"] = [
|
||||||
|
json.loads(r[0])
|
||||||
|
for r in db.execute(
|
||||||
|
"SELECT metadata FROM observation_data WHERE lease=? ORDER BY sequence",
|
||||||
|
(identifier,),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
return value
|
||||||
|
|
||||||
|
def close(self, identifier):
|
||||||
|
"""Disarm without deleting private evidence or retrying a dispatch."""
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("unknown observation")
|
||||||
|
value = json.loads(row[0])
|
||||||
|
value["expires_at"] = min(value["expires_at"], time.time())
|
||||||
|
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||||
|
return self.get(identifier)
|
||||||
|
|
||||||
|
def reply(self, ticket, raw):
|
||||||
|
"""Persist one dispatch before writing, including across service restarts."""
|
||||||
|
request = http_body(raw)
|
||||||
|
if request is None:
|
||||||
|
return None
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
row = db.execute("SELECT body FROM observations WHERE id=?", (ticket[0],)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
value = json.loads(row[0])
|
||||||
|
reference = value.get("reference")
|
||||||
|
if (
|
||||||
|
not reference
|
||||||
|
or value["expires_at"] <= time.time()
|
||||||
|
or value.get("reply_dispatched_at")
|
||||||
|
or request != bytes.fromhex(reference["request"])
|
||||||
|
or not self.store.admitted(str(int.from_bytes(request[4:12], "little")))
|
||||||
|
or not db.execute(
|
||||||
|
"SELECT 1 FROM observation_data WHERE lease=? AND sequence=?", ticket
|
||||||
|
).fetchone()
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
response = bytes.fromhex(reference["response"])
|
||||||
|
value.update(
|
||||||
|
reply_dispatched_at=time.time(),
|
||||||
|
reply_monotonic=time.monotonic(),
|
||||||
|
reply_sha256=hashlib.sha256(response).hexdigest(),
|
||||||
|
reply_sequence=ticket[1],
|
||||||
|
)
|
||||||
|
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), ticket[0]))
|
||||||
|
return response
|
||||||
|
|
||||||
|
def claim(self):
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
for identifier, body in db.execute("SELECT id,body FROM observations"):
|
||||||
|
if json.loads(body)["expires_at"] <= time.time():
|
||||||
|
continue
|
||||||
|
sequence = db.execute(
|
||||||
|
"SELECT COUNT(*) FROM observation_data WHERE lease=?", (identifier,)
|
||||||
|
).fetchone()[0]
|
||||||
|
if sequence >= 4:
|
||||||
|
return None
|
||||||
|
metadata = {
|
||||||
|
"sequence": sequence,
|
||||||
|
"started_at": time.time(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
"state": "receiving",
|
||||||
|
}
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO observation_data VALUES(?,?,?,?)",
|
||||||
|
(identifier, sequence, b"", json.dumps(metadata)),
|
||||||
|
)
|
||||||
|
return identifier, sequence
|
||||||
|
return None
|
||||||
|
|
||||||
|
def finish(self, ticket, raw, events):
|
||||||
|
if len(raw) > 16384:
|
||||||
|
raise ValueError("observation limit")
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT metadata FROM observation_data WHERE lease=? AND sequence=?", ticket
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("unknown capture")
|
||||||
|
value = json.loads(row[0])
|
||||||
|
value.update(
|
||||||
|
state="captured",
|
||||||
|
completed_at=time.time(),
|
||||||
|
bytes=len(raw),
|
||||||
|
sha256=hashlib.sha256(raw).hexdigest(),
|
||||||
|
events=events,
|
||||||
|
)
|
||||||
|
db.execute(
|
||||||
|
"UPDATE observation_data SET raw=?,metadata=? WHERE lease=? AND sequence=?",
|
||||||
|
(raw, json.dumps(value), *ticket),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def http_body(raw):
|
||||||
|
"""First complete, bounded B2 POST only; reject ambiguous HTTP framing."""
|
||||||
|
header, separator, body = raw.partition(b"\r\n\r\n")
|
||||||
|
if not separator or len(header) > 2048:
|
||||||
|
return None
|
||||||
|
lines = header.split(b"\r\n")
|
||||||
|
if lines[0] != b"POST /c/index.php HTTP/1.1":
|
||||||
|
return None
|
||||||
|
headers = {}
|
||||||
|
for line in lines[1:]:
|
||||||
|
key, colon, value = line.partition(b":")
|
||||||
|
key = key.lower()
|
||||||
|
if not colon or key in headers:
|
||||||
|
return None
|
||||||
|
headers[key] = value.strip()
|
||||||
|
size = headers.get(b"content-length", b"")
|
||||||
|
if b"transfer-encoding" in headers or not size.isdigit():
|
||||||
|
return None
|
||||||
|
size = int(size)
|
||||||
|
if not 1 <= size <= 16384 or len(body) < size:
|
||||||
|
return None
|
||||||
|
return bytes(body[:size])
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
"""Durable tracker-maintenance intents; bounded attempts belong to Commands.
|
||||||
|
|
||||||
|
An outage ends an attempt, not its owning intent. No downstream output action
|
||||||
|
is admitted here. State changes reconcile the actual B2 image before retrying.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from . import actions, full_configuration, sim_selection
|
||||||
|
|
||||||
|
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
|
||||||
|
PENDING = {"queued", "dispatched"}
|
||||||
|
RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"}
|
||||||
|
FACTS = {
|
||||||
|
"transport",
|
||||||
|
"stage",
|
||||||
|
"dispatched_at",
|
||||||
|
"received_at",
|
||||||
|
"device_accepted_at",
|
||||||
|
"device_code",
|
||||||
|
"roundtrip_seconds",
|
||||||
|
"reconnected_at",
|
||||||
|
"reconnect_seconds",
|
||||||
|
"verified_at",
|
||||||
|
"configuration",
|
||||||
|
"configuration_sha256",
|
||||||
|
"configuration_received_at",
|
||||||
|
"write_reply_sent_at",
|
||||||
|
"active_sim",
|
||||||
|
"telemetry_measured_at",
|
||||||
|
"unchanged",
|
||||||
|
"sim_guard_verified",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Operations:
|
||||||
|
def __init__(self, store, commands):
|
||||||
|
self.store, self.commands = store, commands
|
||||||
|
# Only local SQLite work under this lock; never sockets, sleeps or device I/O.
|
||||||
|
self.lock = threading.RLock()
|
||||||
|
with store.db() as db:
|
||||||
|
db.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS operations(
|
||||||
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,
|
||||||
|
imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL);
|
||||||
|
CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq);
|
||||||
|
CREATE TABLE IF NOT EXISTS operation_attempts(
|
||||||
|
operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL,
|
||||||
|
body TEXT NOT NULL,PRIMARY KEY(operation,number));
|
||||||
|
CREATE TABLE IF NOT EXISTS operation_modem(
|
||||||
|
imei TEXT PRIMARY KEY,body TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL);
|
||||||
|
""")
|
||||||
|
|
||||||
|
def save(self, value):
|
||||||
|
with self.store.db() as db:
|
||||||
|
encoded = json.dumps(value)
|
||||||
|
db.execute(
|
||||||
|
"UPDATE operations SET state=?,body=? WHERE id=? AND body<>?",
|
||||||
|
(value["state"], encoded, value["id"], encoded),
|
||||||
|
)
|
||||||
|
|
||||||
|
def submit(self, body):
|
||||||
|
body = dict(body)
|
||||||
|
if (
|
||||||
|
not re.fullmatch(r"[a-f0-9]{32}", body.get("id", ""))
|
||||||
|
or body.get("kind") not in KINDS
|
||||||
|
or not self.store.admitted(body.get("imei"))
|
||||||
|
):
|
||||||
|
raise ValueError("unsupported operation")
|
||||||
|
if body["kind"] in full_configuration.KINDS:
|
||||||
|
if not re.fullmatch(r"[0-9]{6}", body.get("password", "")):
|
||||||
|
raise ValueError("invalid password")
|
||||||
|
full_configuration.prepare(body)
|
||||||
|
else:
|
||||||
|
actions.prepare(body)
|
||||||
|
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
|
||||||
|
with self.lock, self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
stopped = db.execute(
|
||||||
|
"SELECT kind FROM operation_stops WHERE id=?", (body["id"],)
|
||||||
|
).fetchone()
|
||||||
|
if stopped:
|
||||||
|
return {
|
||||||
|
"id": body["id"],
|
||||||
|
"kind": stopped[0],
|
||||||
|
"state": "stopped",
|
||||||
|
"durable": True,
|
||||||
|
"runtime_phase": "stopped",
|
||||||
|
"stop_requested": True,
|
||||||
|
"attempt_count": 0,
|
||||||
|
}
|
||||||
|
old = db.execute(
|
||||||
|
"SELECT digest,body FROM operations WHERE id=?", (body["id"],)
|
||||||
|
).fetchone()
|
||||||
|
if old:
|
||||||
|
if old[0] != digest:
|
||||||
|
raise ValueError("idempotency conflict")
|
||||||
|
return self.public(json.loads(old[1]))
|
||||||
|
count = db.execute(
|
||||||
|
"SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')",
|
||||||
|
(body["imei"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
if count >= 32:
|
||||||
|
raise ValueError("operation queue full")
|
||||||
|
value = {
|
||||||
|
"id": body["id"],
|
||||||
|
"imei": body["imei"],
|
||||||
|
"kind": body["kind"],
|
||||||
|
"request": body,
|
||||||
|
"created_at": time.time(),
|
||||||
|
"state": "queued",
|
||||||
|
"runtime_phase": "waiting-link",
|
||||||
|
"attempt_count": 0,
|
||||||
|
"next_attempt_at": 0,
|
||||||
|
"phase": "execute",
|
||||||
|
"result": {},
|
||||||
|
}
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)",
|
||||||
|
(body["id"], body["imei"], value["state"], digest, json.dumps(value)),
|
||||||
|
)
|
||||||
|
return self.public(value)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def public(value):
|
||||||
|
result = {k: v for k, v in value.get("result", {}).items() if k in FACTS}
|
||||||
|
result.update(
|
||||||
|
{
|
||||||
|
k: value[k]
|
||||||
|
for k in (
|
||||||
|
"id",
|
||||||
|
"kind",
|
||||||
|
"state",
|
||||||
|
"created_at",
|
||||||
|
"attempt_count",
|
||||||
|
"runtime_phase",
|
||||||
|
"next_attempt_at",
|
||||||
|
"stop_requested",
|
||||||
|
"reason",
|
||||||
|
)
|
||||||
|
if k in value
|
||||||
|
}
|
||||||
|
)
|
||||||
|
result["durable"] = True
|
||||||
|
if value.get("attempt"):
|
||||||
|
result["attempt_id"] = value["attempt"]["id"]
|
||||||
|
result["attempt_expires_at"] = value["attempt"]["not_after"]
|
||||||
|
return result
|
||||||
|
|
||||||
|
def pending(self, imei):
|
||||||
|
with self.store.db() as db:
|
||||||
|
return (
|
||||||
|
db.execute(
|
||||||
|
"SELECT 1 FROM operations WHERE imei=? AND state IN "
|
||||||
|
"('queued','dispatched') LIMIT 1",
|
||||||
|
(imei,),
|
||||||
|
).fetchone()
|
||||||
|
is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
def fresh(self, imei):
|
||||||
|
return any(
|
||||||
|
0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30
|
||||||
|
for s in tuple(self.commands.sessions.get(imei, ()))
|
||||||
|
)
|
||||||
|
|
||||||
|
def wait_delay(self, imei):
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT body FROM operations WHERE imei=? AND state IN "
|
||||||
|
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
||||||
|
(imei,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
value = json.loads(row[0])
|
||||||
|
if value.get("attempt"):
|
||||||
|
return 1
|
||||||
|
return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None
|
||||||
|
|
||||||
|
def get(self, identifier):
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
with self.store.db() as db:
|
||||||
|
stopped = db.execute(
|
||||||
|
"SELECT kind FROM operation_stops WHERE id=?", (identifier,)
|
||||||
|
).fetchone()
|
||||||
|
if stopped:
|
||||||
|
return {
|
||||||
|
"id": identifier,
|
||||||
|
"kind": stopped[0],
|
||||||
|
"state": "stopped",
|
||||||
|
"durable": True,
|
||||||
|
"runtime_phase": "stopped",
|
||||||
|
"stop_requested": True,
|
||||||
|
"attempt_count": 0,
|
||||||
|
}
|
||||||
|
raise ValueError("unknown operation")
|
||||||
|
self.advance(json.loads(row[0])["imei"])
|
||||||
|
with self.store.db() as db:
|
||||||
|
value = json.loads(
|
||||||
|
db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0]
|
||||||
|
)
|
||||||
|
result = self.public(value)
|
||||||
|
attempt = value.get("attempt", value.get("result", {})).get("id")
|
||||||
|
if attempt:
|
||||||
|
result["transport"] = self.commands.transport.read(db, attempt)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def cancel(self, identifier, kind=None):
|
||||||
|
if not re.fullmatch(r"[a-f0-9]{32}", identifier):
|
||||||
|
raise ValueError("invalid operation identity")
|
||||||
|
with self.lock, self.store.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
if kind not in KINDS:
|
||||||
|
raise ValueError("unknown operation")
|
||||||
|
db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind))
|
||||||
|
return {
|
||||||
|
"id": identifier,
|
||||||
|
"kind": kind,
|
||||||
|
"state": "stopped",
|
||||||
|
"durable": True,
|
||||||
|
"runtime_phase": "stopped",
|
||||||
|
"stop_requested": True,
|
||||||
|
"attempt_count": 0,
|
||||||
|
}
|
||||||
|
value = json.loads(row[0])
|
||||||
|
if value["state"] in PENDING:
|
||||||
|
value["stop_requested"] = True
|
||||||
|
if not value.get("attempt"):
|
||||||
|
value.update(state="stopped", runtime_phase="stopped")
|
||||||
|
db.execute(
|
||||||
|
"UPDATE operations SET state=?,body=? WHERE id=?",
|
||||||
|
(value["state"], json.dumps(value), identifier),
|
||||||
|
)
|
||||||
|
return self.get(identifier)
|
||||||
|
|
||||||
|
def history(self, identifier, before=2**63 - 1):
|
||||||
|
with self.store.db() as db:
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT number,body FROM operation_attempts WHERE operation=? "
|
||||||
|
"AND number<? ORDER BY number DESC LIMIT 21",
|
||||||
|
(identifier, before),
|
||||||
|
).fetchall()
|
||||||
|
items = [json.loads(r[1]) for r in rows[:20]]
|
||||||
|
for item in items:
|
||||||
|
# Transport observations may be persisted just after the device
|
||||||
|
# reply already completed this attempt. Read their current facts.
|
||||||
|
item["transport"] = self.commands.transport.read(db, item["id"])
|
||||||
|
return {
|
||||||
|
"items": items,
|
||||||
|
"next_before": rows[19][0] if len(rows) > 20 else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def note_attempt(self, value, result):
|
||||||
|
item = {k: result[k] for k in FACTS - {"configuration"} if k in result}
|
||||||
|
item.update(
|
||||||
|
id=value["attempt"]["id"],
|
||||||
|
number=value["attempt_count"],
|
||||||
|
phase=value["phase"],
|
||||||
|
state=result["state"],
|
||||||
|
)
|
||||||
|
with self.store.db() as db:
|
||||||
|
old = db.execute(
|
||||||
|
"SELECT body FROM operation_attempts WHERE id=?", (item["id"],)
|
||||||
|
).fetchone()
|
||||||
|
if old:
|
||||||
|
previous = json.loads(old[0])
|
||||||
|
previous.pop("observed_at", None)
|
||||||
|
if previous == item:
|
||||||
|
return
|
||||||
|
item["observed_at"] = time.time()
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) "
|
||||||
|
"DO UPDATE SET body=excluded.body",
|
||||||
|
(value["id"], value["attempt_count"], item["id"], json.dumps(item)),
|
||||||
|
)
|
||||||
|
|
||||||
|
def observe(self, imei, raw):
|
||||||
|
offset = 2
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||||
|
payload = raw[offset + 7 : offset + 7 + size]
|
||||||
|
if raw[offset] == 1 and 0 <= time.time() - measured <= 30:
|
||||||
|
for index in range(0, len(payload) - 4, 5):
|
||||||
|
if payload[index] != 99:
|
||||||
|
continue
|
||||||
|
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
|
||||||
|
value = {
|
||||||
|
"active_sim": 1 + ((ds2 >> 5) & 1),
|
||||||
|
"gprs": (ds2 >> 2) & 7,
|
||||||
|
"measured_at": measured,
|
||||||
|
}
|
||||||
|
with self.store.db() as db:
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) "
|
||||||
|
"DO UPDATE SET body=excluded.body WHERE "
|
||||||
|
"json_extract(excluded.body, '$.measured_at') >= "
|
||||||
|
"json_extract(operation_modem.body, '$.measured_at')",
|
||||||
|
(imei, json.dumps(value)),
|
||||||
|
)
|
||||||
|
offset += size + 8
|
||||||
|
|
||||||
|
def selected(self, value):
|
||||||
|
if (
|
||||||
|
self.commands.sim_guard.check(
|
||||||
|
value["imei"], value["request"].get("sim_guard"), after=value["created_at"]
|
||||||
|
)
|
||||||
|
!= "matched"
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT body FROM operation_modem WHERE imei=?", (value["imei"],)
|
||||||
|
).fetchone()
|
||||||
|
data = json.loads(row[0]) if row else {}
|
||||||
|
return (
|
||||||
|
data
|
||||||
|
if sim_selection.matches(value["request"], data.get("active_sim"))
|
||||||
|
and data.get("gprs") == 4
|
||||||
|
and data.get("measured_at", 0) > value["created_at"]
|
||||||
|
and 0 <= time.time() - data["measured_at"] <= 30
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
def reconcile(self, value, result):
|
||||||
|
request = value["request"]
|
||||||
|
digest = result.get("configuration_sha256")
|
||||||
|
target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest()
|
||||||
|
if digest == target:
|
||||||
|
if value["kind"] == "configure-all":
|
||||||
|
value.update(state="verified", runtime_phase="complete", result=result)
|
||||||
|
elif selected := self.selected(value):
|
||||||
|
value.update(
|
||||||
|
state="sim_selected",
|
||||||
|
runtime_phase="complete",
|
||||||
|
result={
|
||||||
|
**result,
|
||||||
|
"active_sim": selected["active_sim"],
|
||||||
|
"telemetry_measured_at": selected["measured_at"],
|
||||||
|
"sim_guard_verified": bool(request.get("sim_guard")),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
value.update(phase="execute", retry_predecessor=target)
|
||||||
|
elif digest == request["expected_sha256"]:
|
||||||
|
value.update(phase="execute", retry_predecessor=digest)
|
||||||
|
else:
|
||||||
|
value.update(
|
||||||
|
state="rejected",
|
||||||
|
reason="configuration_conflict",
|
||||||
|
runtime_phase="complete",
|
||||||
|
result=result,
|
||||||
|
)
|
||||||
|
|
||||||
|
def advance(self, imei):
|
||||||
|
with self.lock:
|
||||||
|
with self.store.db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT body FROM operations WHERE imei=? AND state IN "
|
||||||
|
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
||||||
|
(imei,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return
|
||||||
|
value = json.loads(row[0])
|
||||||
|
if not self.store.admitted(imei):
|
||||||
|
value.update(state="rejected", reason="device_revoked", runtime_phase="complete")
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
if value.get("attempt"):
|
||||||
|
# Idempotent submission covers a crash before/after attempt admission.
|
||||||
|
# Read first: the accepted attempt may have completed while Core was away.
|
||||||
|
try:
|
||||||
|
result = self.commands.get(value["attempt"]["id"])
|
||||||
|
except ValueError:
|
||||||
|
if value.get("stop_requested"):
|
||||||
|
value.pop("attempt", None)
|
||||||
|
value.update(state="stopped", runtime_phase="stopped")
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
result = self.commands.submit(value["attempt"])
|
||||||
|
except ValueError:
|
||||||
|
return # A legacy operation/session admission still owns the channel.
|
||||||
|
value["result"] = result
|
||||||
|
self.note_attempt(value, result)
|
||||||
|
if result["state"] in PENDING:
|
||||||
|
value.update(
|
||||||
|
state=result["state"],
|
||||||
|
runtime_phase="checking-result"
|
||||||
|
if value["phase"] == "inspect"
|
||||||
|
else "executing",
|
||||||
|
)
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
if value["phase"] == "inspect" and result["state"] == "observed":
|
||||||
|
self.reconcile(value, result)
|
||||||
|
elif result["state"] in {
|
||||||
|
"device_confirmed",
|
||||||
|
"observed",
|
||||||
|
"verified",
|
||||||
|
"sim_selected",
|
||||||
|
"reconnected",
|
||||||
|
}:
|
||||||
|
value.update(state=result["state"], runtime_phase="complete")
|
||||||
|
elif (
|
||||||
|
value["kind"] == "restart"
|
||||||
|
and result.get("device_code") == 0
|
||||||
|
and result.get("device_accepted_at")
|
||||||
|
):
|
||||||
|
value.update(state="accepted", runtime_phase="complete")
|
||||||
|
elif (
|
||||||
|
result["state"] in RETRY
|
||||||
|
or result.get("device_code") == 7
|
||||||
|
or result.get("reason") == "configuration_predecessor_mismatch"
|
||||||
|
):
|
||||||
|
if value["kind"] in {"configure-all", "select-sim"}:
|
||||||
|
value["phase"] = "inspect"
|
||||||
|
else:
|
||||||
|
value.update(state=result["state"], runtime_phase="complete")
|
||||||
|
if result.get("reason") == "sim_card_changed":
|
||||||
|
value["reason"] = "sim_card_changed"
|
||||||
|
value.pop("attempt", None)
|
||||||
|
if value["state"] in PENDING:
|
||||||
|
value.update(
|
||||||
|
state="stopped" if value.get("stop_requested") else "queued",
|
||||||
|
runtime_phase="stopped" if value.get("stop_requested") else "retry-wait",
|
||||||
|
next_attempt_at=time.time()
|
||||||
|
+ min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)),
|
||||||
|
)
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
if value.get("stop_requested"):
|
||||||
|
value.update(state="stopped", runtime_phase="stopped")
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
if value["next_attempt_at"] > time.time():
|
||||||
|
return
|
||||||
|
if not self.fresh(imei):
|
||||||
|
if value["runtime_phase"] != "waiting-link":
|
||||||
|
value.update(runtime_phase="waiting-link")
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
if value["phase"] == "execute" and value["request"].get("sim_guard"):
|
||||||
|
guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"])
|
||||||
|
if guard != "matched":
|
||||||
|
if guard == "changed":
|
||||||
|
value.update(
|
||||||
|
state="rejected", runtime_phase="complete", reason="sim_card_changed"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
value.update(runtime_phase="waiting-identity")
|
||||||
|
self.save(value)
|
||||||
|
return
|
||||||
|
attempt = {**value["request"], "id": uuid.uuid4().hex}
|
||||||
|
if value["phase"] == "inspect":
|
||||||
|
attempt = {
|
||||||
|
k: v
|
||||||
|
for k, v in attempt.items()
|
||||||
|
if k in {"id", "imei", "password", "model", "firmware"}
|
||||||
|
}
|
||||||
|
attempt["kind"] = "read-configuration"
|
||||||
|
elif value.get("retry_predecessor"):
|
||||||
|
attempt["expected_sha256"] = value["retry_predecessor"]
|
||||||
|
lifetime = (
|
||||||
|
360
|
||||||
|
if attempt["kind"] == "select-sim"
|
||||||
|
else 30
|
||||||
|
if attempt["kind"] == "request-position"
|
||||||
|
else 180
|
||||||
|
)
|
||||||
|
attempt["not_after"] = time.time() + lifetime
|
||||||
|
value.update(
|
||||||
|
attempt=attempt,
|
||||||
|
attempt_count=value["attempt_count"] + 1,
|
||||||
|
result={},
|
||||||
|
runtime_phase="checking-result" if value["phase"] == "inspect" else "executing",
|
||||||
|
)
|
||||||
|
# The plan is durable before the attempt's separate transaction.
|
||||||
|
self.save(value)
|
||||||
|
self.advance(imei)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Observe return after a restart request without claiming CPU/power-cycle proof."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def observe(value, raw, session, started):
|
||||||
|
if (
|
||||||
|
value.get("kind") != "restart"
|
||||||
|
or value["state"] != "dispatched"
|
||||||
|
or value["expires_at"] < time.time()
|
||||||
|
or session in value["restart_sessions"]
|
||||||
|
or started <= value["monotonic"]
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
# Only type-1 telemetry measured after dispatch establishes fresh return.
|
||||||
|
# A new header, old archive, text reply or token ACK cannot complete this.
|
||||||
|
offset = 2
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||||
|
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
|
||||||
|
value.update(
|
||||||
|
state="reconnected",
|
||||||
|
reconnected_at=time.time(),
|
||||||
|
reconnect_seconds=time.monotonic() - value["monotonic"],
|
||||||
|
telemetry_measured_at=measured,
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
offset += size + 8
|
||||||
|
return False
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from contextlib import suppress
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
|
from . import arnavi
|
||||||
|
from .commands import COMMAND_SESSION_MAX_IDLE, Commands
|
||||||
|
from .delivery import Delivery
|
||||||
|
from .observation import Observation, http_body
|
||||||
|
from .operations import Operations
|
||||||
|
|
||||||
|
|
||||||
|
class Service:
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
self.connections = 0
|
||||||
|
self.commands = Commands(store)
|
||||||
|
self.operations = Operations(store, self.commands)
|
||||||
|
self.observation = Observation(store)
|
||||||
|
self.wake = {}
|
||||||
|
|
||||||
|
async def tracker(self, reader, writer):
|
||||||
|
self.connections += 1
|
||||||
|
session = uuid.uuid4().hex
|
||||||
|
sender = None
|
||||||
|
delivery = None
|
||||||
|
imei = None
|
||||||
|
try:
|
||||||
|
if self.connections > 256:
|
||||||
|
return
|
||||||
|
async with asyncio.timeout(10):
|
||||||
|
header = await reader.readexactly(10)
|
||||||
|
if header[:2] != b"\xff\x23":
|
||||||
|
if (
|
||||||
|
not await self.observe_configuration(reader, header, writer)
|
||||||
|
and header == b"POST /c/in"
|
||||||
|
):
|
||||||
|
delivery = Delivery(writer)
|
||||||
|
await self.configuration_http(reader, writer, header, delivery)
|
||||||
|
return
|
||||||
|
imei = arnavi.identity(header)
|
||||||
|
if not await asyncio.to_thread(self.store.admitted, imei):
|
||||||
|
return
|
||||||
|
delivery = Delivery(writer)
|
||||||
|
self.commands.sessions.setdefault(imei, set()).add(session)
|
||||||
|
self.commands.session_started[imei, session] = time.monotonic()
|
||||||
|
self.commands.session_activity[imei, session] = time.monotonic()
|
||||||
|
self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0]
|
||||||
|
self.commands.session_ready[imei, session] = False
|
||||||
|
delivery.write(arnavi.header_ack(int(time.time())))
|
||||||
|
await writer.drain()
|
||||||
|
sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery))
|
||||||
|
buffer = b""
|
||||||
|
while True:
|
||||||
|
async with asyncio.timeout(180):
|
||||||
|
chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer)))
|
||||||
|
if not chunk:
|
||||||
|
return
|
||||||
|
buffer += chunk
|
||||||
|
while buffer:
|
||||||
|
parsed = arnavi.parse_package(buffer)
|
||||||
|
if parsed is None:
|
||||||
|
break
|
||||||
|
length, packets = parsed
|
||||||
|
self.commands.session_activity[imei, session] = time.monotonic()
|
||||||
|
await asyncio.to_thread(
|
||||||
|
self.accept_package, imei, buffer[:length], packets, session
|
||||||
|
)
|
||||||
|
self.notify(imei)
|
||||||
|
delivery.write(arnavi.package_ack(buffer[1]))
|
||||||
|
await writer.drain()
|
||||||
|
buffer = buffer[length:]
|
||||||
|
except (
|
||||||
|
ValueError,
|
||||||
|
KeyError,
|
||||||
|
OSError,
|
||||||
|
sqlite3.Error,
|
||||||
|
TimeoutError,
|
||||||
|
asyncio.IncompleteReadError,
|
||||||
|
asyncio.LimitOverrunError,
|
||||||
|
):
|
||||||
|
pass # Deliberately no raw identity/data/credentials in logs.
|
||||||
|
finally:
|
||||||
|
if imei:
|
||||||
|
self.commands.sessions.get(imei, set()).discard(session)
|
||||||
|
self.commands.session_started.pop((imei, session), None)
|
||||||
|
self.commands.session_activity.pop((imei, session), None)
|
||||||
|
self.commands.session_peers.pop((imei, session), None)
|
||||||
|
self.commands.session_ready.pop((imei, session), None)
|
||||||
|
if not self.commands.sessions.get(imei):
|
||||||
|
self.commands.sessions.pop(imei, None)
|
||||||
|
if sender:
|
||||||
|
sender.cancel()
|
||||||
|
await asyncio.gather(sender, return_exceptions=True)
|
||||||
|
self.connections -= 1
|
||||||
|
if delivery:
|
||||||
|
delivery.abort()
|
||||||
|
else:
|
||||||
|
writer.close()
|
||||||
|
|
||||||
|
def accept_package(self, imei, raw, packets, session):
|
||||||
|
# Core may fetch/ack packages concurrently. Publish the packet and its
|
||||||
|
# command evidence together before either Core or B2 can consume it.
|
||||||
|
with self.store.packet_transaction():
|
||||||
|
self.store.append(imei, raw, packets)
|
||||||
|
self.commands.receive(imei, raw, session)
|
||||||
|
self.operations.observe(imei, raw)
|
||||||
|
|
||||||
|
async def observe_configuration(self, reader, header, writer=None):
|
||||||
|
ticket = await asyncio.to_thread(self.observation.claim)
|
||||||
|
if ticket is None:
|
||||||
|
return False
|
||||||
|
raw = bytearray(header)
|
||||||
|
events = [
|
||||||
|
{"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()}
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(8):
|
||||||
|
while len(raw) < 16384:
|
||||||
|
chunk = await reader.read(min(4096, 16384 - len(raw)))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
events.append(
|
||||||
|
{
|
||||||
|
"offset": len(raw),
|
||||||
|
"bytes": len(chunk),
|
||||||
|
"at": time.time(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
raw.extend(chunk)
|
||||||
|
if writer is not None:
|
||||||
|
reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw))
|
||||||
|
if reply is not None:
|
||||||
|
writer.write(
|
||||||
|
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||||
|
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||||
|
+ b"Connection: keep-alive\r\n\r\n"
|
||||||
|
+ reply
|
||||||
|
)
|
||||||
|
await writer.drain()
|
||||||
|
except (TimeoutError, OSError):
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events)
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def configuration_http(self, reader, writer, initial, delivery):
|
||||||
|
if initial != b"POST /c/in":
|
||||||
|
return
|
||||||
|
peer = writer.get_extra_info("peername")[0]
|
||||||
|
for _ in range(8):
|
||||||
|
async with asyncio.timeout(12):
|
||||||
|
header = initial + await reader.readuntil(b"\r\n\r\n")
|
||||||
|
initial = b""
|
||||||
|
if len(header) > 2048:
|
||||||
|
return
|
||||||
|
lengths = [
|
||||||
|
line.split(b":", 1)[1].strip()
|
||||||
|
for line in header.split(b"\r\n")
|
||||||
|
if line.lower().startswith(b"content-length:")
|
||||||
|
]
|
||||||
|
if len(lengths) != 1 or not lengths[0].isdigit():
|
||||||
|
return
|
||||||
|
size = int(lengths[0])
|
||||||
|
if not 20 <= size <= 16384:
|
||||||
|
return
|
||||||
|
body = http_body(header + await reader.readexactly(size))
|
||||||
|
if body is None:
|
||||||
|
return
|
||||||
|
response = await asyncio.to_thread(
|
||||||
|
self.commands.web_receive, body, peer, with_deadline=True
|
||||||
|
)
|
||||||
|
self.notify(str(int.from_bytes(body[4:12], "little")))
|
||||||
|
if response is None:
|
||||||
|
return
|
||||||
|
reply, deadline = response
|
||||||
|
delivery.write(
|
||||||
|
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||||
|
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||||
|
+ b"Connection: keep-alive\r\n\r\n"
|
||||||
|
+ reply,
|
||||||
|
deadline,
|
||||||
|
)
|
||||||
|
await writer.drain()
|
||||||
|
|
||||||
|
async def send_commands(self, imei, writer, session, delivery):
|
||||||
|
event = asyncio.Event()
|
||||||
|
observations = []
|
||||||
|
|
||||||
|
def observe(ticket, phase, at, elapsed, reason):
|
||||||
|
# The socket timer never opens SQLite or waits for filesystem I/O.
|
||||||
|
observations.append((ticket, phase, at, elapsed, reason))
|
||||||
|
event.set()
|
||||||
|
|
||||||
|
async def persist():
|
||||||
|
if observations:
|
||||||
|
batch = observations[:]
|
||||||
|
observations.clear()
|
||||||
|
commit = asyncio.create_task(
|
||||||
|
asyncio.to_thread(self.commands.transport.record, batch)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await asyncio.shield(commit)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
# EOF cancels this sender. Finish the extracted batch before
|
||||||
|
# the finally block records closure of its remaining bytes.
|
||||||
|
await commit
|
||||||
|
raise
|
||||||
|
|
||||||
|
self.wake.setdefault(imei, set()).add(event)
|
||||||
|
try:
|
||||||
|
while not writer.is_closing():
|
||||||
|
event.clear()
|
||||||
|
await persist()
|
||||||
|
last_input = self.commands.session_activity.get((imei, session))
|
||||||
|
self.commands.session_ready[imei, session] = (
|
||||||
|
delivery.ready()
|
||||||
|
and last_input is not None
|
||||||
|
and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
|
||||||
|
)
|
||||||
|
await asyncio.to_thread(self.operations.advance, imei)
|
||||||
|
dispatch = await asyncio.to_thread(
|
||||||
|
self.commands.take_delivery, imei, session, with_receipt=True
|
||||||
|
)
|
||||||
|
if dispatch:
|
||||||
|
data, deadline, ticket = dispatch
|
||||||
|
delivery.write(
|
||||||
|
data,
|
||||||
|
deadline,
|
||||||
|
lambda phase, at, elapsed, reason, ticket=ticket: observe(
|
||||||
|
ticket, phase, at, elapsed, reason
|
||||||
|
),
|
||||||
|
)
|
||||||
|
await writer.drain()
|
||||||
|
await persist()
|
||||||
|
delay = await asyncio.to_thread(self.commands.wait_delay, imei)
|
||||||
|
operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei)
|
||||||
|
delay = (
|
||||||
|
min(d for d in (delay, operation_delay) if d is not None)
|
||||||
|
if (delay is not None or operation_delay is not None)
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
with suppress(TimeoutError):
|
||||||
|
await asyncio.wait_for(event.wait(), delay)
|
||||||
|
finally:
|
||||||
|
self.wake.get(imei, set()).discard(event)
|
||||||
|
if not self.wake.get(imei):
|
||||||
|
self.wake.pop(imei, None)
|
||||||
|
delivery.abort()
|
||||||
|
await persist()
|
||||||
|
|
||||||
|
def notify(self, imei):
|
||||||
|
for event in self.wake.get(imei, ()):
|
||||||
|
event.set()
|
||||||
|
|
||||||
|
async def api(self, reader, writer):
|
||||||
|
status, value = 400, {"error": "invalid_request"}
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout(15):
|
||||||
|
header = await reader.readuntil(b"\r\n\r\n")
|
||||||
|
if len(header) > 8192:
|
||||||
|
raise ValueError
|
||||||
|
lines = header.decode("ascii").split("\r\n")
|
||||||
|
method, target, _ = lines[0].split(" ")
|
||||||
|
headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line)
|
||||||
|
size = int(headers.get("content-length", "0"))
|
||||||
|
if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers:
|
||||||
|
raise ValueError
|
||||||
|
payload = await reader.readexactly(size) if size else b"{}"
|
||||||
|
body = json.loads(payload)
|
||||||
|
route = urlsplit(target)
|
||||||
|
token = headers.get("authorization", "").removeprefix("bearer ")
|
||||||
|
# Header values must retain case for bearer credentials.
|
||||||
|
for line in lines[1:]:
|
||||||
|
if line.lower().startswith("authorization: bearer "):
|
||||||
|
token = line[len("authorization: bearer ") :]
|
||||||
|
if method == "GET" and route.path == "/health":
|
||||||
|
value = {"ok": True, "service": "ndc-mission-vps-host"}
|
||||||
|
elif method == "POST" and route.path == "/v1/pair":
|
||||||
|
value = await asyncio.to_thread(self.store.pair, body)
|
||||||
|
else:
|
||||||
|
if not await asyncio.to_thread(self.store.authorize, token):
|
||||||
|
raise PermissionError
|
||||||
|
if method == "GET" and route.path == "/v1/status":
|
||||||
|
value = await asyncio.to_thread(self.store.status)
|
||||||
|
elif method == "PUT" and route.path == "/v1/devices":
|
||||||
|
await asyncio.to_thread(self.store.set_devices, body["items"])
|
||||||
|
value = {"ok": True}
|
||||||
|
elif method == "GET" and route.path == "/v1/packets":
|
||||||
|
after = int(parse_qs(route.query).get("after", ["0"])[0])
|
||||||
|
value = await asyncio.to_thread(self.store.fetch, max(0, after))
|
||||||
|
elif method == "POST" and route.path == "/v1/commands":
|
||||||
|
if await asyncio.to_thread(self.operations.pending, body["imei"]):
|
||||||
|
raise ValueError("durable operation owns device queue")
|
||||||
|
value = await asyncio.to_thread(self.commands.submit, body)
|
||||||
|
self.notify(body["imei"])
|
||||||
|
elif method == "POST" and route.path == "/v1/operations":
|
||||||
|
value = await asyncio.to_thread(self.operations.submit, body)
|
||||||
|
self.notify(body["imei"])
|
||||||
|
elif (
|
||||||
|
method == "POST"
|
||||||
|
and route.path.startswith("/v1/operations/")
|
||||||
|
and route.path.endswith("/cancel")
|
||||||
|
):
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.operations.cancel, route.path.split("/")[-2], body.get("kind")
|
||||||
|
)
|
||||||
|
elif (
|
||||||
|
method == "GET"
|
||||||
|
and route.path.startswith("/v1/operations/")
|
||||||
|
and route.path.endswith("/attempts")
|
||||||
|
):
|
||||||
|
before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0])
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.operations.history, route.path.split("/")[-2], before
|
||||||
|
)
|
||||||
|
elif method == "GET" and route.path.startswith("/v1/operations/"):
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.operations.get, route.path.rsplit("/", 1)[1]
|
||||||
|
)
|
||||||
|
elif method == "POST" and route.path == "/v1/configuration-observations":
|
||||||
|
value = await asyncio.to_thread(self.observation.arm, body)
|
||||||
|
elif (
|
||||||
|
method == "POST"
|
||||||
|
and route.path.startswith("/v1/configuration-observations/")
|
||||||
|
and route.path.endswith("/close")
|
||||||
|
):
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.observation.close, route.path.split("/")[-2]
|
||||||
|
)
|
||||||
|
elif method == "GET" and route.path.startswith(
|
||||||
|
"/v1/configuration-observations/"
|
||||||
|
):
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.observation.get, route.path.rsplit("/", 1)[1]
|
||||||
|
)
|
||||||
|
elif method == "GET" and route.path.startswith("/v1/commands/"):
|
||||||
|
value = await asyncio.to_thread(
|
||||||
|
self.commands.get, route.path.rsplit("/", 1)[1]
|
||||||
|
)
|
||||||
|
elif method == "POST" and route.path == "/v1/ack":
|
||||||
|
if type(body["through"]) is not int or body["through"] < 0:
|
||||||
|
raise ValueError
|
||||||
|
await asyncio.to_thread(self.store.acknowledge, body["through"])
|
||||||
|
value = {"ok": True}
|
||||||
|
else:
|
||||||
|
raise ValueError
|
||||||
|
status = 200
|
||||||
|
except PermissionError:
|
||||||
|
status, value = 403, {"error": "not_authorized"}
|
||||||
|
except (
|
||||||
|
ValueError,
|
||||||
|
KeyError,
|
||||||
|
TypeError,
|
||||||
|
UnicodeError,
|
||||||
|
asyncio.IncompleteReadError,
|
||||||
|
asyncio.LimitOverrunError,
|
||||||
|
TimeoutError,
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
except (OSError, sqlite3.Error):
|
||||||
|
status, value = 503, {"error": "storage_unavailable"}
|
||||||
|
try:
|
||||||
|
payload = json.dumps(value).encode()
|
||||||
|
writer.write(
|
||||||
|
(
|
||||||
|
f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n"
|
||||||
|
f"Content-Length: {len(payload)}\r\nConnection: close\r\n"
|
||||||
|
"Cache-Control: no-store\r\n\r\n"
|
||||||
|
).encode()
|
||||||
|
+ payload
|
||||||
|
)
|
||||||
|
await writer.drain()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
writer.close()
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
tls.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||||
|
tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key")
|
||||||
|
api = await asyncio.start_server(
|
||||||
|
self.api,
|
||||||
|
"0.0.0.0",
|
||||||
|
self.store.config["api_port"],
|
||||||
|
ssl=tls,
|
||||||
|
ssl_handshake_timeout=8,
|
||||||
|
limit=8192,
|
||||||
|
)
|
||||||
|
tracker = await asyncio.start_server(
|
||||||
|
self.tracker, "0.0.0.0", self.store.config["tracker"]["port"]
|
||||||
|
)
|
||||||
|
async with api, tracker:
|
||||||
|
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Durable firmware SID bindings, checked at the last configuration write boundary."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .sim_network import binding, decode_pairs, merge
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(value):
|
||||||
|
if (
|
||||||
|
not isinstance(value, dict)
|
||||||
|
or set(value) != {"slot", "sid"}
|
||||||
|
or type(value["slot"]) is not int
|
||||||
|
or value["slot"] not in (1, 2)
|
||||||
|
or not isinstance(value["sid"], str)
|
||||||
|
or not re.fullmatch(r"89[0-9]{18}", value["sid"])
|
||||||
|
):
|
||||||
|
raise ValueError("invalid SIM identity guard")
|
||||||
|
return dict(value)
|
||||||
|
|
||||||
|
|
||||||
|
class SimGuard:
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
with store.db() as db:
|
||||||
|
db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS sim_bindings(imei TEXT PRIMARY KEY,body TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
|
||||||
|
def observe(self, imei, raw):
|
||||||
|
# Called only for validated INTERNAL frames in the packet commit transaction.
|
||||||
|
with self.store.db(write=True) as db:
|
||||||
|
old = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
|
||||||
|
value = json.loads(old[0]) if old else None
|
||||||
|
offset, now = 2, time.time()
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||||
|
payload = raw[offset + 7 : offset + 7 + size]
|
||||||
|
if raw[offset] == 1:
|
||||||
|
tags = {}
|
||||||
|
for i in range(0, len(payload) - 4, 5):
|
||||||
|
tags.setdefault(payload[i], set()).add(payload[i + 1 : i + 5])
|
||||||
|
status = {}
|
||||||
|
if len(tags.get(99, ())) == 1:
|
||||||
|
ds = int.from_bytes(next(iter(tags[99])), "little")
|
||||||
|
status = {"sim_states": {"1": (ds >> 6) & 7, "2": (ds >> 9) & 7}}
|
||||||
|
value = merge(
|
||||||
|
value,
|
||||||
|
{
|
||||||
|
"measured_at": measured,
|
||||||
|
"cellular": {"status": status},
|
||||||
|
"sim_identifiers": decode_pairs(tags),
|
||||||
|
},
|
||||||
|
host_id="local",
|
||||||
|
sequence=0,
|
||||||
|
received=now,
|
||||||
|
tracker=imei,
|
||||||
|
)
|
||||||
|
offset += size + 8
|
||||||
|
if value:
|
||||||
|
db.execute(
|
||||||
|
"INSERT OR REPLACE INTO sim_bindings VALUES(?,?)", (imei, json.dumps(value))
|
||||||
|
)
|
||||||
|
|
||||||
|
def check(self, imei, guard, *, after=None, db=None):
|
||||||
|
if guard is None:
|
||||||
|
return "matched"
|
||||||
|
if db is None:
|
||||||
|
with self.store.db() as connection:
|
||||||
|
return self.check(imei, guard, after=after, db=connection)
|
||||||
|
row = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
|
||||||
|
value = json.loads(row[0]) if row else None
|
||||||
|
sid = binding(value, str(guard["slot"]), now=time.time())
|
||||||
|
if sid is None:
|
||||||
|
return "waiting"
|
||||||
|
if sid != guard["sid"]:
|
||||||
|
return "changed"
|
||||||
|
observed = value["slots"][str(guard["slot"])]["observation"]
|
||||||
|
if after is not None and observed["measured_at"] <= after:
|
||||||
|
return "waiting"
|
||||||
|
return "matched"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""SIM permissions: verified flags, one restart, fresh modem evidence."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import actions
|
||||||
|
|
||||||
|
|
||||||
|
def matches(value, slot):
|
||||||
|
return (
|
||||||
|
type(slot) is int
|
||||||
|
and slot in (1, 2)
|
||||||
|
and (value.get("sim_policy") == "both" or slot == value.get("sim_slot"))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def queue_restart(value):
|
||||||
|
value.update(actions.prepare({"kind": "restart", "model": 231, "firmware": "0.01"}))
|
||||||
|
value.update(stage="restart", state="queued", not_before=time.time())
|
||||||
|
value.pop("session", None)
|
||||||
|
|
||||||
|
|
||||||
|
def observe(value, raw, session, started):
|
||||||
|
if (
|
||||||
|
value.get("kind") != "select-sim"
|
||||||
|
or value.get("stage") != "restart"
|
||||||
|
or value["state"] != "dispatched"
|
||||||
|
or value["expires_at"] <= time.time()
|
||||||
|
or session in value["restart_sessions"]
|
||||||
|
or started <= value["monotonic"]
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
# Validated INTERNAL packages only. ACKs, archives, old sockets, old and
|
||||||
|
# future measurements, and GPRS on the wrong SIM cannot confirm selection.
|
||||||
|
offset = 2
|
||||||
|
while offset < len(raw) - 1:
|
||||||
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||||
|
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||||
|
payload = raw[offset + 7 : offset + 7 + size]
|
||||||
|
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
|
||||||
|
for index in range(0, len(payload) - 4, 5):
|
||||||
|
if payload[index] != 99:
|
||||||
|
continue
|
||||||
|
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
|
||||||
|
slot = 1 + ((ds2 >> 5) & 1)
|
||||||
|
if matches(value, slot) and (ds2 >> 2) & 7 == 4:
|
||||||
|
value.update(
|
||||||
|
state="sim_selected",
|
||||||
|
active_sim=slot,
|
||||||
|
verified_at=time.time(),
|
||||||
|
telemetry_measured_at=measured,
|
||||||
|
reconnect_seconds=time.monotonic() - value["monotonic"],
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
offset += size + 8
|
||||||
|
return False
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
"""Durable receiver journal. Acknowledgements follow SQLite FULL commits."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def private_write(path, data):
|
||||||
|
temporary = path.with_name(path.name + ".new")
|
||||||
|
with open(temporary, "wb") as stream:
|
||||||
|
os.chmod(temporary, 0o600)
|
||||||
|
stream.write(data)
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
os.replace(temporary, path)
|
||||||
|
fd = os.open(path.parent, os.O_RDONLY)
|
||||||
|
try:
|
||||||
|
os.fsync(fd)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self, root):
|
||||||
|
self.root = Path(root)
|
||||||
|
self.config = json.loads((self.root / "host.json").read_text())
|
||||||
|
self.path = self.root / "journal.sqlite3"
|
||||||
|
self._packet = threading.local()
|
||||||
|
with self.db() as db:
|
||||||
|
db.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS devices(imei TEXT PRIMARY KEY, instance TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS device_ids(
|
||||||
|
imei TEXT PRIMARY KEY, number INTEGER NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS packages(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
imei TEXT NOT NULL, instance TEXT NOT NULL, digest TEXT UNIQUE NOT NULL,
|
||||||
|
received REAL NOT NULL, raw BLOB NOT NULL, packets TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS receipts(digest TEXT PRIMARY KEY, at REAL NOT NULL);
|
||||||
|
""")
|
||||||
|
self.path.chmod(0o600)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def db(self, *, write=False):
|
||||||
|
# Packet consumers run together on one worker thread. No partial
|
||||||
|
# receipt or modem state may become visible to Core or the sender.
|
||||||
|
current = getattr(self._packet, "connection", None)
|
||||||
|
if current is not None:
|
||||||
|
yield current
|
||||||
|
return
|
||||||
|
connection = sqlite3.connect(self.path, timeout=10)
|
||||||
|
try:
|
||||||
|
connection.execute("PRAGMA synchronous=FULL")
|
||||||
|
with connection:
|
||||||
|
if write:
|
||||||
|
connection.execute("BEGIN IMMEDIATE")
|
||||||
|
yield connection
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def packet_transaction(self):
|
||||||
|
"""Synchronous packet ingestion only: no sockets, awaits or API work."""
|
||||||
|
if getattr(self._packet, "connection", None) is not None:
|
||||||
|
raise RuntimeError("nested packet transaction")
|
||||||
|
with self.db(write=True) as connection:
|
||||||
|
self._packet.connection = connection
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
del self._packet.connection
|
||||||
|
|
||||||
|
def invitation(self):
|
||||||
|
secret = secrets.token_urlsafe(32)
|
||||||
|
expires = int(time.time()) + 86400
|
||||||
|
with self.db() as db:
|
||||||
|
if db.execute("SELECT 1 FROM state WHERE key='owner'").fetchone():
|
||||||
|
raise ValueError("host already paired; restore its Core identity instead")
|
||||||
|
db.execute(
|
||||||
|
"INSERT OR REPLACE INTO state VALUES('invitation',?)",
|
||||||
|
(
|
||||||
|
json.dumps(
|
||||||
|
{"hash": hashlib.sha256(secret.encode()).hexdigest(), "expires_at": expires}
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
code = {
|
||||||
|
"schema": "missioncore.vps-pairing/v1",
|
||||||
|
"host_id": self.config["host_id"],
|
||||||
|
"endpoint": self.config["endpoint"],
|
||||||
|
"fingerprint": self.config["fingerprint"],
|
||||||
|
"secret": secret,
|
||||||
|
"expires_at": expires,
|
||||||
|
}
|
||||||
|
encoded = "MCV1." + base64.urlsafe_b64encode(json.dumps(code).encode()).decode().rstrip("=")
|
||||||
|
private_write(self.root / "connect.key", (encoded + "\n").encode())
|
||||||
|
|
||||||
|
def pair(self, body):
|
||||||
|
core, token, secret = body["core_id"], body["token"], body["secret"]
|
||||||
|
if not all(isinstance(v, str) and 32 <= len(v) <= 100 for v in (core, token, secret)):
|
||||||
|
raise ValueError("invalid pairing")
|
||||||
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
with self.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
current = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
|
||||||
|
if current:
|
||||||
|
owner = json.loads(current[0])
|
||||||
|
if owner["core_id"] != core or not hmac.compare_digest(owner["token"], digest):
|
||||||
|
raise PermissionError("already paired")
|
||||||
|
else:
|
||||||
|
row = db.execute("SELECT value FROM state WHERE key='invitation'").fetchone()
|
||||||
|
invite = json.loads(row[0]) if row else {}
|
||||||
|
if invite.get("expires_at", 0) <= time.time() or not hmac.compare_digest(
|
||||||
|
invite.get("hash", ""), hashlib.sha256(secret.encode()).hexdigest()
|
||||||
|
):
|
||||||
|
raise PermissionError("invalid invitation")
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO state VALUES('owner',?)",
|
||||||
|
(json.dumps({"core_id": core, "token": digest}),),
|
||||||
|
)
|
||||||
|
db.execute("DELETE FROM state WHERE key='invitation'")
|
||||||
|
private_write(
|
||||||
|
self.root / "connect.key", b"PAIRED: key consumed; use the connected Mission Core.\n"
|
||||||
|
)
|
||||||
|
return self.status()
|
||||||
|
|
||||||
|
def authorize(self, token):
|
||||||
|
with self.db() as db:
|
||||||
|
row = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
|
||||||
|
return bool(
|
||||||
|
row
|
||||||
|
and hmac.compare_digest(
|
||||||
|
json.loads(row[0])["token"], hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def status(self):
|
||||||
|
from . import VERSION
|
||||||
|
|
||||||
|
with self.db() as db:
|
||||||
|
count, latest = db.execute("SELECT COUNT(*),MAX(received) FROM packages").fetchone()
|
||||||
|
devices = db.execute("SELECT COUNT(*) FROM devices").fetchone()[0]
|
||||||
|
return {
|
||||||
|
"schema": "missioncore.vps-host/v1",
|
||||||
|
"host_id": self.config["host_id"],
|
||||||
|
"version": VERSION,
|
||||||
|
"tracker": self.config["tracker"],
|
||||||
|
"pending_packages": count,
|
||||||
|
"last_packet_at": latest,
|
||||||
|
"devices": devices,
|
||||||
|
"capabilities": [
|
||||||
|
"arnavi-b2-internal",
|
||||||
|
"arnavi-b2-durable-operations-v1",
|
||||||
|
"arnavi-b2-sim-guard-v1",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
def set_devices(self, items):
|
||||||
|
if not isinstance(items, list) or len(items) > 10000:
|
||||||
|
raise ValueError("invalid devices")
|
||||||
|
rows, identities = [], []
|
||||||
|
for item in items:
|
||||||
|
imei, instance = item["imei"], item["instance_id"]
|
||||||
|
if (
|
||||||
|
not isinstance(imei, str)
|
||||||
|
or not imei.isascii()
|
||||||
|
or not imei.isdigit()
|
||||||
|
or len(imei) != 15
|
||||||
|
):
|
||||||
|
raise ValueError("invalid identity")
|
||||||
|
if not isinstance(instance, str) or len(instance) != 32:
|
||||||
|
raise ValueError("invalid instance")
|
||||||
|
rows.append((imei, instance))
|
||||||
|
if "device_id" in item:
|
||||||
|
number = item["device_id"]
|
||||||
|
if type(number) is not int or not 1 <= number <= 0xFFFFFFFF:
|
||||||
|
raise ValueError("invalid numeric device identity")
|
||||||
|
identities.append((imei, number))
|
||||||
|
if len({r[0] for r in rows}) != len(rows):
|
||||||
|
raise ValueError("duplicate identity")
|
||||||
|
with self.db() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
for imei, number in identities:
|
||||||
|
previous = db.execute(
|
||||||
|
"SELECT number FROM device_ids WHERE imei=?", (imei,)
|
||||||
|
).fetchone()
|
||||||
|
if previous and previous[0] != number:
|
||||||
|
raise ValueError("numeric device identity conflict")
|
||||||
|
db.execute("INSERT OR IGNORE INTO device_ids VALUES(?,?)", (imei, number))
|
||||||
|
db.execute("DELETE FROM devices")
|
||||||
|
db.executemany("INSERT INTO devices VALUES(?,?)", rows)
|
||||||
|
|
||||||
|
def numeric_id(self, imei):
|
||||||
|
with self.db() as db:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT number FROM device_ids JOIN devices USING(imei) WHERE imei=?", (imei,)
|
||||||
|
).fetchone()
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
def admitted(self, imei):
|
||||||
|
with self.db() as db:
|
||||||
|
row = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
def append(self, imei, raw, packets):
|
||||||
|
# Reserve disk for system services. Refuse ACK when durable storage cannot accept data.
|
||||||
|
if os.statvfs(self.root).f_bavail * os.statvfs(self.root).f_frsize < 256 * 1024**2:
|
||||||
|
raise OSError("journal storage reserve")
|
||||||
|
digest = hashlib.sha256(imei.encode() + raw).hexdigest()
|
||||||
|
with self.db(write=True) as db:
|
||||||
|
device = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
|
||||||
|
if not device:
|
||||||
|
raise PermissionError("device not admitted")
|
||||||
|
if db.execute("SELECT 1 FROM receipts WHERE digest=?", (digest,)).fetchone():
|
||||||
|
return
|
||||||
|
# Fixed 512 MiB journal budget; backpressure, never drop unacknowledged data.
|
||||||
|
pages = db.execute("PRAGMA page_count").fetchone()[0]
|
||||||
|
free = db.execute("PRAGMA freelist_count").fetchone()[0]
|
||||||
|
page_size = db.execute("PRAGMA page_size").fetchone()[0]
|
||||||
|
if (pages - free) * page_size > 512 * 1024**2:
|
||||||
|
raise OSError("journal full")
|
||||||
|
db.execute(
|
||||||
|
"INSERT OR IGNORE INTO packages(imei,instance,digest,received,raw,packets) "
|
||||||
|
"VALUES(?,?,?,?,?,?)",
|
||||||
|
(imei, device[0], digest, time.time(), raw, json.dumps(packets)),
|
||||||
|
)
|
||||||
|
|
||||||
|
def fetch(self, after):
|
||||||
|
with self.db() as db:
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT id,instance,digest,received,raw,packets FROM packages "
|
||||||
|
"WHERE id>? ORDER BY id LIMIT 20",
|
||||||
|
(after,),
|
||||||
|
).fetchall()
|
||||||
|
return {
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": r[0],
|
||||||
|
"instance_id": r[1],
|
||||||
|
"digest": r[2],
|
||||||
|
"received_at": r[3],
|
||||||
|
"raw": base64.b64encode(r[4]).decode(),
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
def acknowledge(self, through):
|
||||||
|
with self.db() as db:
|
||||||
|
db.execute(
|
||||||
|
"INSERT OR IGNORE INTO receipts SELECT digest,received FROM packages WHERE id<=?",
|
||||||
|
(through,),
|
||||||
|
)
|
||||||
|
db.execute("DELETE FROM packages WHERE id<=?", (through,))
|
||||||
|
db.execute("DELETE FROM receipts WHERE at<?", (time.time() - 7 * 86400,))
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Private-free transport observations, independent of device execution state."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
class TransportEvidence:
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
with store.db(write=True) as db:
|
||||||
|
db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS command_transport("
|
||||||
|
"seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,"
|
||||||
|
"command TEXT NOT NULL,state TEXT NOT NULL,body TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
db.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS transport_command ON command_transport(command,seq)"
|
||||||
|
)
|
||||||
|
db.execute("CREATE INDEX IF NOT EXISTS transport_pending ON command_transport(state)")
|
||||||
|
# A process crash cannot tell us whether buffered bytes reached B2.
|
||||||
|
# It must never synthesize a TCP ACK or alter command retry policy.
|
||||||
|
for identifier, body in db.execute(
|
||||||
|
"SELECT id,body FROM command_transport WHERE state IN ('prepared','written')"
|
||||||
|
).fetchall():
|
||||||
|
value = json.loads(body)
|
||||||
|
value.update(state="unconfirmed", reason="host_restarted", closed_at=time.time())
|
||||||
|
db.execute(
|
||||||
|
"UPDATE command_transport SET state=?,body=? WHERE id=?",
|
||||||
|
(value["state"], json.dumps(value), identifier),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def prepare(db, command, stage):
|
||||||
|
value = dict(id=uuid.uuid4().hex, stage=stage, state="prepared", prepared_at=time.time())
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO command_transport(id,command,state,body) VALUES(?,?,?,?)",
|
||||||
|
(value["id"], command, value["state"], json.dumps(value)),
|
||||||
|
)
|
||||||
|
return value["id"]
|
||||||
|
|
||||||
|
def record(self, events):
|
||||||
|
with self.store.db(write=True) as db:
|
||||||
|
for identifier, phase, at, elapsed, reason in events:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT body FROM command_transport WHERE id=?", (identifier,)
|
||||||
|
).fetchone()
|
||||||
|
if not row or phase not in {"written", "tcp_acknowledged", "unconfirmed"}:
|
||||||
|
continue
|
||||||
|
value = json.loads(row[0])
|
||||||
|
if value["state"] in {"tcp_acknowledged", "unconfirmed"}:
|
||||||
|
continue
|
||||||
|
if phase == "written":
|
||||||
|
value.setdefault("written_at", at)
|
||||||
|
elif phase == "tcp_acknowledged":
|
||||||
|
value.update(tcp_acknowledged_at=at, tcp_ack_seconds=elapsed)
|
||||||
|
else:
|
||||||
|
value.update(closed_at=at, reason=reason)
|
||||||
|
value["state"] = phase
|
||||||
|
db.execute(
|
||||||
|
"UPDATE command_transport SET state=?,body=? WHERE id=?",
|
||||||
|
(phase, json.dumps(value), identifier),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def read(db, command):
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT body FROM command_transport WHERE command=? ORDER BY seq DESC LIMIT 32",
|
||||||
|
(command,),
|
||||||
|
).fetchall()
|
||||||
|
return [json.loads(row[0]) for row in reversed(rows)]
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Single-file headless installer entry point, using the same plan/apply engine."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import fcntl
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Install VPS Host ARNavi on Ubuntu Server 24.04 amd64"
|
||||||
|
)
|
||||||
|
parser.add_argument("--host", help="Public DNS name or IPv4 of this VPS")
|
||||||
|
actions = parser.add_mutually_exclusive_group()
|
||||||
|
actions.add_argument(
|
||||||
|
"--fresh", action="store_true", help="Back up and replace this product installation"
|
||||||
|
)
|
||||||
|
actions.add_argument("--restore", help="Restore the private backup created by --fresh")
|
||||||
|
actions.add_argument("--export-state", help="Stop and fence this VPS; export private state")
|
||||||
|
actions.add_argument("--import-state", help="Restore exported state on an empty Ubuntu VPS")
|
||||||
|
actions.add_argument(
|
||||||
|
"--resume-source",
|
||||||
|
action="store_true",
|
||||||
|
help="Cancel migration fencing; target must already be stopped",
|
||||||
|
)
|
||||||
|
parser.add_argument("--sha256", help="Required SHA-256 of --import-state archive")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
parser.error("Run: sudo python3 " + Path(sys.argv[0]).name)
|
||||||
|
# Serialize all owner installer actions, including crash recovery/migration.
|
||||||
|
with open("/run/lock/ndc-mission-vps-installer.lock", "a") as lock:
|
||||||
|
try:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError:
|
||||||
|
parser.error("Another VPS installer operation is running")
|
||||||
|
with tempfile.TemporaryDirectory(prefix="ndc-vps-install-") as directory:
|
||||||
|
with zipfile.ZipFile(sys.argv[0]) as archive:
|
||||||
|
for name in archive.namelist():
|
||||||
|
if name.startswith("payload/"):
|
||||||
|
relative = Path(name).relative_to("payload")
|
||||||
|
if ".." in relative.parts:
|
||||||
|
raise ValueError("Invalid installer payload")
|
||||||
|
target = Path(directory) / relative
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
target.write_bytes(archive.read(name))
|
||||||
|
sys.path.insert(0, directory)
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
"installer", Path(directory) / "install.py"
|
||||||
|
)
|
||||||
|
engine = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(engine)
|
||||||
|
if args.export_state or args.import_state or args.resume_source:
|
||||||
|
import portable_state
|
||||||
|
|
||||||
|
if args.export_state:
|
||||||
|
portable_state.export_state(engine, Path(args.export_state))
|
||||||
|
elif args.import_state:
|
||||||
|
if args.host or not args.sha256:
|
||||||
|
parser.error("Import preserves the endpoint; provide --sha256, not --host")
|
||||||
|
portable_state.import_state(engine, Path(args.import_state), args.sha256)
|
||||||
|
else:
|
||||||
|
portable_state.resume_source(engine)
|
||||||
|
return
|
||||||
|
if args.restore:
|
||||||
|
engine.restore(Path(args.restore))
|
||||||
|
return
|
||||||
|
host = args.host or input("Public DNS name or IPv4 of this VPS: ").strip()
|
||||||
|
options = argparse.Namespace(host=host, api_port=19443, tracker_port=9922, expect=None)
|
||||||
|
proposal = engine.plan(options)
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{k: proposal[k] for k in ("environment", "configuration", "artifact")}, indent=2
|
||||||
|
)
|
||||||
|
)
|
||||||
|
options.expect = proposal["plan_sha256"]
|
||||||
|
if args.fresh:
|
||||||
|
engine.fresh(options, proposal)
|
||||||
|
else:
|
||||||
|
engine.apply(options, proposal)
|
||||||
|
print(
|
||||||
|
"VPS Host ARNavi ready. Copy the key from "
|
||||||
|
"/opt/nodedc-mission-vps/connect.key into Mission Core."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
"""Private, quiesced state transfer. Code and system configuration come from the installer."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
SCHEMA = "missioncore.vps-portable-state/v1"
|
||||||
|
FILES = {"host.json", "tls.crt", "tls.key", "connect.key", "journal.sqlite3"}
|
||||||
|
MAX_BYTES = 2 * 1024**3
|
||||||
|
SERVICE = "ndc-mission-vps.service"
|
||||||
|
|
||||||
|
|
||||||
|
def sha(path):
|
||||||
|
with path.open("rb") as stream:
|
||||||
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_directory(path):
|
||||||
|
fd = os.open(path, os.O_RDONLY)
|
||||||
|
try:
|
||||||
|
os.fsync(fd)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
|
def durable_json(path, value):
|
||||||
|
temporary = path.with_name(path.name + ".new")
|
||||||
|
with temporary.open("wb") as stream:
|
||||||
|
temporary.chmod(0o600)
|
||||||
|
stream.write(json.dumps(value, sort_keys=True, indent=2).encode())
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
os.replace(temporary, path)
|
||||||
|
sync_directory(path.parent)
|
||||||
|
|
||||||
|
|
||||||
|
def options(config):
|
||||||
|
return argparse.Namespace(
|
||||||
|
host=config["public_host"],
|
||||||
|
api_port=config["api_port"],
|
||||||
|
tracker_port=config["tracker"]["port"],
|
||||||
|
expect=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check_state(state):
|
||||||
|
config = json.loads((state / "host.json").read_text())
|
||||||
|
fingerprint = hashlib.sha256(
|
||||||
|
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
|
||||||
|
).hexdigest()
|
||||||
|
if config["fingerprint"] != fingerprint or config["host_id"] != "vps_" + fingerprint:
|
||||||
|
raise ValueError("state TLS identity mismatch")
|
||||||
|
if (
|
||||||
|
config["endpoint"] != f"https://{config['public_host']}:{config['api_port']}"
|
||||||
|
or config["tracker"]["host"] != config["public_host"]
|
||||||
|
):
|
||||||
|
raise ValueError("inconsistent state endpoints")
|
||||||
|
cert = subprocess.run(
|
||||||
|
["openssl", "x509", "-in", str(state / "tls.crt"), "-pubkey", "-noout"],
|
||||||
|
capture_output=True,
|
||||||
|
check=True,
|
||||||
|
).stdout
|
||||||
|
key = subprocess.run(
|
||||||
|
["openssl", "pkey", "-in", str(state / "tls.key"), "-pubout"],
|
||||||
|
capture_output=True,
|
||||||
|
check=True,
|
||||||
|
).stdout
|
||||||
|
if cert != key:
|
||||||
|
raise ValueError("state private key mismatch")
|
||||||
|
with sqlite3.connect((state / "journal.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
|
||||||
|
if db.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
|
||||||
|
raise ValueError("state journal integrity failure")
|
||||||
|
# Enforce the known state boundary without rewriting its IDs or deadlines.
|
||||||
|
for table in (
|
||||||
|
"state",
|
||||||
|
"devices",
|
||||||
|
"packages",
|
||||||
|
"receipts",
|
||||||
|
"commands",
|
||||||
|
"operations",
|
||||||
|
"operation_attempts",
|
||||||
|
"operation_stops",
|
||||||
|
):
|
||||||
|
db.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def export_state(engine, destination):
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("root required")
|
||||||
|
destination = destination.absolute()
|
||||||
|
if destination.exists() or destination.is_symlink() or not destination.parent.is_dir():
|
||||||
|
raise ValueError("new archive path in an existing directory required")
|
||||||
|
config = json.loads((engine.STATE / "host.json").read_text())
|
||||||
|
proposal = engine.plan(options(config))
|
||||||
|
if not proposal["previous"] or Path(proposal["previous"]).name != proposal["artifact"]:
|
||||||
|
raise ValueError("install this exact release before exporting its state")
|
||||||
|
if (
|
||||||
|
"ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json"
|
||||||
|
not in engine.UNIT.read_text()
|
||||||
|
):
|
||||||
|
raise ValueError("installed service has no persistent migration fence")
|
||||||
|
engine.healthy()
|
||||||
|
allowed = FILES | {"journal.sqlite3-wal", "journal.sqlite3-shm", "journal.sqlite3-journal"}
|
||||||
|
if any(
|
||||||
|
p.name not in allowed or p.is_symlink() or not p.is_file() for p in engine.STATE.iterdir()
|
||||||
|
):
|
||||||
|
raise ValueError("unrecognized private state; export refuses to omit it")
|
||||||
|
required = sum((engine.STATE / name).stat().st_size for name in FILES)
|
||||||
|
if (
|
||||||
|
required > MAX_BYTES
|
||||||
|
or shutil.disk_usage(destination.parent).free < required * 2 + 256 * 1024**2
|
||||||
|
):
|
||||||
|
raise ValueError("insufficient archive space or state exceeds portable limit")
|
||||||
|
fence = engine.ROOT / "migration-fence.json"
|
||||||
|
record = {
|
||||||
|
"schema": SCHEMA,
|
||||||
|
"migration_id": uuid.uuid4().hex,
|
||||||
|
"created_at": time.time(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
"artifact": proposal["artifact"],
|
||||||
|
"status": "quiescing",
|
||||||
|
}
|
||||||
|
# Persistent unit condition blocks manual/automatic starts and host reboots.
|
||||||
|
# Failure after this point stays fenced; the operator can explicitly resume.
|
||||||
|
durable_json(fence, record)
|
||||||
|
engine.run("systemctl", "stop", SERVICE)
|
||||||
|
active = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True).stdout.strip()
|
||||||
|
if active not in (b"inactive", b"failed"):
|
||||||
|
raise ValueError("source did not stop; migration remains fenced")
|
||||||
|
with tempfile.TemporaryDirectory(prefix=".ndc-vps-export-", dir=destination.parent) as work:
|
||||||
|
work = Path(work)
|
||||||
|
state = work / "state"
|
||||||
|
state.mkdir(mode=0o700)
|
||||||
|
for name in FILES - {"journal.sqlite3"}:
|
||||||
|
shutil.copyfile(engine.STATE / name, state / name)
|
||||||
|
(state / name).chmod(0o600)
|
||||||
|
with (
|
||||||
|
sqlite3.connect(
|
||||||
|
(engine.STATE / "journal.sqlite3").as_uri() + "?mode=ro", uri=True
|
||||||
|
) as src,
|
||||||
|
sqlite3.connect(state / "journal.sqlite3") as dst,
|
||||||
|
):
|
||||||
|
src.backup(dst)
|
||||||
|
(state / "journal.sqlite3").chmod(0o600)
|
||||||
|
check_state(state)
|
||||||
|
record.update(
|
||||||
|
status="source_fenced",
|
||||||
|
files={
|
||||||
|
"state/" + name: {
|
||||||
|
"sha256": sha(state / name),
|
||||||
|
"size": (state / name).stat().st_size,
|
||||||
|
}
|
||||||
|
for name in sorted(FILES)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
durable_json(work / "manifest.json", record)
|
||||||
|
archive = work / "state.tar.gz"
|
||||||
|
with tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as tar:
|
||||||
|
for name in ["manifest.json", *record["files"]]:
|
||||||
|
info = tar.gettarinfo(work / name, arcname=name)
|
||||||
|
info.mode = 0o600
|
||||||
|
info.mtime = int(info.mtime)
|
||||||
|
info.uid = info.gid = 0
|
||||||
|
info.uname = info.gname = ""
|
||||||
|
with (work / name).open("rb") as stream:
|
||||||
|
tar.addfile(info, stream)
|
||||||
|
archive.chmod(0o600)
|
||||||
|
with archive.open("rb") as stream:
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
# Atomic publication without ever overwriting an existing backup.
|
||||||
|
os.link(archive, destination)
|
||||||
|
sync_directory(destination.parent)
|
||||||
|
digest = sha(destination)
|
||||||
|
durable_json(fence, {**record, "archive_sha256": digest})
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"status": "source_fenced",
|
||||||
|
"archive": str(destination),
|
||||||
|
"sha256": digest,
|
||||||
|
"migration_id": record["migration_id"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def unpack(archive, expected, directory, artifact):
|
||||||
|
if not re.fullmatch(r"[a-f0-9]{64}", expected) or archive.is_symlink() or not archive.is_file():
|
||||||
|
raise ValueError("regular archive and exact SHA-256 required")
|
||||||
|
if archive.stat().st_size > MAX_BYTES or sha(archive) != expected:
|
||||||
|
raise ValueError("archive digest or size mismatch")
|
||||||
|
expected_names = {"manifest.json"} | {"state/" + name for name in FILES}
|
||||||
|
seen, total = set(), 0
|
||||||
|
# Never extract paths/links/modes supplied by an archive or deserialize code.
|
||||||
|
with tarfile.open(archive, "r:gz") as tar:
|
||||||
|
for member in tar:
|
||||||
|
if (
|
||||||
|
member.name not in expected_names
|
||||||
|
or member.name in seen
|
||||||
|
or not member.isfile()
|
||||||
|
or member.pax_headers
|
||||||
|
):
|
||||||
|
raise ValueError("invalid portable archive member")
|
||||||
|
total += member.size
|
||||||
|
limit = MAX_BYTES if member.name == "state/journal.sqlite3" else 1024 * 1024
|
||||||
|
if member.size > limit or total > MAX_BYTES:
|
||||||
|
raise ValueError("portable archive size limit")
|
||||||
|
seen.add(member.name)
|
||||||
|
target = directory / member.name
|
||||||
|
target.parent.mkdir(mode=0o700, exist_ok=True)
|
||||||
|
with target.open("xb") as stream, tar.extractfile(member) as source:
|
||||||
|
target.chmod(0o600)
|
||||||
|
shutil.copyfileobj(source, stream, 1024 * 1024)
|
||||||
|
if seen != expected_names:
|
||||||
|
raise ValueError("incomplete portable archive")
|
||||||
|
record = json.loads((directory / "manifest.json").read_text())
|
||||||
|
if (
|
||||||
|
record.get("schema") != SCHEMA
|
||||||
|
or record.get("status") != "source_fenced"
|
||||||
|
or record.get("artifact") != artifact
|
||||||
|
or set(record.get("files", {})) != expected_names - {"manifest.json"}
|
||||||
|
):
|
||||||
|
raise ValueError("archive requires its exact installer release and complete manifest")
|
||||||
|
for name, item in record["files"].items():
|
||||||
|
if item != {"sha256": sha(directory / name), "size": (directory / name).stat().st_size}:
|
||||||
|
raise ValueError("state integrity mismatch")
|
||||||
|
return record, check_state(directory / "state")
|
||||||
|
|
||||||
|
|
||||||
|
def import_state(engine, archive, expected):
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("root required")
|
||||||
|
for path in (engine.ROOT, engine.STATE, engine.UNIT):
|
||||||
|
if path.exists() or path.is_symlink():
|
||||||
|
raise ValueError("portable import requires an empty product installation")
|
||||||
|
if shutil.disk_usage(engine.STATE.parent).free < MAX_BYTES + 256 * 1024**2:
|
||||||
|
raise ValueError("portable import requires 2.25 GiB free staging space")
|
||||||
|
with tempfile.TemporaryDirectory(prefix=".ndc-vps-import-", dir=engine.STATE.parent) as work:
|
||||||
|
work = Path(work)
|
||||||
|
record, config = unpack(archive, expected, work, engine.digest())
|
||||||
|
args = options(config)
|
||||||
|
proposal = engine.plan(args) # OS, prerequisites, ports and firewall, before mutation.
|
||||||
|
args.expect = proposal["plan_sha256"]
|
||||||
|
# Install this shipped code and unit, creating the target's system account.
|
||||||
|
# Only identity/journal state crosses hosts; no old executable/unit/firewall does.
|
||||||
|
staged_state = work / "state"
|
||||||
|
staged_state.chmod(0o700)
|
||||||
|
for path in staged_state.iterdir():
|
||||||
|
with path.open("rb") as stream:
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
sync_directory(staged_state)
|
||||||
|
# Same-filesystem rename publishes all state at once. A failed copy
|
||||||
|
# must not leave a partial identity or require twice the journal space.
|
||||||
|
os.rename(staged_state, engine.STATE)
|
||||||
|
sync_directory(engine.STATE.parent)
|
||||||
|
engine.apply(args, proposal)
|
||||||
|
durable_json(
|
||||||
|
engine.ROOT / "imported-state.json",
|
||||||
|
{
|
||||||
|
"schema": SCHEMA,
|
||||||
|
"migration_id": record["migration_id"],
|
||||||
|
"archive_sha256": expected,
|
||||||
|
"imported_at": time.time(),
|
||||||
|
"endpoint_preserved": True,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"status": "imported",
|
||||||
|
"identity_preserved": True,
|
||||||
|
"migration_id": record["migration_id"],
|
||||||
|
"endpoint_preserved": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resume_source(engine):
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("root required")
|
||||||
|
fence = engine.ROOT / "migration-fence.json"
|
||||||
|
record = json.loads(fence.read_text())
|
||||||
|
if record.get("schema") != SCHEMA or record.get("artifact") != engine.digest():
|
||||||
|
raise ValueError("source fence requires the same installer")
|
||||||
|
fence.unlink()
|
||||||
|
sync_directory(fence.parent)
|
||||||
|
try:
|
||||||
|
engine.run("systemctl", "start", SERVICE)
|
||||||
|
engine.healthy()
|
||||||
|
except Exception:
|
||||||
|
durable_json(fence, record)
|
||||||
|
engine.run("systemctl", "stop", SERVICE)
|
||||||
|
raise
|
||||||
|
durable_json(
|
||||||
|
engine.ROOT / "migration-cancelled.json",
|
||||||
|
{"migration_id": record["migration_id"], "resumed_at": time.time()},
|
||||||
|
)
|
||||||
|
print(json.dumps({"status": "source_resumed", "migration_id": record["migration_id"]}))
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Bounded HTTP clock exchange over real loopback streams; no physical B2."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from ndc_vps.commands import frame
|
||||||
|
from ndc_vps.service import Service
|
||||||
|
from ndc_vps.store import Store
|
||||||
|
from ndc_vps.web_protocol import time_reply
|
||||||
|
|
||||||
|
|
||||||
|
async def qualify():
|
||||||
|
with tempfile.TemporaryDirectory(prefix="ndc-vps-clock-") as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
(root / "host.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{"host_id": "vps_" + "a" * 64, "tracker": {"host": "example.org", "port": 9922}}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
store = Store(root)
|
||||||
|
imei = "123456789012345"
|
||||||
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
||||||
|
service = Service(store)
|
||||||
|
server = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
||||||
|
writers = []
|
||||||
|
try:
|
||||||
|
port = server.sockets[0].getsockname()[1]
|
||||||
|
monitor, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||||
|
writers.append(writer)
|
||||||
|
writer.write(b"\xff\x23" + int(imei).to_bytes(8, "little"))
|
||||||
|
await writer.drain()
|
||||||
|
assert (await monitor.readexactly(9))[0] == 0x7B
|
||||||
|
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||||
|
writers.append(writer)
|
||||||
|
request = (
|
||||||
|
b"[\x01\x00\x0f"
|
||||||
|
+ int(imei).to_bytes(8, "little")
|
||||||
|
+ bytes.fromhex("0001e7020000075d")
|
||||||
|
)
|
||||||
|
for _ in range(2):
|
||||||
|
before = int(time.time())
|
||||||
|
writer.write(b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + request)
|
||||||
|
await writer.drain()
|
||||||
|
header = await reader.readuntil(b"\r\n\r\n")
|
||||||
|
assert header.startswith(b"HTTP/1.1 200 OK\r\n")
|
||||||
|
assert b"Content-Length: 10\r\n" in header
|
||||||
|
body = await reader.readexactly(10)
|
||||||
|
seconds = int.from_bytes(body[5:9], "big")
|
||||||
|
assert before <= seconds <= int(time.time())
|
||||||
|
assert body == time_reply(seconds)
|
||||||
|
with store.db() as db:
|
||||||
|
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 0
|
||||||
|
session = next(iter(service.commands.sessions[imei]))
|
||||||
|
service.commands.session_activity[imei, session] = time.monotonic() - 20
|
||||||
|
original = service.commands.submit(
|
||||||
|
{"id": "d" * 32, "imei": imei, "kind": "read-settings", "password": "123456"}
|
||||||
|
)
|
||||||
|
service.notify(imei)
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
assert service.commands.get("d" * 32)["state"] == "queued"
|
||||||
|
# A real incoming telemetry frame wakes the waiting sender.
|
||||||
|
data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0"
|
||||||
|
writers[0].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]")
|
||||||
|
await writers[0].drain()
|
||||||
|
expected = frame("123456*GETP")
|
||||||
|
received = await monitor.readexactly(len(expected) + 4)
|
||||||
|
assert received in (b"{\x00\x01}" + expected, expected + b"{\x00\x01}")
|
||||||
|
receipt = service.commands.get("d" * 32)
|
||||||
|
assert receipt["state"] == "dispatched"
|
||||||
|
assert receipt["expires_at"] == original["expires_at"]
|
||||||
|
assert service.commands.take(imei, session) is None
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
for writer in writers:
|
||||||
|
writer.close()
|
||||||
|
await asyncio.gather(
|
||||||
|
*(writer.wait_closed() for writer in writers), return_exceptions=True
|
||||||
|
)
|
||||||
|
for _ in range(30):
|
||||||
|
if service.connections == 0:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
assert service.connections == 0 and not service.wake
|
||||||
|
await server.wait_closed()
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"clock_replies": 2,
|
||||||
|
"same_http_connection": True,
|
||||||
|
"clock_commands_created": 0,
|
||||||
|
"stale_configuration_deferred": True,
|
||||||
|
"fresh_packet_dispatched_once": True,
|
||||||
|
"physical_devices_used": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 8)), sort_keys=True))
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""Bounded Linux loopback qualification; no tracker, firewall or service changes.
|
||||||
|
|
||||||
|
Run with the unpacked release's Python. Two ephemeral local TCP connections,
|
||||||
|
at most 64 KiB synthetic data, no dependencies or persistent state.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from ndc_vps import VERSION
|
||||||
|
from ndc_vps.delivery import Delivery, queued_bytes
|
||||||
|
|
||||||
|
|
||||||
|
async def qualify(blocked):
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
accepted = loop.create_future()
|
||||||
|
finished = asyncio.Event()
|
||||||
|
handler_done = asyncio.Event()
|
||||||
|
|
||||||
|
async def handler(reader, writer):
|
||||||
|
accepted.set_result(writer)
|
||||||
|
try:
|
||||||
|
await finished.wait()
|
||||||
|
finally:
|
||||||
|
writer.transport.abort()
|
||||||
|
handler_done.set()
|
||||||
|
|
||||||
|
server = await asyncio.start_server(handler, "127.0.0.1", 0)
|
||||||
|
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
|
||||||
|
client.setblocking(False)
|
||||||
|
guard = None
|
||||||
|
try:
|
||||||
|
await loop.sock_connect(client, server.sockets[0].getsockname())
|
||||||
|
writer = await asyncio.wait_for(accepted, 2)
|
||||||
|
sock = writer.get_extra_info("socket")
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
|
||||||
|
aborted = []
|
||||||
|
|
||||||
|
class ObservedDelivery(Delivery):
|
||||||
|
def abort(self, reason="connection_closed"):
|
||||||
|
aborted.append(time.monotonic())
|
||||||
|
super().abort(reason)
|
||||||
|
|
||||||
|
guard = ObservedDelivery(writer)
|
||||||
|
assert guard.ready()
|
||||||
|
started = time.monotonic()
|
||||||
|
deadline = started + 0.75
|
||||||
|
payload = b"x" * (65536 if blocked else 12)
|
||||||
|
guard.write(payload, deadline)
|
||||||
|
if not blocked:
|
||||||
|
assert await asyncio.wait_for(loop.sock_recv(client, 12), 1) == payload
|
||||||
|
await asyncio.sleep(0.15)
|
||||||
|
kernel = queued_bytes(sock)
|
||||||
|
buffered = writer.transport.get_write_buffer_size()
|
||||||
|
if blocked:
|
||||||
|
assert kernel > 0, "The peer did not actually block TCP delivery"
|
||||||
|
assert not guard.ready(), "An unacknowledged prefix must block a new command"
|
||||||
|
else:
|
||||||
|
assert guard.ready(), "A fully acknowledged stream should accept a new command"
|
||||||
|
await asyncio.sleep(0.85)
|
||||||
|
if blocked:
|
||||||
|
assert writer.is_closing() and sock.fileno() == -1
|
||||||
|
assert aborted and 0 <= aborted[0] - deadline < 0.25
|
||||||
|
reset = False
|
||||||
|
async with asyncio.timeout(2):
|
||||||
|
try:
|
||||||
|
while await loop.sock_recv(client, 4096):
|
||||||
|
pass
|
||||||
|
except ConnectionResetError:
|
||||||
|
reset = True
|
||||||
|
assert reset, "Expected abortive close, not graceful buffered delivery"
|
||||||
|
else:
|
||||||
|
assert not writer.is_closing() and not aborted and not guard.pending
|
||||||
|
return {
|
||||||
|
"case": "blocked-receiver" if blocked else "transport-ack-without-device-reply",
|
||||||
|
"bytes": len(payload),
|
||||||
|
"kernel_queued_before_deadline": kernel,
|
||||||
|
"asyncio_queued_before_deadline": buffered,
|
||||||
|
"deadline_seconds": deadline - started,
|
||||||
|
"abort_seconds": aborted[0] - started if aborted else None,
|
||||||
|
"peer_reset": reset if blocked else False,
|
||||||
|
"passed": True,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
if guard:
|
||||||
|
guard.abort()
|
||||||
|
client.close()
|
||||||
|
finished.set()
|
||||||
|
if accepted.done():
|
||||||
|
await asyncio.wait_for(handler_done.wait(), 2)
|
||||||
|
server.close()
|
||||||
|
await server.wait_closed()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
assert sys.platform == "linux", "Qualify on the supported Linux host"
|
||||||
|
result = {
|
||||||
|
"session_id": str(uuid.uuid4()),
|
||||||
|
"version": VERSION,
|
||||||
|
"started_utc": datetime.now(UTC).isoformat(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
"cases": [],
|
||||||
|
}
|
||||||
|
for blocked in (False, True):
|
||||||
|
result["cases"].append(await qualify(blocked))
|
||||||
|
result["completed_utc"] = datetime.now(UTC).isoformat()
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
"""Crash and response-loss qualification on isolated loopback sockets and SQLite.
|
||||||
|
|
||||||
|
Uses the installed ndc_vps package unchanged. One synthetic tracker at a time,
|
||||||
|
no production database, TLS endpoint, firewall, physical device or service change.
|
||||||
|
The internal HTTP loopback harness does not qualify production TLS transport.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from ndc_vps import VERSION
|
||||||
|
from ndc_vps.service import Service
|
||||||
|
from ndc_vps.store import Store
|
||||||
|
|
||||||
|
IMEI = "123456789012345"
|
||||||
|
TOKEN = "synthetic-owner-token-" + "a" * 32
|
||||||
|
|
||||||
|
|
||||||
|
def initialize(root):
|
||||||
|
(root / "host.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"host_id": "vps_" + "a" * 64,
|
||||||
|
"tracker": {"host": "synthetic.example", "port": 9922},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
store = Store(root)
|
||||||
|
store.set_devices([{"imei": IMEI, "instance_id": "c" * 32}])
|
||||||
|
with store.db() as db:
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO state VALUES('owner',?)",
|
||||||
|
(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"core_id": "synthetic",
|
||||||
|
"token": hashlib.sha256(TOKEN.encode()).hexdigest(),
|
||||||
|
}
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
async def child(root):
|
||||||
|
service = Service(Store(root))
|
||||||
|
api = await asyncio.start_server(service.api, "127.0.0.1", 0)
|
||||||
|
tracker = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{"api": api.sockets[0].getsockname()[1], "tracker": tracker.sockets[0].getsockname()[1]}
|
||||||
|
),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
async with api, tracker:
|
||||||
|
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||||
|
|
||||||
|
|
||||||
|
class Harness:
|
||||||
|
def __init__(self, root):
|
||||||
|
self.root, self.process, self.peer = root, None, None
|
||||||
|
self.store = initialize(root)
|
||||||
|
self.frames = []
|
||||||
|
|
||||||
|
async def start(self):
|
||||||
|
self.process = await asyncio.create_subprocess_exec(
|
||||||
|
sys.executable,
|
||||||
|
str(Path(__file__).resolve()),
|
||||||
|
"--child",
|
||||||
|
str(self.root),
|
||||||
|
stdout=asyncio.subprocess.PIPE,
|
||||||
|
stderr=asyncio.subprocess.PIPE,
|
||||||
|
)
|
||||||
|
line = await asyncio.wait_for(self.process.stdout.readline(), 8)
|
||||||
|
if not line:
|
||||||
|
raise RuntimeError((await self.process.stderr.read()).decode())
|
||||||
|
self.ports = json.loads(line)
|
||||||
|
|
||||||
|
async def stop(self):
|
||||||
|
if self.peer:
|
||||||
|
self.peer[1].transport.abort()
|
||||||
|
self.peer = None
|
||||||
|
if self.process and self.process.returncode is None:
|
||||||
|
self.process.kill() # Deliberately no graceful drain or in-memory handoff.
|
||||||
|
await asyncio.wait_for(self.process.wait(), 5)
|
||||||
|
|
||||||
|
async def restart(self):
|
||||||
|
await self.stop()
|
||||||
|
await self.start()
|
||||||
|
|
||||||
|
def body(self, **extra):
|
||||||
|
return {
|
||||||
|
"id": uuid.uuid4().hex,
|
||||||
|
"imei": IMEI,
|
||||||
|
"kind": "request-position",
|
||||||
|
"model": 231,
|
||||||
|
"firmware": "0.01",
|
||||||
|
"not_after": time.time() + 15,
|
||||||
|
**extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def http(self, method, path, body=None, *, loss=None):
|
||||||
|
reader, writer = await asyncio.open_connection("127.0.0.1", self.ports["api"])
|
||||||
|
data = json.dumps(body or {}).encode()
|
||||||
|
header = (
|
||||||
|
f"{method} {path} HTTP/1.1\r\nHost: localhost\r\n"
|
||||||
|
f"Authorization: Bearer {TOKEN}\r\nContent-Length: {len(data)}\r\n\r\n"
|
||||||
|
).encode()
|
||||||
|
try:
|
||||||
|
writer.write(header + (data[:-4] if loss == "before-body" else data))
|
||||||
|
await writer.drain()
|
||||||
|
if loss == "before-body":
|
||||||
|
return None
|
||||||
|
if loss == "after-commit":
|
||||||
|
async with asyncio.timeout(3):
|
||||||
|
while True:
|
||||||
|
with self.store.db() as db:
|
||||||
|
exists = db.execute(
|
||||||
|
"SELECT 1 FROM commands WHERE id=?", (body["id"],)
|
||||||
|
).fetchone()
|
||||||
|
if exists:
|
||||||
|
return None # The client intentionally never observes the HTTP result.
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
raw = await asyncio.wait_for(reader.read(), 4)
|
||||||
|
head, payload = raw.split(b"\r\n\r\n", 1)
|
||||||
|
return int(head.split()[1]), json.loads(payload)
|
||||||
|
finally:
|
||||||
|
writer.transport.abort()
|
||||||
|
|
||||||
|
async def get(self, body):
|
||||||
|
status, result = await self.http("GET", "/v1/commands/" + body["id"])
|
||||||
|
assert status == 200, result
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def submit(self, body, **kwargs):
|
||||||
|
value = await self.http("POST", "/v1/commands", body, **kwargs)
|
||||||
|
if value is not None:
|
||||||
|
assert value[0] == 200, value
|
||||||
|
return value[1]
|
||||||
|
|
||||||
|
async def connect(self):
|
||||||
|
if self.peer:
|
||||||
|
self.peer[1].transport.abort()
|
||||||
|
self.peer = await asyncio.open_connection("127.0.0.1", self.ports["tracker"])
|
||||||
|
self.peer[1].write(b"\xff\x23" + int(IMEI).to_bytes(8, "little"))
|
||||||
|
await self.peer[1].drain()
|
||||||
|
assert len(await asyncio.wait_for(self.peer[0].readexactly(9), 2)) == 9
|
||||||
|
|
||||||
|
async def frame(self):
|
||||||
|
first = await asyncio.wait_for(self.peer[0].readexactly(4), 3)
|
||||||
|
raw = first + await asyncio.wait_for(self.peer[0].readexactly(first[1] + 1), 2)
|
||||||
|
assert raw[0] == 0x7B and raw[-1] == 0x7D
|
||||||
|
self.frames.append(raw)
|
||||||
|
return raw
|
||||||
|
|
||||||
|
async def no_frame(self):
|
||||||
|
try:
|
||||||
|
data = await asyncio.wait_for(self.peer[0].read(1), 0.35)
|
||||||
|
except TimeoutError:
|
||||||
|
return
|
||||||
|
raise AssertionError(f"Unexpected data or connection loss: {data.hex()}")
|
||||||
|
|
||||||
|
async def reply(self, frame):
|
||||||
|
payload = struct.pack("<I", int(time.time())) + b"\0" + frame[5:9]
|
||||||
|
raw = b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]"
|
||||||
|
self.peer[1].write(raw)
|
||||||
|
await self.peer[1].drain()
|
||||||
|
assert await asyncio.wait_for(self.peer[0].readexactly(4), 2) == b"{\0\x01}"
|
||||||
|
|
||||||
|
|
||||||
|
async def qualify():
|
||||||
|
result = {
|
||||||
|
"session_id": uuid.uuid4().hex,
|
||||||
|
"version": VERSION,
|
||||||
|
"started_utc": datetime.now(UTC).isoformat(),
|
||||||
|
"monotonic": time.monotonic(),
|
||||||
|
"physical_devices_used": False,
|
||||||
|
"production_state_used": False,
|
||||||
|
"cases": [],
|
||||||
|
}
|
||||||
|
with tempfile.TemporaryDirectory(prefix="ndc-vps-faults-") as name:
|
||||||
|
harness = Harness(Path(name))
|
||||||
|
await harness.start()
|
||||||
|
try:
|
||||||
|
# Lost upload before any accepted operation.
|
||||||
|
body = harness.body()
|
||||||
|
await harness.submit(body, loss="before-body")
|
||||||
|
status, _ = await harness.http("GET", "/v1/commands/" + body["id"])
|
||||||
|
assert status == 400
|
||||||
|
await harness.submit(body)
|
||||||
|
await harness.connect()
|
||||||
|
await harness.reply(await harness.frame())
|
||||||
|
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||||
|
result["cases"].append({"name": "lost-request-retry-same-id", "passed": True})
|
||||||
|
|
||||||
|
# Lose HTTP result, then kill the process with a durable queued read.
|
||||||
|
await harness.restart()
|
||||||
|
body = harness.body()
|
||||||
|
await harness.submit(body, loss="after-commit")
|
||||||
|
await harness.restart()
|
||||||
|
queued = await harness.submit(body)
|
||||||
|
assert queued["state"] == "queued" and queued["expires_at"] == body["not_after"]
|
||||||
|
await harness.connect()
|
||||||
|
frame = await harness.frame()
|
||||||
|
await harness.submit(body)
|
||||||
|
await harness.no_frame()
|
||||||
|
await harness.reply(frame)
|
||||||
|
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||||
|
result["cases"].append({"name": "lost-http-response-crash-queued-read", "passed": True})
|
||||||
|
|
||||||
|
# No tracker until after the original deadline, even across SIGKILL.
|
||||||
|
await harness.restart()
|
||||||
|
body = harness.body(not_after=time.time() + 0.8)
|
||||||
|
await harness.submit(body)
|
||||||
|
await harness.restart()
|
||||||
|
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||||
|
await harness.connect()
|
||||||
|
await harness.no_frame()
|
||||||
|
assert (await harness.submit(body))["state"] == "expired"
|
||||||
|
result["cases"].append({"name": "offline-expiry-not-extended-by-crash", "passed": True})
|
||||||
|
|
||||||
|
# TCP accepted the bytes; no command ACK. The runtime must not say success.
|
||||||
|
body = harness.body(not_after=time.time() + 0.8)
|
||||||
|
await harness.submit(body)
|
||||||
|
await harness.frame()
|
||||||
|
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||||
|
assert (await harness.get(body))["state"] == "unconfirmed"
|
||||||
|
await harness.restart()
|
||||||
|
await harness.connect()
|
||||||
|
await harness.no_frame()
|
||||||
|
assert (await harness.submit(body))["state"] == "unconfirmed"
|
||||||
|
result["cases"].append({"name": "tcp-ack-without-command-reply", "passed": True})
|
||||||
|
|
||||||
|
# Effect bytes were received by the synthetic peer; crash before a reply.
|
||||||
|
body = harness.body(kind="set-output", pin=4, enabled=True, password="123456")
|
||||||
|
await harness.submit(body)
|
||||||
|
frame = await harness.frame()
|
||||||
|
assert frame[2] == 0xFC and b"*SERV*8.4.1" in frame
|
||||||
|
await harness.restart()
|
||||||
|
await harness.connect()
|
||||||
|
assert (await harness.submit(body))["state"] == "uncertain"
|
||||||
|
await harness.no_frame()
|
||||||
|
result["cases"].append({"name": "dispatched-output-crash-no-replay", "passed": True})
|
||||||
|
|
||||||
|
# A fresh independent read still works on the same identity after recovery.
|
||||||
|
body = harness.body()
|
||||||
|
await harness.submit(body)
|
||||||
|
await harness.reply(await harness.frame())
|
||||||
|
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||||
|
with harness.store.db() as db:
|
||||||
|
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||||
|
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 6
|
||||||
|
assert (
|
||||||
|
db.execute("SELECT instance FROM devices WHERE imei=?", (IMEI,)).fetchone()[0]
|
||||||
|
== "c" * 32
|
||||||
|
)
|
||||||
|
result["cases"].append(
|
||||||
|
{"name": "identity-and-history-survive-recovery", "passed": True}
|
||||||
|
)
|
||||||
|
assert len(harness.frames) == 5
|
||||||
|
result["received_command_frames"] = len(harness.frames)
|
||||||
|
finally:
|
||||||
|
await harness.stop()
|
||||||
|
result.update(
|
||||||
|
completed_utc=datetime.now(UTC).isoformat(),
|
||||||
|
elapsed_seconds=time.monotonic() - result["monotonic"],
|
||||||
|
ok=True,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
os.umask(0o077)
|
||||||
|
if len(sys.argv) == 3 and sys.argv[1] == "--child":
|
||||||
|
asyncio.run(child(Path(sys.argv[2])))
|
||||||
|
else:
|
||||||
|
print(json.dumps(asyncio.run(qualify()), indent=2))
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user