diff --git a/README.md b/README.md index 4198d5bd..636b5a11 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # NODEDC MISSION CORE +ARNavi B2 VPS server development moved to +[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS). +Mission Core retains its B2 client and existing pairing; see the +[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md). + NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning, recording, and integration platform for NODEDC autonomous systems. This repository is the canonical early-stage monorepo: it contains the Mission Core diff --git a/apps/control-station/src/core/fleet/cellular.ts b/apps/control-station/src/core/fleet/cellular.ts index bdaa3d61..347cbc96 100644 --- a/apps/control-station/src/core/fleet/cellular.ts +++ b/apps/control-station/src/core/fleet/cellular.ts @@ -35,6 +35,14 @@ export function cellularNetworkLabel(value:CellularNetwork|undefined){ const name=cellularOperator(value); return name?`${name} · ${code}`:`Оператор не определён · код ${code}`; } +export function cellularSlotDescription(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){ + const view=cellularSlotView(telemetry,slot,now); + if(view.absent)return 'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.'; + const operator=cellularCardOperator(telemetry,slot); + if(operator)return operator; + if(view.current&&view.network?.mcc==null)return view.internet?'Интернет подключён. B2 ещё не передал код сети оператора.':'B2 ещё не передал код сети оператора.'; + return cellularNetworkLabel(view.network); +} 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); diff --git a/apps/control-station/src/core/fleet/commandRuntime.ts b/apps/control-station/src/core/fleet/commandRuntime.ts index 315db390..31ccd55d 100644 --- a/apps/control-station/src/core/fleet/commandRuntime.ts +++ b/apps/control-station/src/core/fleet/commandRuntime.ts @@ -2,11 +2,11 @@ import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from 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 {sequence?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial;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;catalog:CommandPreset[];device:IndependentDevice;capacity:number;durable_kinds?:string[]} +export interface CommandEntry extends Omit {sequence?:number;delivered_at?:number;delivery_seconds?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial;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;catalog:CommandPreset[];device:IndependentDevice;capacity:number|null;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)[state]??'Неизвестный статус'; +export const commandStatus=(state:string)=>({delivered:'Доставлено',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)[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)} с`; @@ -15,10 +15,14 @@ export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):Co 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)[value.reason??'']??''; + if(value.reason==='pulse_result_unknown')return 'Импульс был отправлен, но доставка не подтверждена. Автоматический повтор может вызвать второй импульс. Проверьте результат перед повторной отправкой.'; + if(value.state==='expired'&&value.vps_created_at&&!value.dispatched_at)return 'VPS не дождался готового соединения с B2 до истечения срока. Команда трекеру не отправлена.'; + return ({settings_changed:'Настройки изменились после запроса повтора. Команда не отправлена.',queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record)[value.reason??'']??''; } export function commandReceipt(value:CommandEntry):string{ + if(value.delivered_at!==undefined)return 'Доставка команды подтверждена. Это не подтверждение переключения контактов выхода.'; + if(value.device_code===undefined&&value.description?.encoding?.includes('FC'))return 'Текстовый ответ B2 не содержит идентификатора команды. Исполнение по такому ответу подтвердить нельзя.'; 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)[value.device_code]??'Неизвестный ответ B2'; } diff --git a/apps/control-station/src/core/fleet/useCommandRuntime.ts b/apps/control-station/src/core/fleet/useCommandRuntime.ts index 805b3402..b75c5b2e 100644 --- a/apps/control-station/src/core/fleet/useCommandRuntime.ts +++ b/apps/control-station/src/core/fleet/useCommandRuntime.ts @@ -2,24 +2,24 @@ 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}; +type Intent={request_id:string;preset_id?:string;repeat_of?:string}; export function useCommandRuntime(identifier:string){ const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`; const [data,setData]=useState(null),[items,setItems]=useState([]),[before,setBefore]=useState(null),[error,setError]=useState(''),[activity,setActivity]=useState(''); const alive=useRef(true),sending=useRef(false),first=useRef(true); const tracked=useRef([]); - const [intent,setIntent]=useState(()=>{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 [intent,setIntent]=useState(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&(typeof v.preset_id==='string'||typeof v.repeat_of==='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(`${path}?${query}`));},[path,accept]); useEffect(()=>{alive.current=true;let timer:ReturnType;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}; + async function send(preset:string,repeatOf?:string){ + if(sending.current)return;sending.current=true;setActivity(repeatOf?`repeat:${repeatOf}`:'send');setError(''); + const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),...(repeatOf?{repeat_of:repeatOf}:{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)}); + const response=await fetch(`/api/v1/fleet/equipment${path}${request.repeat_of?`/${request.repeat_of}/repeat`:''}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request.repeat_of?{request_id:request.request_id}: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.');} @@ -27,5 +27,5 @@ export function useCommandRuntime(identifier:string){ } 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(`${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}; + return {data,items,before,error,setError,working:!!activity,activity,intent,send,repeat:(id:string)=>send('',id),cancel,more,refresh}; } diff --git a/apps/control-station/src/workspaces/fleet/equipment/CommandHistory.tsx b/apps/control-station/src/workspaces/fleet/equipment/CommandHistory.tsx index fb801a7a..b5e5a157 100644 --- a/apps/control-station/src/workspaces/fleet/equipment/CommandHistory.tsx +++ b/apps/control-station/src/workspaces/fleet/equipment/CommandHistory.tsx @@ -1,9 +1,9 @@ -import {Button,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react'; +import {Button,Icon,IconButton,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 {items.map(item=>
  • {commandEntryStatus(item)}} actions={<>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&}}/>{item.id===selected&&}
  • )}
    ; +export function CommandHistory({identifier,items,selected,onSelect,onCancel,onRepeat,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;onRepeat:(id:string)=>void;working:boolean;cancelling:string}){ + return {items.map(item=>
  • {commandEntryStatus(item)}} actions={<>onRepeat(item.id)}>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&}}/>{item.id===selected&&}
  • )}
    ; } function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){ @@ -14,6 +14,7 @@ function CommandDetails({identifier,current}:{identifier:string;current:CommandE
    Принято Core
    {commandDate(current.created_at)}
    {current.durable?<>
    Попыток
    {current.attempt_count??0}
    {current.attempt_expires_at!==undefined&&
    Срок текущей попытки
    {commandDate(current.attempt_expires_at)}
    }:<>
    Срок отправки из Core
    {commandDate(current.queue_deadline)}
    Срок ожидания ответа
    {commandDate(current.expires_at)}
    }
    Отправлено B2
    {commandDate(current.dispatched_at)}
    Ответ B2
    {commandDate(current.received_at)}
    + {current.delivered_at!==undefined&&
    Доставка подтверждена
    {commandDate(current.delivered_at)} · {commandDuration(current.delivery_seconds)}
    } {current.device_accepted_at!==undefined&&
    Принято B2
    {commandDate(current.device_accepted_at)}
    } {current.scope==='command'&&
    Результат B2
    {commandReceipt(current)}
    }
    До ответа
    {commandDuration(current.roundtrip_seconds)}
    diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentCellular.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentCellular.tsx index e9ce18ed..a5574e49 100644 --- a/apps/control-station/src/workspaces/fleet/equipment/EquipmentCellular.tsx +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentCellular.tsx @@ -1,5 +1,5 @@ import {SettingsCard,StatusBadge} from '@nodedc/ui-react'; -import {cellularCardOperator,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular'; +import {cellularFresh,cellularSlotDescription,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular'; import type {EquipmentObservation} from '../../../core/fleet/equipment'; import type {TrackerTelemetry} from '../../../core/fleet/vps'; @@ -11,7 +11,7 @@ export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTeleme 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 {view.role}}> + return {view.role}}>
    Регистрация
    {cellularSimLabel(status?.sim_states[slot])}
    {!view.absent&&network&&<> diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentCommandWindow.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentCommandWindow.tsx index b836423f..3a5dbfe7 100644 --- a/apps/control-station/src/workspaces/fleet/equipment/EquipmentCommandWindow.tsx +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentCommandWindow.tsx @@ -19,13 +19,14 @@ export function EquipmentCommandWindow({device,telemetry,onClose}:{device:Indepe {data&&<> {!items.length&&

    {runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}

    } - void runtime.cancel(id)} working={runtime.working} cancelling={runtime.activity}/> + void runtime.cancel(id)} onRepeat={id=>void runtime.repeat(id)} working={runtime.working||!!runtime.intent} cancelling={runtime.activity}/> {runtime.before!==null&&}
    } diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx index aeb0aa97..5a20425a 100644 --- a/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx @@ -28,7 +28,7 @@ export function EquipmentFirmware({device}:{device:IndependentDevice}){ {const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/> - {loadError?<>

    {loadError}

    :catalog?.items.length?<> + {loadError?<>

    {loadError}

    :catalog?.items.length?
    ({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/> -

    {slot==='native'?'Оба слота разрешены. APN, логин и пароль обеих SIM будут очищены; B2 попробует подключиться без них. Для тарифов со специальным APN сохраните текущие параметры. После применения B2 перезапустится, результат проверим по новой связи.':slot==='both'?'B2 сможет использовать любую из установленных SIM. APN обеих карт сохранятся. Одновременно работает одна SIM; срок автоматического переключения не гарантирован. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или разрешите обе. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}

    +