feat(ui): add tracker provisioning, SIM policies, command history and firmware archive
This commit is contained in:
@@ -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);
|
||||
}
|
||||
@@ -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};
|
||||
}
|
||||
@@ -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};
|
||||
}
|
||||
Reference in New Issue
Block a user