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};
|
||||
}
|
||||
@@ -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:<><Button disabled={pending} onClick={onClose}>Отмена</Button>{preview?<Button loading={pending} disabled={pending||(!vehicle&&!name.trim())} onClick={()=>void attach()}>{vehicle?(replacing?'Заменить БК':'Подключить БК'):'Добавить аппарат'}</Button>:<Button loading={pending} type="submit" form={form} disabled={pending||!code.trim()}>Проверить БК</Button>}</>,content:
|
||||
<form id={form} className="fleet-form" onSubmit={inspect} aria-busy={pending}>
|
||||
{!preview&&<InstallerCard kind="node"/>}
|
||||
{!vehicle&&<><Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending}/><TextField label="Название аппарата" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={pending} autoComplete="off"/></>}
|
||||
{vehicle&&<SettingsCard title={vehicle.name} description={replacing?'Новый БК заменит текущий. Аппарат, его название и раскладки сохранятся; прежняя привязка будет отозвана.':'Подключите БК к этому аппарату по приглашению Mission Core Node.'}/>}
|
||||
{preview?<SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={()=>setPreview(null)}>Другое приглашение</Button></SettingsCard>:<TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={e=>setCode(e.target.value)}/>}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {useEffect,useSyncExternalStore} from 'react';
|
||||
import {Button,Icon,IconButton,Inspector,LoadingRegion} from '@nodedc/ui-react';
|
||||
import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
|
||||
import type {BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout';
|
||||
import type {SensorBoardContent} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||
import type {Vehicle} from '../../core/fleet/useFleet';
|
||||
import {VehicleIdentitySettings} from './VehicleIdentitySettings';
|
||||
import {BoardComputerRow} from './BoardComputer';
|
||||
import {IndependentEquipment} from './equipment/IndependentEquipment';
|
||||
|
||||
export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;layout:BoardLayoutStore;content:SensorBoardContent;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
|
||||
const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot);
|
||||
@@ -19,10 +20,9 @@ export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,o
|
||||
<Inspector variant="panel" openSections={state.value.open_sections.filter(id=>id!=='computer')} onOpenSectionsChange={changeSections} sections={[
|
||||
{id:'settings',label:'Настройки аппарата',icon:<Icon name="sliders"/>,disabled:!state.ready,content:<div className="sensor-content"><VehicleIdentitySettings key={vehicle.id} vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>},
|
||||
{id:'devices',label:'Оборудование',icon:<Icon name="apps"/>,disabled:!state.ready,content:<div className="sensor-content">
|
||||
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и подключённые к нему устройства</span><div className="sensor-actions"><IconButton label="Подключить бортовой компьютер" onClick={onAddComputer}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>void content.refresh()}><Icon name="refresh"/></IconButton></div></div>
|
||||
<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
|
||||
<IndependentEquipment key={vehicle.id} vehicle={vehicle} onComputer={onAddComputer} onRefresh={()=>void content.refresh()} computer={<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
|
||||
{computerOpen&&<div className="fleet-computer-devices">{content.devices}</div>}
|
||||
</div>
|
||||
</div>}/>
|
||||
</div>},
|
||||
]}/>
|
||||
</LoadingRegion>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {Button,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime';
|
||||
import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts';
|
||||
|
||||
export function CommandHistory({identifier,items,selected,onSelect,onCancel,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;working:boolean;cancelling:string}){
|
||||
return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>;
|
||||
}
|
||||
|
||||
function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){
|
||||
const attempts=useCommandAttempts(identifier,current);
|
||||
return <SettingsCard title={current.description.label??'Операция B2'} description={`ID ${current.id} · ПО ${current.firmware??'неизвестно'}`}>
|
||||
{current.description.wire&&<p><code>{current.description.wire}</code></p>}
|
||||
<dl className="fleet-facts">
|
||||
<div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div>
|
||||
{current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>}
|
||||
<div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div>
|
||||
{current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>}
|
||||
{current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>}
|
||||
<div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div>
|
||||
{current.reconnected_at!==undefined&&<div><dt>Возвращение на связь</dt><dd>{commandDate(current.reconnected_at)}</dd></div>}
|
||||
</dl>
|
||||
{commandReason(current)&&<p>{commandReason(current)}</p>}
|
||||
<p>{current.description.confirmation}</p>
|
||||
{current.stop_requested&&<p>Новые попытки остановлены или ожидают остановки на VPS. Уже переданная попытка может завершиться.</p>}
|
||||
{current.durable&&<>
|
||||
<ResourceList aria-label="Попытки доставки">{attempts.items.map(item=><li key={item.id}><ResourceRow title={`Попытка ${item.number}${item.phase==='inspect'?' · проверка состояния':''}`} description={`Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDate(item.received_at)} · ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandStatus(item.state)}</StatusBadge>} metadata={item.device_code!==undefined?commandReceipt({...current,device_code:item.device_code}):undefined}/></li>)}</ResourceList>
|
||||
{attempts.error&&<><p>{attempts.error}</p><Button onClick={attempts.refresh}>Повторить чтение попыток</Button></>}
|
||||
{attempts.next_before!==null&&<Button loading={attempts.working} onClick={()=>void attempts.more()}>Предыдущие попытки</Button>}
|
||||
</>}
|
||||
<ResourceList aria-label="Этапы операции">{[...current.events].sort((a,b)=>(a.occurred_at??a.observed_at)-(b.occurred_at??b.observed_at)).map((event,index)=><li key={index}><ResourceRow title={`${commandStatus(event.state)}${event.attempt?` ${event.attempt}`:''}`} description={event.stage?({preflight:'Чтение настроек',write:'Запись',verify:'Проверка',restart:'Ожидание после перезапуска'} as Record<string,string>)[event.stage]:undefined} metadata={`${commandDate(event.occurred_at??event.observed_at)}${event.historical?' · восстановлено из истории':''}`}/></li>)}</ResourceList>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {cellularCardOperator,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular';
|
||||
import type {EquipmentObservation} from '../../../core/fleet/equipment';
|
||||
import type {TrackerTelemetry} from '../../../core/fleet/vps';
|
||||
|
||||
export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation}){
|
||||
const status=telemetry?.cellular?.status;
|
||||
const configTime=observed.configuration_read_at??observed.read_at;
|
||||
return <div className="fleet-form">
|
||||
{(['1','2'] as const).map(slot=>{
|
||||
const view=cellularSlotView(telemetry,slot),network=view.network;
|
||||
const fresh=!!telemetry?.online&&cellularFresh(network);
|
||||
const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
|
||||
return <SettingsCard key={slot} title={`SIM ${slot}`} description={view.absent?'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.':cellularCardOperator(telemetry,slot)??cellularNetworkLabel(network)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}>
|
||||
<dl className="fleet-facts">
|
||||
<div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div>
|
||||
{!view.absent&&network&&<>
|
||||
<div><dt>Сигнал</dt><dd>{network.signal===null?'Неизвестен':`${network.signal} из 31`}</dd></div>
|
||||
<div><dt>{fresh?'Сеть измерена':'Последнее измерение сети'}</dt><dd>{new Date(network.measured_at*1000).toLocaleString('ru-RU')}</dd></div>
|
||||
</>}
|
||||
<div><dt>APN из настроек B2</dt><dd>{apn||'Не задан'}<br/>Прочитан {new Date(configTime*1000).toLocaleString('ru-RU')}</dd></div>
|
||||
</dl>
|
||||
</SettingsCard>;
|
||||
})}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {commandPending} from '../../../core/fleet/commandRuntime';
|
||||
import {useCommandRuntime} from '../../../core/fleet/useCommandRuntime';
|
||||
import {telemetryLabel,type TrackerTelemetry} from '../../../core/fleet/vps';
|
||||
import type {IndependentDevice} from '../../../core/fleet/equipment';
|
||||
import {CommandHistory} from './CommandHistory';
|
||||
|
||||
export function EquipmentCommandWindow({device,telemetry,onClose}:{device:IndependentDevice;telemetry?:TrackerTelemetry;onClose:()=>void}){
|
||||
const runtime=useCommandRuntime(device.id);
|
||||
const [preset,setPreset]=useState('position'),[filter,setFilter]=useState('all'),[selected,setSelected]=useState('');
|
||||
const data=runtime.data,chosen=data?.catalog.find(value=>value.id===(runtime.intent?.preset_id??preset));
|
||||
const pending=Object.entries(data?.counts??{}).reduce((total,[state,n])=>total+(commandPending(state)?n:0),0);
|
||||
const items=runtime.items.filter(item=>filter==='all'||(filter==='active'?commandPending(item.state):!commandPending(item.state)));
|
||||
return <><Window open title="Команды ARNavi B2" subtitle={data?.device.name??device.name} size="lg" onClose={onClose}>
|
||||
<div className="fleet-form">
|
||||
<StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>
|
||||
<LoadingRegion loading={!data&&!runtime.error} label="Загрузка команд и журнала">
|
||||
{data&&<>
|
||||
<SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}>
|
||||
<Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/>
|
||||
{chosen&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.':`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>}
|
||||
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||pending>=data.capacity))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Журнал операций" description={`Незавершённых: ${pending} · Вместимость очереди: ${data.capacity}`}>
|
||||
<Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/>
|
||||
{!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>}
|
||||
<CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} working={runtime.working} cancelling={runtime.activity}/>
|
||||
{runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>}
|
||||
</SettingsCard>
|
||||
</>}
|
||||
</LoadingRegion>
|
||||
{!data&&runtime.error&&<Button onClick={()=>void runtime.refresh().catch(()=>undefined)}>Повторить чтение</Button>}
|
||||
</div>
|
||||
</Window><ToastStack items={runtime.error?[{id:'command-runtime-error',title:runtime.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>runtime.setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {equipmentRequest,type EquipmentCandidate,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||
import {NodeInvitationForm} from '../NodeInvitationForm';
|
||||
import {VPSHostSettings} from './VPSHostSettings';
|
||||
import type {VPSHost} from '../../../core/fleet/vps';
|
||||
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||
|
||||
export function EquipmentConnect({vehicle,vehicles,models,profiles,hosts,onComputer,onVPS,onClose,onAdded}:{vehicle:Vehicle;vehicles:Vehicle[];models:EquipmentModel[];profiles:EquipmentProfile[];hosts:VPSHost[];onComputer:()=>void;onVPS:()=>void;onClose:()=>void;onAdded:(item:IndependentDevice)=>void}){
|
||||
const [type,setType]=useState('computer'),[name,setName]=useState(''),[target,setTarget]=useState(vehicle.id),[profile,setProfile]=useState('');
|
||||
const [candidate,setCandidate]=useState<EquipmentCandidate|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const model=models.find(m=>m.id===type),selectedProfile=profiles.find(p=>p.id===profile);
|
||||
async function inspect(){setBusy(true);setError('');setCandidate(null);try{const value=await equipmentRequest<EquipmentCandidate>('/inspect','POST',{model_id:type});setCandidate(value);setName(current=>current||`${model?.label??''} · ${value.observed.device_id}`);}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать устройство.');}finally{setBusy(false);}}
|
||||
async function add(){if(!candidate)return;setBusy(true);setError('');try{onAdded(await equipmentRequest<IndependentDevice>('/instances','POST',{candidate_id:candidate.id,name:name.trim(),vehicle_id:target,profile_id:profile||null}));}catch(e){setError(e instanceof Error?e.message:'Не удалось добавить устройство.');}finally{setBusy(false);}}
|
||||
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,busy:pending})=><Window open title="Подключить независимое устройство" subtitle={vehicle.name} size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={()=>{if(!pending)onClose();}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}><div className="fleet-form"><Select label="Тип устройства" value={type} options={[{value:'computer',label:'Бортовой компьютер'},...models.map(m=>({value:m.id,label:m.label})),{value:'vps-host',label:'VPS Host ARNavi'}]} disabled={pending} onChange={value=>{setType(value);setCandidate(null);setName('');setProfile('');}}/>{content}</div></Window>;
|
||||
if(type==='computer')return <NodeInvitationForm vehicle={vehicle} onClose={onClose} onComplete={()=>onComputer()} renderWindow={renderWindow}/>;
|
||||
if(type==='vps-host')return <VPSHostSettings hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={onClose} onSaved={onVPS} renderWindow={renderWindow}/>;
|
||||
return <>{renderWindow({busy,actions:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!candidate||!name.trim()||!target} onClick={()=>void add()}>Добавить к аппарату</Button></>,content:<div className="fleet-form">
|
||||
{model&&<><TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
<Select label="Аппарат" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
|
||||
<Select label="Профиль настроек" value={profile} options={[{value:'',label:'Прочитать настройки трекера'},...profiles.filter(p=>p.model_id===type).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} onChange={setProfile} disabled={busy}/>
|
||||
{selectedProfile&&<SettingsCard title={selectedProfile.name} description={selectedProfile.settings.endpoint?`${selectedProfile.settings.endpoint.host}:${selectedProfile.settings.endpoint.port} · сервер ${selectedProfile.settings.endpoint.slot}`:'Адрес сервера сохраняется из трекера'}/>}
|
||||
<SettingsCard title="USB на этом Mac" description="Подключите один трекер кабелем с передачей данных. Проверка считает модель, идентификатор и настройки."><Button loading={busy} disabled={busy} onClick={()=>void inspect()}>{candidate?'Прочитать повторно':'Проверить USB'}</Button></SettingsCard>
|
||||
{candidate&&<SettingsCard title={`${candidate.observed.model} · ${candidate.observed.device_id}`} description={`IMEI …${candidate.observed.imei_suffix} · ПО ${candidate.observed.firmware}`}><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>Устройство будет добавлено в реестр. Передача на ваш сервер ещё не подтверждена; выбранный профиль будет сохранён для настройки.</p></SettingsCard>}
|
||||
</>}
|
||||
</div>
|
||||
})}<ToastStack items={error?[{id:'equipment-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Icon,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
|
||||
import type {IndependentDevice} from '../../../core/fleet/equipment';
|
||||
import {downloadFirmware,readFirmware,uploadFirmware,type FirmwareCatalog} from '../../../core/fleet/firmware';
|
||||
|
||||
export function EquipmentFirmware({device}:{device:IndependentDevice}){
|
||||
const [catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[selected,setSelected]=useState('');
|
||||
const [loading,setLoading]=useState(true),[uploading,setUploading]=useState(false),[downloading,setDownloading]=useState(false);
|
||||
const [loadError,setLoadError]=useState(''),[error,setError]=useState(''),[notice,setNotice]=useState(''),[reload,setReload]=useState(0);
|
||||
const picker=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;setLoading(true);setLoadError('');
|
||||
readFirmware(device.model_id).then(value=>{if(active){setCatalog(value);setSelected(current=>value.items.some(item=>item.id===current)?current:value.items[0]?.id??'');}})
|
||||
.catch(e=>{if(active)setLoadError(e instanceof Error?e.message:'Не удалось прочитать архив прошивок.');})
|
||||
.finally(()=>{if(active)setLoading(false);});return()=>{active=false;};
|
||||
},[device.model_id,reload]);
|
||||
const item=catalog?.items.find(image=>image.id===selected);
|
||||
async function add(file:File){setUploading(true);setError('');setNotice('');try{
|
||||
const image=await uploadFirmware(device.model_id,file);setSelected(image.id);setReload(value=>value+1);setNotice('Файл сохранён в Mission Core. Прошивка трекера не изменена.');
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}finally{setUploading(false);}}
|
||||
async function download(){if(!item)return;setDownloading(true);setError('');try{await downloadFirmware(item);}catch(e){setError(e instanceof Error?e.message:'Не удалось скачать файл.');}finally{setDownloading(false);}}
|
||||
const recordedVersion=device.observed.firmware;
|
||||
return <>
|
||||
<SettingsCard title="Прошивка трекера" description="Последняя считанная версия устройства.">
|
||||
<dl className="fleet-facts"><div><dt>Версия</dt><dd>{recordedVersion||'Нет сведений'}</dd></div><div><dt>Считана</dt><dd>{device.observed.read_at?new Date(device.observed.read_at*1000).toLocaleString('ru-RU'):'Нет сведений'}</dd></div></dl>
|
||||
<p>Обновление прошивки через Mission Core недоступно. Файлы ниже хранятся отдельно от настроек трекера.</p>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Файлы прошивок" description="Архив Mission Core. Добавление и выбор файла не запускают установку.">
|
||||
<input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/>
|
||||
<Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button>
|
||||
<LoadingRegion loading={loading} label="Читаем архив прошивок">
|
||||
{loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<>
|
||||
<Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/>
|
||||
{item&&<>
|
||||
<StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge>
|
||||
<dl className="fleet-facts"><div><dt>Версия файла</dt><dd>{item.version??'Не определена'}</dd></div><div><dt>Размер</dt><dd>{new Intl.NumberFormat('ru-RU').format(item.bytes)} байт</dd></div><div><dt>Сохранён</dt><dd>{new Date(item.added_at*1000).toLocaleString('ru-RU')}</dd></div></dl>
|
||||
<Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button>
|
||||
</>}
|
||||
{recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>}
|
||||
</>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>}
|
||||
</LoadingRegion>
|
||||
</SettingsCard>
|
||||
<ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
|
||||
import {cellularFresh,cellularSimOptions} from '../../../core/fleet/cellular';
|
||||
import {allowBothInternetSims,selectInternetSim,type ConnectivityPreset,type EquipmentObservation,type EquipmentPolicy} from '../../../core/fleet/equipment';
|
||||
import type {TrackerTelemetry} from '../../../core/fleet/vps';
|
||||
|
||||
export function EquipmentInternet({telemetry,observed,presets,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
|
||||
const options=cellularSimOptions(telemetry);
|
||||
const preferred=['both','native'].includes(value.connectivity.strategy)?value.connectivity.strategy:value.connectivity.activate?String(value.connectivity.sim_slot??1):'';
|
||||
const both=['both','native'].includes(preferred);
|
||||
const slot=both?preferred:options.some(option=>option.value===preferred)?preferred:'';
|
||||
const current=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
|
||||
const connection=value.connectivity;
|
||||
const automatic=connection.strategy==='sim'&&connection.automatic===true;
|
||||
const access=telemetry?.internet_access?.[slot];
|
||||
const targeted=String(connection.sim_slot??1)===slot;
|
||||
const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current;
|
||||
return <SettingsCard title="Интернет"><div className="fleet-form">
|
||||
<Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Обе SIM — без заданного APN'},{value:'both',label:'Обе SIM — сохранить APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/>
|
||||
<p>{slot==='native'?'Оба слота разрешены. APN, логин и пароль обеих SIM будут очищены; B2 попробует подключиться без них. Для тарифов со специальным APN сохраните текущие параметры. После применения B2 перезапустится, результат проверим по новой связи.':slot==='both'?'B2 сможет использовать любую из установленных SIM. APN обеих карт сохранятся. Одновременно работает одна SIM; срок автоматического переключения не гарантирован. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или разрешите обе. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p>
|
||||
{!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>}
|
||||
{slot&&!both?<>
|
||||
<Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/>
|
||||
{automatic?<p>{access?.state==='ready'?`${access.source==='verified_card'?'Проверенные настройки этой карты':'Стандартные настройки оператора'}: ${access.apn}. После сохранения проверим запись и подключение выбранной SIM.`:access?.state==='unknown_card'?'Карта ещё не распознана. Прочитайте её через USB или отключите автоподбор и задайте APN.':access?.state==='unsupported_operator'?'Для этой карты нет сохранённых настроек. Отключите автоподбор и задайте APN.':'Ожидаем подтверждение карты в выбранном слоте.'}</p>:<TextField label="APN" value={apn} maxLength={29} disabled={disabled} hint={`В B2 прочитан: ${current||'не задан'}. Изменение будет отправлено при сохранении настроек.`} onChange={event=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:false,apn:event.target.value,apn1:'',apn2:'',preset_id:null}})}/>}
|
||||
</>:!both&&!options.length&&<p>Ожидаем актуальные сведения о SIM от трекера.</p>}
|
||||
</div></SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
|
||||
import type {TrackerTelemetry,VPSHost} from '../../../core/fleet/vps';
|
||||
import type {ConnectivityPreset,EquipmentField,EquipmentObservation,EquipmentPolicy} from '../../../core/fleet/equipment';
|
||||
|
||||
import {EquipmentInternet} from './EquipmentInternet';
|
||||
|
||||
export function EquipmentPolicyFields({hosts,section,fields,presets,telemetry,observed,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;hosts:VPSHost[];section:string;fields:EquipmentField[];presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
|
||||
if(section==='connection')return <div className="fleet-form">
|
||||
<EquipmentInternet telemetry={telemetry} observed={observed} presets={presets} value={value} onChange={onChange} disabled={disabled}/>
|
||||
<SettingsCard title="Сервер мониторинга" description="Используйте постоянное DNS-имя: при переезде VPS можно сохранить адрес в трекерах.">
|
||||
<div className="fleet-form"><Select label="Зарегистрированный VPS" value={hosts.find(h=>h.status?.tracker.host===value.endpoint?.host&&h.status?.tracker.port===value.endpoint?.port)?.id??''} options={[{value:'',label:'Сохранить адрес или указать вручную'},...hosts.filter(h=>h.status).map(h=>({value:h.id,label:h.name}))]} disabled={disabled} onChange={id=>{const host=hosts.find(h=>h.id===id);if(host?.status)onChange({...value,endpoint:{...host.status.tracker,slot:value.endpoint?.slot??2}});}}/><Switch label="Задать сервер в профиле" checked={value.endpoint!==null} disabled={disabled} onChange={enabled=>onChange({...value,endpoint:enabled?{host:'',port:0,slot:1}:null})}/>
|
||||
{value.endpoint&&<><TextField label="DNS/IP сервера" value={value.endpoint.host} maxLength={49} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,host:e.target.value}})}/><TextField label="Порт" type="number" min={1} max={65535} value={value.endpoint.port||''} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,port:Number(e.target.value)}})}/><Select label="Слот сервера" value={String(value.endpoint.slot)} options={[1,2,3,4].map(n=>({value:String(n),label:`Сервер ${n}`}))} disabled={disabled} onChange={slot=>onChange({...value,endpoint:{...value.endpoint!,slot:Number(slot)}})}/><p>Протокол INTERNAL. Остальные серверы сохраняются.</p></>}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</div>;
|
||||
return <div className="fleet-form"><p>Пустое поле — сохранить значение конкретного трекера. Ноль — задать нулевое значение.</p>{fields.filter(f=>f.group===section).map(field=><TextField key={field.key} label={field.label} type="number" min={field.min} max={field.max} step={1} hint={`${field.min} … ${field.max}`} value={value.parameters[field.key]??''} disabled={disabled} onChange={e=>{const parameters={...value.parameters};if(e.target.value==='')delete parameters[field.key];else parameters[field.key]=Number(e.target.value);onChange({...value,parameters});}}/>)}</div>;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {configurationWriteNotStarted,simSelectionIntent,equipmentPolicyEqual,equipmentApplyMessage,equipmentRequest,networkOperationMessage,networkOperationProgress,policyError,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||
import {cellularSimCurrent} from '../../../core/fleet/cellular';
|
||||
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||
import {telemetryLabel,type TrackerTelemetry,type VPSHost} from '../../../core/fleet/vps';
|
||||
import {EquipmentPolicyFields} from './EquipmentPolicyFields';
|
||||
import {EquipmentCellular} from './EquipmentCellular';
|
||||
import {EquipmentFirmware} from './EquipmentFirmware';
|
||||
|
||||
export function EquipmentSettings({device,model,hosts,telemetry,vehicles,profiles,onClose,onObserved,onProfile,onCommands}:{device:IndependentDevice;model:EquipmentModel;hosts:VPSHost[];telemetry?:TrackerTelemetry;vehicles:Vehicle[];profiles:EquipmentProfile[];onClose:()=>void;onObserved:(item:IndependentDevice)=>void;onProfile:()=>void;onCommands:()=>void}){
|
||||
const [name,setName]=useState(device.name),[target,setTarget]=useState(device.vehicle_id),[settings,setSettings]=useState(device.settings),[section,setSection]=useState('identity');
|
||||
const [profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false),[working,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[selectedProfile,setSelectedProfile]=useState('');
|
||||
const contentRef=useRef<HTMLDivElement>(null);
|
||||
const [simRequested,setSimRequested]=useState(false);
|
||||
const selectSim=simSelectionIntent(settings,device.settings,simRequested);
|
||||
function changeSettings(value:typeof settings){if(value.connectivity!==settings.connectivity)setSimRequested(true);setSettings(value);}
|
||||
const [now,setNow]=useState(()=>Date.now()/1000);
|
||||
const progress=networkOperationProgress(device.network_operation,now);
|
||||
const networkPending=progress.pending;
|
||||
useEffect(()=>{if(!networkPending)return;setNow(Date.now()/1000);const timer=setInterval(()=>setNow(Date.now()/1000),1000);return()=>clearInterval(timer);},[networkPending,device.network_operation?.id]);
|
||||
const busy=working||networkPending;
|
||||
useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&¤t)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]);
|
||||
const observed=device.observed;
|
||||
const secondary=observed.configuration.servers.find(s=>s.slot===2);
|
||||
const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port);
|
||||
const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters);
|
||||
const fields=model.fields.filter(f=>supported.includes(f.key));
|
||||
const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':'');
|
||||
const dirty=name!==device.name||target!==device.vehicle_id||!equipmentPolicyEqual(settings,device.settings);
|
||||
const writable=model.usb_write_firmware?.includes(observed.firmware)??false;
|
||||
const [applying,setApplying]=useState(false),[saving,setSaving]=useState(false),[readingUsb,setReadingUsb]=useState(false);
|
||||
async function applyUsb(){setBusy(true);setApplying(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/apply`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Результат записи не получен. Прочитайте USB повторно.');}finally{setBusy(false);setApplying(false);}}
|
||||
const sections=[{id:'identity',label:'Устройство и аппарат'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...Array.from(new Set(fields.map(f=>f.group))).map(group=>({id:group,label:group,group:'Параметры профиля'}))];
|
||||
async function readNetwork(){setBusy(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect-network`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Чтение через VPS не подтверждено.');}finally{setBusy(false);}}
|
||||
async function applyNetwork(item:IndependentDevice=device,selection=selectSim){setBusy(true);setError('');contentRef.current?.scrollIntoView({block:'start'});try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${item.id}/apply-network`,'POST',{expected_revision:item.revision,select_sim:selection}));setSimRequested(false);}catch(e){setError(e instanceof Error?e.message:'Отправка через VPS не подтверждена.');}finally{setBusy(false);}}
|
||||
async function save(){setBusy(true);setSaving(true);setError('');setNotice('');try{const changed=!equipmentPolicyEqual(settings,device.settings);const retrySelection=selectSim;if(!dirty&&!retrySelection){setNotice('Изменений настроек нет. Команда трекеру не отправлена.');return;}const item=dirty?await equipmentRequest<IndependentDevice>(`/instances/${device.id}`,'PUT',{expected_revision:device.revision,name:name.trim(),vehicle_id:target,settings}):device;onObserved(item);if(changed||retrySelection)await applyNetwork(item,selectSim);else setNotice('Изменения сохранены в Mission Core.');}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить настройки.');}finally{setBusy(false);setSaving(false);}}
|
||||
async function readUsb(){setBusy(true);setReadingUsb(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать USB.');}finally{setBusy(false);setReadingUsb(false);}}
|
||||
async function saveProfile(){setBusy(true);setError('');try{await equipmentRequest('/profiles','POST',{name:profileName.trim(),model_id:device.model_id,settings});setProfileOpen(false);setNotice('Профиль сохранён и доступен при подключении новых трекеров.');onProfile();}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{setBusy(false);}}
|
||||
return <><FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={device.name} identity={{title:model.label,subtitle:`IMEI …${observed.imei_suffix}`,avatarLabel:model.label}} sections={sections} activeSection={section} onSectionChange={setSection} onClose={()=>{if(!working)onClose();}} footer={section==='firmware'?undefined:<WindowFooterActions><Button loading={saving} disabled={busy||!!validation||!name.trim()||!target} onClick={()=>void save()}>Сохранить настройки</Button><Button disabled={working||!!validation} onClick={()=>{setProfileName(`${model.label} — ${name}`.slice(0,80));setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>}>
|
||||
<div className="fleet-form" ref={contentRef}><StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>{section!=='commands'&§ion!=='firmware'&&<SettingsCard title="Настройки через VPS" description={fullSettings?"Параметры профиля записываются через VPS. Текущие настройки читаются перед записью, а результат проверяется повторным чтением. Адрес резервного сервера сохраняется.":"По сети доступна смена адреса и порта сервера 1. Сервер 2 сохраняет связь с текущим VPS. Для полной конфигурации нужен обновлённый VPS."}><p>{equipmentApplyMessage(configurationWriteNotStarted(device.network_operation)?'not_started':device.policy_state)}</p>{device.network_server1&&<p>Последний подтверждённый сервер 1: {device.network_server1.host}:{device.network_server1.port}.</p>}<p>{networkOperationMessage(device.network_operation?.scope!=='command'?device.network_operation:undefined)}</p>{networkPending&&device.network_operation?.scope!=='command'&&<p>{device.network_operation?.durable?`Попыток: ${device.network_operation.attempt_count??0}. Окно можно закрыть — задание сохранено. Повторы можно остановить в журнале команд.`:progress.overdue?'Срок ожидания истёк. Уточняем результат у VPS; повторная отправка заблокирована до получения результата.':`До окончания ожидания: ${progress.remaining??'—'} с. Окно можно закрыть — операция продолжится на VPS.`}</p>}<Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&!device.network_operation?.read_only} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyNetwork()}>Отправить через VPS</Button><Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&device.network_operation?.read_only} disabled={busy||dirty} onClick={()=>void readNetwork()}>Прочитать через VPS</Button></SettingsCard>}
|
||||
{section==='connection'&&<EquipmentCellular telemetry={telemetry} observed={observed}/>}
|
||||
{section==='firmware'?<EquipmentFirmware device={device}/>:section==='identity'?<>
|
||||
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
<Select label="Привязка к аппарату" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
|
||||
<Select label="Загрузить сохранённый профиль" value={selectedProfile} options={[{value:'',label:'Текущие настройки'},...profiles.filter(p=>p.model_id===device.model_id).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} disabled={busy} onChange={id=>{setSelectedProfile(id);const p=profiles.find(p=>p.id===id);changeSettings(p?.settings??device.settings);}}/>
|
||||
<SettingsCard title="Сведения B2" description={`ID ${observed.device_id} · ПО ${observed.firmware} · идентификация по USB ${new Date(observed.read_at*1000).toLocaleString('ru-RU')}`}>{observed.configuration_read_at&&<p>Настройки прочитаны через VPS: {new Date(observed.configuration_read_at*1000).toLocaleString('ru-RU')}.</p>}<dl className="fleet-facts"><div><dt>Основная SIM</dt><dd>{observed.sim1_iccid_reported_suffix?`…${observed.sim1_iccid_reported_suffix} (${observed.sim1_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>Вторая SIM</dt><dd>{observed.sim2_iccid_reported_suffix?`…${observed.sim2_iccid_reported_suffix} (${observed.sim2_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>APN основной SIM</dt><dd>{observed.configuration.apn1||'Не задан'}</dd></div><div><dt>APN второй SIM</dt><dd>{observed.configuration.apn2||'Не задан'}</dd></div>{observed.configuration.servers.filter(s=>s.host).map(s=><div key={s.slot}><dt>Сервер {s.slot}</dt><dd>{s.host}:{s.port}</dd></div>)}</dl><Button loading={readingUsb} disabled={busy||dirty} onClick={()=>void readUsb()}>Прочитать USB повторно</Button><Button loading={applying} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyUsb()}>Первоначальная настройка по USB</Button>{applying&&<p>Запись и проверка настроек. Не отсоединяйте USB.</p>}</SettingsCard>
|
||||
</>:section==='commands'?<SettingsCard title="Команды и журнал" description="Отправка команд, очередь и история обмена с B2."><Button disabled={working||dirty} onClick={onCommands}>Открыть команды</Button>{dirty&&<p>Сохраните изменения перед переходом к командам.</p>}</SettingsCard>:<EquipmentPolicyFields telemetry={telemetry} observed={observed} hosts={hosts.filter(h=>h.vehicle_ids.includes(target))} section={section} fields={fields} presets={model.connectivity_presets??[]} value={settings} onChange={changeSettings} disabled={busy}/>}
|
||||
{section!=='firmware'&&validation&&<StatusBadge tone="warning">{validation}</StatusBadge>}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
<Window open={profileOpen} title="Сохранить профиль" subtitle="Общие настройки для новых трекеров" onClose={()=>{if(!working)setProfileOpen(false);}} closeOnEscape={!working} closeOnBackdrop={false} footer={<WindowFooterActions><Button disabled={working} onClick={()=>setProfileOpen(false)}>Отмена</Button><Button loading={working} disabled={working||!profileName.trim()||!!validation} onClick={()=>void saveProfile()}>Сохранить профиль</Button></WindowFooterActions>}><div className="fleet-form"><TextField label="Название профиля" value={profileName} maxLength={80} disabled={working} onChange={e=>setProfileName(e.target.value)}/><p>Сохранятся параметры работы, выбранный сервер и настройки связи. IMEI, номера SIM, личные пароли и привязка к аппарату не входят в профиль. Настройки уже добавленных устройств не изменятся.</p></div></Window>
|
||||
<ToastStack items={error?[{id:'equipment-settings-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'equipment-profile-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useCallback,useEffect,useState,type ReactNode} from 'react';
|
||||
import {Button,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,StatusBadge,ToastStack} from '@nodedc/ui-react';
|
||||
import {equipmentRequest,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
|
||||
import {fleetRequest,type Vehicle} from '../../../core/fleet/useFleet';
|
||||
import {EquipmentConnect} from './EquipmentConnect';
|
||||
import {EquipmentSettings} from './EquipmentSettings';
|
||||
import {EquipmentCommandWindow} from './EquipmentCommandWindow';
|
||||
import {hostOnline,telemetryLabel,useTrackerTelemetry,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
|
||||
import {VPSHostSettings} from './VPSHostSettings';
|
||||
import './equipment.css';
|
||||
|
||||
export function IndependentEquipment({vehicle,computer,onRefresh}:{vehicle:Vehicle;computer:ReactNode;onComputer:()=>void;onRefresh:()=>void}){
|
||||
const [devices,setDevices]=useState<IndependentDevice[]|null>(null),[models,setModels]=useState<EquipmentModel[]>([]),[profiles,setProfiles]=useState<EquipmentProfile[]>([]),[vehicles,setVehicles]=useState<Vehicle[]>([]);
|
||||
const [hosts,setHosts]=useState<VPSHost[]>([]),[vpsOpen,setVpsOpen]=useState(false),[selectedHost,setSelectedHost]=useState<VPSHost|undefined>();
|
||||
const telemetry=useTrackerTelemetry(vehicle.id);
|
||||
const [adding,setAdding]=useState(false),[selected,setSelected]=useState<IndependentDevice|null>(null),[error,setError]=useState('');
|
||||
const refresh=useCallback(async()=>{
|
||||
const [items,catalog,policies,fleet,vps]=await Promise.all([equipmentRequest<{items:IndependentDevice[]}>(`/instances?vehicle_id=${encodeURIComponent(vehicle.id)}`),equipmentRequest<{models:EquipmentModel[]}>('/catalog'),equipmentRequest<{items:EquipmentProfile[]}>('/profiles'),fleetRequest<{items:Vehicle[]}>(),vpsRequest<{items:VPSHost[]}>()]);
|
||||
setHosts(vps.items);setDevices(items.items);setModels(catalog.models);setProfiles(policies.items);setVehicles(fleet.items);setError('');
|
||||
},[vehicle.id]);
|
||||
const observe=useCallback((item:IndependentDevice)=>{setSelected(item);void refresh().catch(()=>setError('Не удалось обновить независимое оборудование.'));},[refresh]);
|
||||
const reload=()=>{void refresh().catch(()=>setError('Не удалось обновить независимое оборудование. Повторите запрос.'));};
|
||||
useEffect(()=>{let active=true;void refresh().catch(()=>{if(active)setError('Не удалось получить независимое оборудование.');});return()=>{active=false;};},[refresh]);
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await vpsRequest<{items:VPSHost[]}>();if(active)setHosts(value.items);}catch{/* Existing timestamps expire when the connection is unavailable. */}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}void poll();return()=>{active=false;clearTimeout(timer);};},[]);
|
||||
const [commandDevice,setCommandDevice]=useState<IndependentDevice|null>(null);
|
||||
const model=selected&&models.find(m=>m.id===selected.model_id);
|
||||
const selectedTelemetry=telemetry.items.find(t=>t.instance_id===selected?.id);
|
||||
return <>
|
||||
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и независимые устройства</span><div className="sensor-actions"><IconButton label="Подключить независимое устройство" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>{reload();onRefresh();}}><Icon name="refresh"/></IconButton></div></div>
|
||||
{computer}
|
||||
{!devices?<LoadingRegion loading={!error} label="Загрузка независимых устройств"/>:<ResourceList aria-label="Независимые устройства">{devices.map(device=><li key={device.id}><ResourceRow icon={<Icon name="network"/>} title={device.name} description={`${models.find(m=>m.id===device.model_id)?.label??device.model_id} · IMEI …${device.observed.imei_suffix}`} metadata={telemetry.unavailable?'Связь с сервером не проверена':telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={!telemetry.unavailable&&telemetry.items.find(t=>t.instance_id===device.id)?.online?'success':'neutral'} aria-label={telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))}/>} actions={<><IconButton label={`Команды: ${device.name}`} onClick={()=>setCommandDevice(device)}><Icon name="terminal"/></IconButton><IconButton label={`Настройки: ${device.name}`} onClick={()=>setSelected(device)}><Icon name="settings"/></IconButton></>}/></li>)}</ResourceList>}
|
||||
<ResourceList aria-label="VPS Host ARNavi">{hosts.filter(h=>h.vehicle_ids.includes(vehicle.id)).map(host=><li key={host.id}><ResourceRow icon={<Icon name="database"/>} title={host.name} description="VPS Host ARNavi" metadata={`${host.endpoint} · Аппаратов: ${host.vehicle_ids.length}`} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={hostOnline(host)?'success':'neutral'} aria-label={hostOnline(host)?'VPS на связи':'Нет связи с VPS'}/>} actions={<IconButton label={`Настройки: ${host.name}`} onClick={()=>{setSelectedHost(host);setVpsOpen(true);}}><Icon name="settings"/></IconButton>}/></li>)}</ResourceList>
|
||||
{vpsOpen&&<VPSHostSettings host={hosts.find(h=>h.id===selectedHost?.id)} hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={()=>setVpsOpen(false)} onSaved={()=>{setVpsOpen(false);reload();}}/>}
|
||||
{error&&!devices&&<Button onClick={reload}>Повторить</Button>}
|
||||
{adding&&<EquipmentConnect vehicle={vehicle} vehicles={vehicles} models={models} profiles={profiles} hosts={hosts} onClose={()=>setAdding(false)} onComputer={()=>{setAdding(false);onRefresh();}} onVPS={()=>{setAdding(false);reload();}} onAdded={item=>{setAdding(false);if(item.vehicle_id===vehicle.id)setSelected(item);reload();}}/>}
|
||||
{selected&&model&&<EquipmentSettings key={selected.id} device={selected} model={model} hosts={hosts} telemetry={telemetry.unavailable&&selectedTelemetry?{...selectedTelemetry,online:false}:selectedTelemetry} vehicles={vehicles} profiles={profiles} onClose={()=>setSelected(null)} onObserved={observe} onProfile={reload} onCommands={()=>{setCommandDevice(selected);setSelected(null);}}/>}
|
||||
{commandDevice&&<EquipmentCommandWindow key={commandDevice.id} device={commandDevice} telemetry={telemetry.items.find(t=>t.instance_id===commandDevice.id)} onClose={()=>{setCommandDevice(null);reload();}}/>}
|
||||
<ToastStack items={error?[{id:'independent-equipment-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,Switch,TextAreaField,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {hostOnline,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
|
||||
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import {InstallerCard} from './InstallerCard';
|
||||
import type {Vehicle} from '../../../core/fleet/useFleet';
|
||||
|
||||
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
|
||||
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
|
||||
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
|
||||
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const current=host??hosts.find(h=>h.id===existing);
|
||||
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
|
||||
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
|
||||
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
|
||||
const content=<div className="fleet-form">
|
||||
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
|
||||
{!current&&<InstallerCard kind="vps-arnavi"/>}
|
||||
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
|
||||
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
|
||||
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
|
||||
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
|
||||
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
|
||||
</div>;
|
||||
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.equipment-settings-title { display:flex; align-items:center; flex-wrap:wrap; gap:var(--nodedc-space-4); }
|
||||
@@ -0,0 +1,81 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/cellular.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const {cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularModemLabel,cellularSlotView,cellularSimOptions,cellularSimCurrent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
test('SIM freshness rejects old, future and missing observations independently',()=>{
|
||||
assert.equal(cellularFresh(undefined,100),false);
|
||||
assert.equal(cellularFresh({measured_at:11},100),true);
|
||||
assert.equal(cellularFresh({measured_at:10},100),false);
|
||||
assert.equal(cellularFresh({measured_at:101},100),false);
|
||||
});
|
||||
test('missing country code cannot identify a carrier from MNC alone',()=>{
|
||||
assert.equal(cellularNetworkLabel({mcc:null,mnc:2}),'Оператор не определён');
|
||||
assert.equal(cellularNetworkLabel({mcc:250,mnc:2}),'МегаФон · 250-02');
|
||||
assert.equal(cellularNetworkLabel({mcc:250,mnc:1}),'МТС · 250-01');
|
||||
assert.equal(cellularNetworkLabel({mcc:310,mnc:260}),'Оператор не определён · код 310-260');
|
||||
assert.equal(cellularNetworkLabel(undefined),'Оператор не определён');
|
||||
});
|
||||
test('unknown registration and modem states never imply data service',()=>{
|
||||
assert.equal(cellularSimLabel(undefined),'Нет сведений');
|
||||
assert.equal(cellularSimLabel(0),'SIM не обнаружена');
|
||||
assert.equal(cellularSimLabel(6),'Ошибка PIN');
|
||||
assert.equal(cellularSimLabel(7),'Нет сведений');
|
||||
assert.equal(cellularModemLabel(4),'GPRS подключён');
|
||||
assert.equal(cellularModemLabel(7),'Нет сведений о модеме');
|
||||
});
|
||||
|
||||
test('registered second SIM is not presented as another internet connection',()=>{
|
||||
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
|
||||
assert.equal(cellularSlotView(t,'1',100).role,'Используется для интернета');
|
||||
assert.equal(cellularSlotView(t,'2',100).role,'Не выбрана для интернета');
|
||||
assert.equal(cellularNetworkLabel(cellularSlotView(t,'2',100).network),'Оператор не определён · код 250-00');
|
||||
t.cellular.status.active_sim=2;
|
||||
assert.equal(cellularSlotView(t,'2',100).internet,true);
|
||||
assert.equal(cellularSlotView(t,'1',100).internet,false);
|
||||
t.online=false;
|
||||
assert.equal(cellularSlotView(t,'2',100).role,'Последнее полученное состояние');
|
||||
assert.equal(cellularSlotView(t,'2',100).internet,false);
|
||||
});
|
||||
test('removed SIM does not retain a current operator or internet badge',()=>{
|
||||
const t={online:true,cellular:{status:{active_sim:2,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'2':{mcc:250,mnc:1,measured_at:98}}}};
|
||||
assert.equal(cellularSlotView(t,'2',100).role,'SIM не обнаружена');
|
||||
assert.equal(cellularSlotView(t,'2',100).network,undefined);
|
||||
assert.equal(cellularSlotView(t,'2',100).internet,false);
|
||||
assert.equal(cellularSlotView(t,'1',200).role,'Последнее полученное состояние');
|
||||
assert.equal(cellularSlotView(undefined,'1',100).internet,false);
|
||||
assert.equal(cellularNetworkLabel({mcc:250,mnc:99}),'Билайн · 250-99');
|
||||
});
|
||||
|
||||
test('target selector lists installed SIMs and resolves labels anew after swaps',()=>{
|
||||
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:1,measured_at:99}}}};
|
||||
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'}]);
|
||||
t.cellular.status.sim_states['2']=1;
|
||||
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'},{value:'2',label:'SIM 2 (МТС)'}]);
|
||||
[t.cellular.networks['1'],t.cellular.networks['2']]=[t.cellular.networks['2'],t.cellular.networks['1']];
|
||||
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МТС)'},{value:'2',label:'SIM 2 (МегаФон)'}]);
|
||||
t.cellular.networks['2'].mnc=99;
|
||||
assert.equal(cellularSimOptions(t,100)[1].label,'SIM 2 (Билайн)');
|
||||
t.cellular.status.sim_states['1']=0;
|
||||
assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн)'}]);
|
||||
assert.deepEqual(cellularSimOptions(t,200),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
|
||||
assert.equal(cellularSimCurrent(t,2,200),false);
|
||||
assert.equal(cellularSimCurrent(t,2,100),true);
|
||||
t.online=false;assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
|
||||
assert.equal(cellularSimCurrent(t,2,100),false);
|
||||
assert.deepEqual(cellularSimOptions(undefined,100),[]);
|
||||
});
|
||||
test('target selector never carries an old operator into stale, searching or unknown evidence',()=>{
|
||||
const t={online:true,cellular:{status:{sim_states:{'1':2,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
|
||||
assert.deepEqual(cellularSimOptions(t,100).map(o=>o.label),['SIM 1 (оператор не определён)','SIM 2 (оператор не определён)']);
|
||||
t.cellular.status.sim_states['1']=1;t.cellular.networks['1'].measured_at=1;
|
||||
assert.equal(cellularSimOptions(t,100)[0].label,'SIM 1 (оператор не определён)');
|
||||
});
|
||||
|
||||
test('qualified card home operator follows current binding even when serving MNC is unavailable',()=>{
|
||||
const t={online:true,cellular:{status:{measured_at:100,sim_states:{'1':1,'2':1}},networks:{}},sim_identity:{slots:{'1':{binding_current:true,known_card:{home_network:'25002'}},'2':{binding_current:true,known_card:{home_network:'25001'}}}}};
|
||||
assert.deepEqual(cellularSimOptions(t,101).map(x=>x.label),['SIM 1 (МегаФон)','SIM 2 (МТС)']);
|
||||
t.sim_identity.slots['2'].binding_current=false;
|
||||
assert.equal(cellularSimOptions(t,101)[1].label,'SIM 2 (оператор не определён)');
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/commandRuntime.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const {mergeCommands,commandPending,commandTracked,commandStatus,commandTone,commandDate,commandDuration,commandReceipt,commandEntryStatus}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
test('runtime retains loaded history and merges a changing operation by immutable id',()=>{
|
||||
const a={id:'a',sequence:10,state:'waiting'},b={id:'b',sequence:9,state:'device_confirmed'};
|
||||
const entries=mergeCommands([a,b],[{...a,state:'dispatched'},{id:'c',sequence:11,state:'queued'}]);
|
||||
assert.deepEqual(entries.map(x=>[x.id,x.state]),[['c','queued'],['a','dispatched'],['b','device_confirmed']]);
|
||||
assert.equal(a.state,'waiting');
|
||||
});
|
||||
test('a delayed polling response cannot roll a completed command back to pending',()=>{
|
||||
const current={id:'a',sequence:10,state:'device_confirmed',updated_at:20};
|
||||
assert.equal(mergeCommands([current],[{...current,state:'dispatched',updated_at:10}])[0].state,'device_confirmed');
|
||||
});
|
||||
test('runtime makes expiry, no confirmation and receipt distinct; none claim actuator execution',()=>{
|
||||
for(const state of ['waiting','submitting','queued','dispatched'])assert.equal(commandPending(state),true);
|
||||
for(const state of ['expired','cancelled','unconfirmed','uncertain','device_confirmed'])assert.equal(commandPending(state),false);
|
||||
assert.equal(commandTone('device_confirmed'),'success');
|
||||
assert.equal(commandTone('unconfirmed'),'warning');
|
||||
assert.notEqual(commandStatus('expired'),commandStatus('unconfirmed'));
|
||||
assert.doesNotMatch(commandStatus('device_confirmed'),/исполнено|выполнено/i);
|
||||
assert.equal(commandDuration(undefined),'—');assert.equal(commandDuration(0.01234),'0.012 с');assert.equal(commandDate(undefined),'—');
|
||||
});
|
||||
|
||||
test('unresolved results remain tracked after timeout without blocking the command queue',()=>{
|
||||
const unknown={id:'a',sequence:1,state:'uncertain',reconcile_pending:true,updated_at:10};
|
||||
assert.equal(commandPending(unknown.state),false);
|
||||
assert.equal(commandTracked(unknown),true);
|
||||
const final={...unknown,state:'device_confirmed',reconcile_pending:false,updated_at:20};
|
||||
assert.equal(commandTracked(final),false);
|
||||
assert.deepEqual(mergeCommands([unknown],[final]),[final]);
|
||||
});
|
||||
|
||||
test('tracker ACK is visible without pretending that execution finished',()=>{
|
||||
const ack={state:'dispatched',device_code:6,device_accepted_at:10};
|
||||
assert.equal(commandPending(ack.state),true);
|
||||
assert.equal(commandEntryStatus(ack),'Принято B2, выполняется');
|
||||
assert.equal(commandReceipt(ack),'B2 принял команду; требуется время на выполнение');
|
||||
assert.equal(commandReceipt({device_code:0,kind:'restart'}),'B2 принял команду перезапуска');
|
||||
assert.equal(commandEntryStatus({...ack,state:'device_confirmed'}),'Подтверждено B2');
|
||||
assert.equal(commandReceipt({device_code:5}),'B2 сообщил об ошибке выполнения');
|
||||
assert.equal(commandReceipt({device_code:7}),'Очередь команд B2 заполнена');
|
||||
});
|
||||
|
||||
test('durable jobs show recovery independently of a single attempt and stop request',()=>{
|
||||
const entry={state:'queued',durable:true,device_accepted_at:10};
|
||||
assert.equal(commandEntryStatus({...entry,runtime_phase:'retry-wait'}),'Ожидает следующей попытки');
|
||||
assert.equal(commandEntryStatus({...entry,runtime_phase:'reconciling'}),'Уточнение результата у VPS');
|
||||
assert.equal(commandEntryStatus({...entry,stop_requested:true}),'Остановка повторов');
|
||||
assert.equal(commandPending('accepted'),false);
|
||||
assert.equal(commandPending('stopped'),false);
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/equipment.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const {emptyEquipmentPolicy,policyError,equipmentRequest,selectInternetSim,networkOperationMessage,equipmentPolicyEqual}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const fields=[{key:'25',min:0,max:65535,label:'Интервал'}];
|
||||
test('SIM choice creates explicit activation without copying another APN or legacy preset',()=>{
|
||||
for(const connectivity of [
|
||||
{strategy:'operator',sim_slot:2,preset_id:'ru-megafon-public-v1',apn1:'',apn2:''},
|
||||
{strategy:'sim',sim_slot:1,apn:'test.apn',apn1:'',apn2:''},
|
||||
{strategy:'preserve',apn1:'',apn2:''},
|
||||
]){
|
||||
const policy={...emptyEquipmentPolicy(),parameters:{'25':60},connectivity};
|
||||
const next=selectInternetSim(policy,2);
|
||||
assert.deepEqual(next.connectivity,{strategy:'sim',sim_slot:2,activate:true,automatic:true,apn:null,apn1:'',apn2:'',preset_id:null});
|
||||
assert.equal(next.parameters,policy.parameters);assert.equal(policy.connectivity,connectivity);
|
||||
}
|
||||
const current=selectInternetSim(emptyEquipmentPolicy(),2);current.connectivity.apn='custom';
|
||||
assert.equal(selectInternetSim(current,2).connectivity.apn,'custom');
|
||||
assert.equal(selectInternetSim(current,1).connectivity.apn,null);
|
||||
});
|
||||
test('blank policy preserves settings; explicit zero remains present',()=>{
|
||||
const value=emptyEquipmentPolicy();assert.equal(policyError(value,fields),'');assert.deepEqual(value.parameters,{});
|
||||
value.parameters['25']=0;assert.equal(policyError(value,fields),'');
|
||||
value.parameters['25']=0.5;assert.notEqual(policyError(value,fields),'');
|
||||
});
|
||||
test('endpoint and APN must be concrete before saving',()=>{
|
||||
const value=emptyEquipmentPolicy();value.endpoint={host:'',port:0,slot:1};assert.notEqual(policyError(value,fields),'');
|
||||
value.endpoint={host:'track.example.test',port:9023,slot:2};assert.equal(policyError(value,fields),'');
|
||||
value.connectivity.strategy='manual';assert.notEqual(policyError(value,fields),'');
|
||||
value.connectivity.apn1='iot.example';assert.equal(policyError(value,fields),'');
|
||||
});
|
||||
test('equipment request has independent route, no Node identity, and preserves server errors',async()=>{
|
||||
const original=globalThis.fetch;const calls=[];
|
||||
try{
|
||||
globalThis.fetch=async(url,options)=>{calls.push({url,options});return new Response(JSON.stringify({detail:'Конфликт'}),{status:409});};
|
||||
await assert.rejects(equipmentRequest('/instances','POST',{candidate_id:'synthetic'}),/Конфликт/);
|
||||
assert.equal(calls[0].url,'/api/v1/fleet/equipment/instances');assert.equal(calls[0].options.cache,'no-store');
|
||||
}finally{globalThis.fetch=original;}
|
||||
});
|
||||
test('operator connectivity requires a selected preset and a valid SIM slot',()=>{
|
||||
const value=emptyEquipmentPolicy();value.connectivity={strategy:'operator',apn1:'',apn2:'',preset_id:null,sim_slot:2};
|
||||
assert.notEqual(policyError(value,fields),'');
|
||||
value.connectivity.preset_id='ru-mts-public-v1';assert.equal(policyError(value,fields),'');
|
||||
value.connectivity.sim_slot=3;assert.notEqual(policyError(value,fields),'');
|
||||
});
|
||||
test('network status distinguishes observed endpoint from verified write and whole profile',async()=>{
|
||||
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
assert.match(networkOperationMessage({id:'x',state:'verified',scope:'server1',verified_at:1,server1:{host:'example.test',port:9922}}),/Сервер 1 подтверждён/);
|
||||
assert.match(networkOperationMessage({id:'x',state:'uncertain',scope:'server1'}),/не подтверждён/);
|
||||
assert.match(networkOperationMessage({id:'x',state:'observed',scope:'server1',server1:{host:'example.test',port:9922}}),/прочитан/);
|
||||
});
|
||||
test('command receipt never claims a relay transition or a settings write',async()=>{
|
||||
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
for(const state of ['submitting','queued','dispatched','device_confirmed','device_rejected','expired','unconfirmed','uncertain']){
|
||||
const message=networkOperationMessage({id:'x',scope:'command',state});
|
||||
assert.doesNotMatch(message,/записи|адреса сервера|реле включено|реле выключено/i);
|
||||
}
|
||||
assert.match(networkOperationMessage({id:'x',scope:'command',state:'device_confirmed'}),/подтвердил приём/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'command',state:'unconfirmed'}),/не подтверждено/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'command',state:'uncertain'}),/повторения не будет/);
|
||||
});
|
||||
|
||||
test('full configuration distinguishes progress, readback and unchanged profile',async()=>{
|
||||
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
for(const state of ['queued','dispatched','uncertain','unconfirmed','expired','rejected'])assert.doesNotMatch(networkOperationMessage({id:'x',scope:'configuration',state,stage:'write'}),/записаны.*подтверждены/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'observed',record_count:207}),/207 параметров/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified'}),/повторным чтением/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified',unchanged:true}),/уже совпадают/);
|
||||
});
|
||||
|
||||
test('restart status requires fresh reconnection and never claims a hardware reset from ACK',async()=>{
|
||||
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const op={id:'x',scope:'command',command:{kind:'restart'}};
|
||||
assert.match(networkOperationMessage({...op,state:'dispatched'}),/Ожидаем свежие данные/);
|
||||
assert.match(networkOperationMessage({...op,state:'reconnected'}),/свежие данные по новому соединению/);
|
||||
assert.doesNotMatch(networkOperationMessage({...op,state:'device_confirmed'}),/перезапущен|снова в сети|свежие данные/);
|
||||
assert.match(networkOperationMessage({...op,state:'unconfirmed'}),/повторения не будет/);
|
||||
});
|
||||
|
||||
test('deadline stops progress without releasing the write interlock or inventing success',async()=>{
|
||||
const {networkOperationProgress}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const op={id:'x',scope:'configuration',state:'dispatched',stage:'preflight',created_at:100,expires_at:280};
|
||||
assert.deepEqual(networkOperationProgress(op,200),{pending:true,overdue:false,waiting:true,remaining:80});
|
||||
assert.deepEqual(networkOperationProgress(op,280),{pending:true,overdue:true,waiting:false,remaining:0});
|
||||
assert.equal(networkOperationProgress({...op,state:'unconfirmed'},300).pending,false);
|
||||
assert.equal(networkOperationProgress({...op,expires_at:undefined},340).overdue,true);
|
||||
assert.equal(networkOperationProgress(undefined,300).waiting,false);
|
||||
});
|
||||
test('only a terminal preflight timeout proves that configuration writing never began',async()=>{
|
||||
const {networkOperationMessage,configurationWriteNotStarted}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const op={id:'x',scope:'configuration',state:'unconfirmed',stage:'preflight',read_only:false};
|
||||
assert.equal(configurationWriteNotStarted(op),true);
|
||||
assert.match(networkOperationMessage(op),/Запись настроек не началась/);
|
||||
for(const change of [{state:'dispatched'},{state:'uncertain'},{stage:'write'},{stage:'verify'},{read_only:true},{scope:'command'}]){
|
||||
assert.equal(configurationWriteNotStarted({...op,...change}),false);
|
||||
assert.doesNotMatch(networkOperationMessage({...op,...change}),/Запись настроек не началась/);
|
||||
}
|
||||
});
|
||||
|
||||
test('SIM result requires modem confirmation and exposes restart wait',()=>{
|
||||
const op={id:'x',scope:'sim-selection',sim_slot:2};
|
||||
assert.match(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/ждём интернет через SIM 2/);
|
||||
assert.match(networkOperationMessage({...op,state:'uncertain',stage:'restart'}),/не подтверждён/);
|
||||
assert.match(networkOperationMessage({...op,state:'sim_selected',active_sim:2}),/SIM 2 подключена/);
|
||||
assert.match(networkOperationMessage({...op,state:'unconfirmed',stage:'preflight'}),/Запись настроек не началась/);
|
||||
});
|
||||
|
||||
test('saved settings are clean despite server key ordering and default expansion',()=>{
|
||||
const draft=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15,'50':7}},2);
|
||||
const server={schema_version:1,endpoint:null,connectivity:{strategy:'sim',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:2,activate:true,automatic:true},parameters:{'50':7,'25':15}};
|
||||
assert.equal(equipmentPolicyEqual(draft,server),true);
|
||||
assert.equal(equipmentPolicyEqual(emptyEquipmentPolicy(),{...emptyEquipmentPolicy(),connectivity:{strategy:'preserve',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:1,activate:false}}),true);
|
||||
assert.equal(equipmentPolicyEqual(draft,selectInternetSim(server,1)),false);
|
||||
assert.equal(equipmentPolicyEqual(draft,{...server,parameters:{'50':7,'25':16}}),false);
|
||||
});
|
||||
|
||||
test('explicit SIM intent survives unchanged settings but unrelated edits do not reselect',async()=>{
|
||||
const {simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const saved=selectInternetSim(emptyEquipmentPolicy(),1);
|
||||
assert.equal(simSelectionIntent(saved,saved,false),false);
|
||||
assert.equal(simSelectionIntent({...saved,parameters:{'25':16}},saved,false),false);
|
||||
assert.equal(simSelectionIntent(saved,saved,true),true);
|
||||
assert.equal(simSelectionIntent(selectInternetSim(saved,2),saved,false),true);
|
||||
assert.equal(simSelectionIntent({...saved,connectivity:{...saved.connectivity,apn:'new.apn'}},saved,false),true);
|
||||
assert.equal(simSelectionIntent(emptyEquipmentPolicy(),saved,true),false);
|
||||
});
|
||||
|
||||
for(const withoutApn of [false,true])test(`both-SIM permission (empty APN: ${withoutApn}) remains an explicit intent`,async()=>{
|
||||
const {allowBothInternetSims,simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
|
||||
const before=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15}},2);
|
||||
const both=allowBothInternetSims(before,withoutApn);
|
||||
assert.deepEqual(both.connectivity,{strategy:withoutApn?'native':'both',apn1:'',apn2:''});
|
||||
assert.equal(both.parameters,before.parameters);
|
||||
assert.equal(simSelectionIntent(both,before,false),true);
|
||||
assert.equal(simSelectionIntent(both,both,false),false);
|
||||
assert.equal(simSelectionIntent({...both,parameters:{'25':16}},both,false),false);
|
||||
assert.equal(simSelectionIntent(both,both,true),true);
|
||||
assert.equal(policyError(both,fields),'');
|
||||
const op={id:'x',scope:'sim-selection',sim_policy:'both',state:'sim_selected',active_sim:2};
|
||||
assert.match(networkOperationMessage(op),/Обе SIM разрешены/);
|
||||
assert.match(networkOperationMessage(op),/SIM 2/);
|
||||
assert.doesNotMatch(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/undefined/);
|
||||
});
|
||||
|
||||
test('durable SIM restart shows reconnect phase instead of generic command wait',()=>{
|
||||
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',sim_policy:'both',state:'dispatched',durable:true,runtime_phase:'executing',stage:'restart'}),/свежую связь после перезапуска/);
|
||||
});
|
||||
|
||||
test('automatic internet is an explicit profile choice and waiting identity is not success',()=>{
|
||||
const policy=selectInternetSim(emptyEquipmentPolicy(),1);
|
||||
assert.equal(policy.connectivity.automatic,true);
|
||||
assert.equal(equipmentPolicyEqual(policy,{...policy,connectivity:{...policy.connectivity,automatic:false}}),false);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'queued',durable:true,runtime_phase:'waiting-identity'}),/Ожидаем подтверждение карты/);
|
||||
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'rejected',reason:'sim_card_changed'}),/Карта.*изменилась/);
|
||||
});
|
||||
Reference in New Issue
Block a user