From 031e01a99b958095953693f35fb3f7df848f438d Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Mon, 28 Sep 2026 18:44:18 +0300 Subject: [PATCH] feat(ui): add tracker provisioning, SIM policies, command history and firmware archive --- .../src/core/fleet/cellular.ts | 54 ++++++ .../src/core/fleet/commandRuntime.ts | 25 +++ .../src/core/fleet/equipment.ts | 105 ++++++++++++ .../src/core/fleet/firmware.ts | 27 +++ .../src/core/fleet/useCommandAttempts.ts | 17 ++ .../src/core/fleet/useCommandRuntime.ts | 31 ++++ apps/control-station/src/core/fleet/vps.ts | 26 +++ .../workspaces/fleet/NodeInvitationForm.tsx | 2 + .../src/workspaces/fleet/VehicleEquipment.tsx | 8 +- .../fleet/equipment/CommandHistory.tsx | 32 ++++ .../fleet/equipment/EquipmentCellular.tsx | 26 +++ .../equipment/EquipmentCommandWindow.tsx | 36 ++++ .../fleet/equipment/EquipmentConnect.tsx | 29 ++++ .../fleet/equipment/EquipmentFirmware.tsx | 44 +++++ .../fleet/equipment/EquipmentInternet.tsx | 26 +++ .../fleet/equipment/EquipmentPolicyFields.tsx | 17 ++ .../fleet/equipment/EquipmentSettings.tsx | 55 ++++++ .../fleet/equipment/IndependentEquipment.tsx | 40 +++++ .../fleet/equipment/InstallerCard.tsx | 11 ++ .../fleet/equipment/VPSHostSettings.tsx | 29 ++++ .../workspaces/fleet/equipment/equipment.css | 1 + .../test/cellularTelemetry.test.mjs | 81 +++++++++ .../test/commandRuntime.test.mjs | 54 ++++++ .../test/independentEquipment.test.mjs | 157 ++++++++++++++++++ 24 files changed, 929 insertions(+), 4 deletions(-) create mode 100644 apps/control-station/src/core/fleet/cellular.ts create mode 100644 apps/control-station/src/core/fleet/commandRuntime.ts create mode 100644 apps/control-station/src/core/fleet/equipment.ts create mode 100644 apps/control-station/src/core/fleet/firmware.ts create mode 100644 apps/control-station/src/core/fleet/useCommandAttempts.ts create mode 100644 apps/control-station/src/core/fleet/useCommandRuntime.ts create mode 100644 apps/control-station/src/core/fleet/vps.ts create mode 100644 apps/control-station/src/workspaces/fleet/equipment/CommandHistory.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentCellular.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentCommandWindow.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentConnect.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentInternet.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentPolicyFields.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/EquipmentSettings.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/IndependentEquipment.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/InstallerCard.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/VPSHostSettings.tsx create mode 100644 apps/control-station/src/workspaces/fleet/equipment/equipment.css create mode 100644 apps/control-station/test/cellularTelemetry.test.mjs create mode 100644 apps/control-station/test/commandRuntime.test.mjs create mode 100644 apps/control-station/test/independentEquipment.test.mjs diff --git a/apps/control-station/src/core/fleet/cellular.ts b/apps/control-station/src/core/fleet/cellular.ts new file mode 100644 index 00000000..bdaa3d61 --- /dev/null +++ b/apps/control-station/src/core/fleet/cellular.ts @@ -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={'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)[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)[value??-1]??'Нет сведений'; +} +export function cellularModemLabel(value:number|undefined){ + return ({0:'Модем выключен',1:'Модем включён',2:'Модем отвечает',3:'Подключение GPRS',4:'GPRS подключён'} as Record)[value??-1]??'Нет сведений о модеме'; +} diff --git a/apps/control-station/src/core/fleet/commandRuntime.ts b/apps/control-station/src/core/fleet/commandRuntime.ts new file mode 100644 index 00000000..315db390 --- /dev/null +++ b/apps/control-station/src/core/fleet/commandRuntime.ts @@ -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 {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 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 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)[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)[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)[value.runtime_phase]??commandStatus(value.state):value.state==='dispatched'&&value.device_accepted_at!==undefined?commandStatus('device_accepted'):commandStatus(value.state); diff --git a/apps/control-station/src/core/fleet/equipment.ts b/apps/control-station/src/core/fleet/equipment.ts new file mode 100644 index 00000000..93fcc185 --- /dev/null +++ b/apps/control-station/src/core/fleet/equipment.ts @@ -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; +} +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;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(path:string,method='GET',body?:unknown):Promise{ + 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)||valuefield.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)[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)[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)[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)[operation.state]??'Статус операции недоступен.'; +} diff --git a/apps/control-station/src/core/fleet/firmware.ts b/apps/control-station/src/core/fleet/firmware.ts new file mode 100644 index 00000000..42a08e5c --- /dev/null +++ b/apps/control-station/src/core/fleet/firmware.ts @@ -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{ + return (await response(`${root}/${encodeURIComponent(model)}`)).json(); +} +export async function uploadFirmware(model:string,file:File):Promise{ + 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{ + 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); +} diff --git a/apps/control-station/src/core/fleet/useCommandAttempts.ts b/apps/control-station/src/core/fleet/useCommandAttempts.ts new file mode 100644 index 00000000..ffda77b1 --- /dev/null +++ b/apps/control-station/src/core/fleet/useCommandAttempts.ts @@ -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({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; + async function read(){try{const value=await equipmentRequest(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(`${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)}; +} diff --git a/apps/control-station/src/core/fleet/useCommandRuntime.ts b/apps/control-station/src/core/fleet/useCommandRuntime.ts new file mode 100644 index 00000000..805b3402 --- /dev/null +++ b/apps/control-station/src/core/fleet/useCommandRuntime.ts @@ -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(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 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}; + 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(`${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}; +} diff --git a/apps/control-station/src/core/fleet/vps.ts b/apps/control-station/src/core/fleet/vps.ts new file mode 100644 index 00000000..a4ea7602 --- /dev/null +++ b/apps/control-station/src/core/fleet/vps.ts @@ -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;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} +export interface CellularNetwork extends CellularStamp {mcc:number|null;mnc:number;signal:number|null} +export interface TrackerCellular {host_id:string;status?:CellularStatus;networks:Record} +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|null;sim_identity?:{slots:Record}|null} +export async function vpsRequest(path='',method='GET',body?:unknown):Promise{ + 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([]),[unavailable,setUnavailable]=useState(false); + useEffect(()=>{let active=true;let timer:ReturnType;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}; +} diff --git a/apps/control-station/src/workspaces/fleet/NodeInvitationForm.tsx b/apps/control-station/src/workspaces/fleet/NodeInvitationForm.tsx index 443f625f..a6b5e00f 100644 --- a/apps/control-station/src/workspaces/fleet/NodeInvitationForm.tsx +++ b/apps/control-station/src/workspaces/fleet/NodeInvitationForm.tsx @@ -2,6 +2,7 @@ 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; @@ -31,6 +32,7 @@ export function NodeInvitationForm({vehicle,onClose,onComplete,renderWindow}:{ve const replacing=!!vehicle&&vehicle.enrollment!=='revoked'; return renderWindow({busy:pending,actions:<>{preview?:},content:
+ {!preview&&} {!vehicle&&<>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/> + {chosen&&<>
{chosen.encoding} · тело
{chosen.wire}

{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.':`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}

{chosen.unavailable&&

{chosen.unavailable}

}} + + + + ({value:m.id,label:m.label})),{value:'vps-host',label:'VPS Host ARNavi'}]} disabled={pending} onChange={value=>{setType(value);setCandidate(null);setName('');setProfile('');}}/>{content}; + if(type==='computer')return onComputer()} renderWindow={renderWindow}/>; + if(type==='vps-host')return ; + return <>{renderWindow({busy,actions:<>,content:
+ {model&&<>setName(e.target.value)}/> + 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&&} + + {candidate&&Настройки прочитаны

Устройство будет добавлено в реестр. Передача на ваш сервер ещё не подтверждена; выбранный профиль будет сохранён для настройки.

} + } +
+ })}setError('')}/>; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx new file mode 100644 index 00000000..aeb0aa97 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentFirmware.tsx @@ -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(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(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 <> + +
Версия
{recordedVersion||'Нет сведений'}
Считана
{device.observed.read_at?new Date(device.observed.read_at*1000).toLocaleString('ru-RU'):'Нет сведений'}
+

Обновление прошивки через Mission Core недоступно. Файлы ниже хранятся отдельно от настроек трекера.

+
+ + {const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/> + + + {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.'}

+ {!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&

Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.

} + {slot&&!both?<> + onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/> + {automatic?

{access?.state==='ready'?`${access.source==='verified_card'?'Проверенные настройки этой карты':'Стандартные настройки оператора'}: ${access.apn}. После сохранения проверим запись и подключение выбранной SIM.`:access?.state==='unknown_card'?'Карта ещё не распознана. Прочитайте её через USB или отключите автоподбор и задайте APN.':access?.state==='unsupported_operator'?'Для этой карты нет сохранённых настроек. Отключите автоподбор и задайте APN.':'Ожидаем подтверждение карты в выбранном слоте.'}

: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&&

Ожидаем актуальные сведения о SIM от трекера.

} +
; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentPolicyFields.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentPolicyFields.tsx new file mode 100644 index 00000000..7f585358 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentPolicyFields.tsx @@ -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
+ + +
({value:String(n),label:`Сервер ${n}`}))} disabled={disabled} onChange={slot=>onChange({...value,endpoint:{...value.endpoint!,slot:Number(slot)}})}/>

Протокол INTERNAL. Остальные серверы сохраняются.

} +
+
+
; + return

Пустое поле — сохранить значение конкретного трекера. Ноль — задать нулевое значение.

{fields.filter(f=>f.group===section).map(field=>{const parameters={...value.parameters};if(e.target.value==='')delete parameters[field.key];else parameters[field.key]=Number(e.target.value);onChange({...value,parameters});}}/>)}
; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/EquipmentSettings.tsx b/apps/control-station/src/workspaces/fleet/equipment/EquipmentSettings.tsx new file mode 100644 index 00000000..30ee9137 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/EquipmentSettings.tsx @@ -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(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;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(`/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(`/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(`/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(`/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(`/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 <>{if(!working)onClose();}} footer={section==='firmware'?undefined:}> +
{telemetryLabel(telemetry)}{section!=='commands'&§ion!=='firmware'&&

{equipmentApplyMessage(configurationWriteNotStarted(device.network_operation)?'not_started':device.policy_state)}

{device.network_server1&&

Последний подтверждённый сервер 1: {device.network_server1.host}:{device.network_server1.port}.

}

{networkOperationMessage(device.network_operation?.scope!=='command'?device.network_operation:undefined)}

{networkPending&&device.network_operation?.scope!=='command'&&

{device.network_operation?.durable?`Попыток: ${device.network_operation.attempt_count??0}. Окно можно закрыть — задание сохранено. Повторы можно остановить в журнале команд.`:progress.overdue?'Срок ожидания истёк. Уточняем результат у VPS; повторная отправка заблокирована до получения результата.':`До окончания ожидания: ${progress.remaining??'—'} с. Окно можно закрыть — операция продолжится на VPS.`}

}
} + {section==='connection'&&} + {section==='firmware'?:section==='identity'?<> + setName(e.target.value)}/> + 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);}}/> + {observed.configuration_read_at&&

Настройки прочитаны через VPS: {new Date(observed.configuration_read_at*1000).toLocaleString('ru-RU')}.

}
Основная SIM
{observed.sim1_iccid_reported_suffix?`…${observed.sim1_iccid_reported_suffix} (${observed.sim1_iccid_reported_length} цифр в ответе)`:'Нет сведений'}
Вторая SIM
{observed.sim2_iccid_reported_suffix?`…${observed.sim2_iccid_reported_suffix} (${observed.sim2_iccid_reported_length} цифр в ответе)`:'Нет сведений'}
APN основной SIM
{observed.configuration.apn1||'Не задан'}
APN второй SIM
{observed.configuration.apn2||'Не задан'}
{observed.configuration.servers.filter(s=>s.host).map(s=>
Сервер {s.slot}
{s.host}:{s.port}
)}
{applying&&

Запись и проверка настроек. Не отсоединяйте USB.

}
+ :section==='commands'?{dirty&&

Сохраните изменения перед переходом к командам.

}
:h.vehicle_ids.includes(target))} section={section} fields={fields} presets={model.connectivity_presets??[]} value={settings} onChange={changeSettings} disabled={busy}/>} + {section!=='firmware'&&validation&&{validation}} +
+
+ {if(!working)setProfileOpen(false);}} closeOnEscape={!working} closeOnBackdrop={false} footer={}>
setProfileName(e.target.value)}/>

Сохранятся параметры работы, выбранный сервер и настройки связи. IMEI, номера SIM, личные пароли и привязка к аппарату не входят в профиль. Настройки уже добавленных устройств не изменятся.

+ {setError('');setNotice('');}}/> + ; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/IndependentEquipment.tsx b/apps/control-station/src/workspaces/fleet/equipment/IndependentEquipment.tsx new file mode 100644 index 00000000..ed1417eb --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/IndependentEquipment.tsx @@ -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(null),[models,setModels]=useState([]),[profiles,setProfiles]=useState([]),[vehicles,setVehicles]=useState([]); + const [hosts,setHosts]=useState([]),[vpsOpen,setVpsOpen]=useState(false),[selectedHost,setSelectedHost]=useState(); + const telemetry=useTrackerTelemetry(vehicle.id); + const [adding,setAdding]=useState(false),[selected,setSelected]=useState(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;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(null); + const model=selected&&models.find(m=>m.id===selected.model_id); + const selectedTelemetry=telemetry.items.find(t=>t.instance_id===selected?.id); + return <> +
Бортовой компьютер и независимые устройства
setAdding(true)}>{reload();onRefresh();}}>
+ {computer} + {!devices?:{devices.map(device=>
  • } 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={t.instance_id===device.id)?.online?'success':'neutral'} aria-label={telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))}/>} actions={<>setCommandDevice(device)}>setSelected(device)}>}/>
  • )}
    } + {hosts.filter(h=>h.vehicle_ids.includes(vehicle.id)).map(host=>
  • } title={host.name} description="VPS Host ARNavi" metadata={`${host.endpoint} · Аппаратов: ${host.vehicle_ids.length}`} statusPlacement="leading" status={} actions={{setSelectedHost(host);setVpsOpen(true);}}>}/>
  • )}
    + {vpsOpen&&h.id===selectedHost?.id)} hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={()=>setVpsOpen(false)} onSaved={()=>{setVpsOpen(false);reload();}}/>} + {error&&!devices&&} + {adding&&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&&setSelected(null)} onObserved={observe} onProfile={reload} onCommands={()=>{setCommandDevice(selected);setSelected(null);}}/>} + {commandDevice&&t.instance_id===commandDevice.id)} onClose={()=>{setCommandDevice(null);reload();}}/>} + setError('')}/> + ; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/InstallerCard.tsx b/apps/control-station/src/workspaces/fleet/equipment/InstallerCard.tsx new file mode 100644 index 00000000..ef88624f --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/InstallerCard.tsx @@ -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(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 {`${item.label} ${item.version} · Только ${item.os}`}

    {item.instructions.map((step,index)=>{index>0&&
    }{index+1}. {step}
    )}:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}> + +
    ; +} diff --git a/apps/control-station/src/workspaces/fleet/equipment/VPSHostSettings.tsx b/apps/control-station/src/workspaces/fleet/equipment/VPSHostSettings.tsx new file mode 100644 index 00000000..46441c76 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/equipment/VPSHostSettings.tsx @@ -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=<>; + const footer={actions}; + const content=
    + {!host&&h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>} + {interfaces.length>0&&<>{advanced&&