Compare commits
7
Commits
fb33a6d45c
...
03d44d0fb1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03d44d0fb1 | ||
|
|
21f46ac38a | ||
|
|
67ae1f4d77 | ||
|
|
031e01a99b | ||
|
|
f3a7592d90 | ||
|
|
d684eb7e05 | ||
|
|
b6efae3272 |
@@ -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};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {useEffect,useRef} from 'react';
|
||||
|
||||
/** Recover the existing renderer only after its own gateway is reachable again. */
|
||||
export function useMapRecovery(unavailable:boolean,retry:()=>void){
|
||||
const callback=useRef(retry);callback.current=retry;
|
||||
useEffect(()=>{
|
||||
if(!unavailable)return;
|
||||
let active=true;let timer:ReturnType<typeof setTimeout>;
|
||||
const abort=new AbortController();
|
||||
async function check(){
|
||||
try{
|
||||
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
|
||||
const value=response.ok?await response.json():null;
|
||||
if(active&&value?.ok===true){callback.current();return;}
|
||||
}catch{/* Retain the unavailable state; no public-provider fallback. */}
|
||||
if(active)timer=setTimeout(()=>void check(),30000);
|
||||
}
|
||||
timer=setTimeout(()=>void check(),30000);
|
||||
return()=>{active=false;abort.abort();clearTimeout(timer);};
|
||||
},[unavailable]);
|
||||
}
|
||||
@@ -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); }
|
||||
@@ -1,23 +1,34 @@
|
||||
import {useMemo,useRef,useState} from 'react';
|
||||
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera} from '@nodedc/map-cesium-react';
|
||||
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
|
||||
import {Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
|
||||
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
||||
import {defaultMapViewDocument} from '../../../core/map/mapView';
|
||||
import {useTrackerTelemetry} from '../../../core/fleet/vps';
|
||||
import {defaultMapViewDocument,encodeMapViewPut} from '../../../core/map/mapView';
|
||||
import {useMapRecovery} from '../../../core/map/useMapRecovery';
|
||||
import {mapPresentation} from '../../../components/map/mapPresentation';
|
||||
|
||||
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
|
||||
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
|
||||
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
|
||||
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
|
||||
const [camera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
|
||||
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:false});
|
||||
const ready=state.phase==='ready';
|
||||
const available=Object.values(state.providers).some(provider=>provider.phase==='ready');
|
||||
const [camera,setCamera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
|
||||
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:true});
|
||||
const telemetry=useTrackerTelemetry(vehicleID),centered=useRef(false);
|
||||
const pins=telemetry.items.flatMap(item=>item.position?[{id:item.instance_id,label:`${item.name} · ${item.position_fresh&&!telemetry.unavailable?item.position.source.toUpperCase():new Date(item.position.measured_at*1000).toLocaleTimeString('ru-RU')}`,longitude:item.position.longitude,latitude:item.position.latitude,heading_degrees:item.position.course,speed_meters_per_second:0}]:[]);
|
||||
const presentation=useMemo(()=>(encodeMapViewPut(defaultMapViewDocument()) as {view:{ghost_pins:MapGhostPinLayer}}).view.ghost_pins.presentation,[]);
|
||||
const markers:MapGhostPinLayer={anchor:null,radius_meters:0,simulation_enabled:false,pins,presentation:{...presentation,stem_height_meters:20,head_size_px:12,label_mode:'attributes',label_max_length:80}};
|
||||
function center(){const pin=pins[0];if(pin){setCamera({longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0});setGeneration(v=>v+1);}}
|
||||
useEffect(()=>{if(pins.length&&!centered.current){centered.current=true;center();}},[pins.length]);
|
||||
const latest=telemetry.items.find(item=>item.position);
|
||||
const positionLabel=telemetry.unavailable?'Обновление координат недоступно':latest?.position?`${latest.position.latitude.toFixed(6)}, ${latest.position.longitude.toFixed(6)} · ${latest.position.source.toUpperCase()} · ${latest.position.satellites??'—'} спутников · ${new Date(latest.position.measured_at*1000).toLocaleTimeString('ru-RU')}`:'Ожидание координат трекера';
|
||||
const available=state.phase==='ready'||Object.values(state.providers).some(provider=>provider.phase==='ready');
|
||||
const unavailable=!available&&state.phase!=='loading';
|
||||
useMapRecovery(unavailable,()=>setGeneration(v=>v+1));
|
||||
return <div className="observation-source">
|
||||
<ObservationHeader targets={header} live={ready} label={ready?'Карта доступна':state.phase==='loading'?'Загрузка карты':state.phase==='degraded'?'Часть слоёв недоступна':'Карта недоступна'}><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
|
||||
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
|
||||
{!available&&state.phase!=='loading'&&<div className="observation-source__notice"><p>Не удалось загрузить картографические слои.</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
|
||||
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
|
||||
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
|
||||
{unavailable&&<div className="observation-source__notice"><p>Картографические слои недоступны. Проверяем связь с сервером карты.</p><p>{positionLabel}</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
|
||||
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
|
||||
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
|
||||
</div>
|
||||
|
||||
@@ -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'}),/Карта.*изменилась/);
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
# NODE.DC Mission VPS Host 0.1.41
|
||||
|
||||
Version 0.1.41 completes the extracted transport observation batch before a
|
||||
socket closure cancels its sender. Closing a stream can no longer abandon a
|
||||
pending observation commit. All monitoring commands now wait for device input
|
||||
on their selected socket no older than five seconds, as configuration commands
|
||||
already did. Empty send queues alone are insufficient evidence of a live path.
|
||||
The pending intent and original attempt deadlines are preserved; device input
|
||||
wakes the sender without an extra probing command. This mitigates stale-stream
|
||||
dispatch but does not guarantee delivery on a cellular network.
|
||||
|
||||
Version 0.1.40 persists command transport observations separately from B2
|
||||
execution: prepared, written, TCP acknowledged, or unconfirmed with a reason.
|
||||
The Linux send-queue watchdog records when the complete command prefix was
|
||||
acknowledged; it never promotes the command to executed. Socket closure, expiry
|
||||
and process restart preserve uncertainty. Observations are available on command
|
||||
and operation APIs and attempt history, including late observations after a
|
||||
device reply. No payload, password, modem address or SIM identity is logged.
|
||||
Existing deadlines, retry policy and Core-to-VPS polling direction are unchanged.
|
||||
|
||||
|
||||
Version 0.1.39 adds engineering-only `probe-diagnostic-mode` (INTERNAL
|
||||
SERVER_COM `01 00`) for model 231 / firmware 0.01. A separately armed,
|
||||
authenticated observation ID is mandatory; exactly one command may consume
|
||||
each observation. Dispatch is restricted to an existing admitted connection,
|
||||
expires within three seconds, and is never replayed across reconnect/restart.
|
||||
Closing the observation prevents a queued dispatch. There is no raw-command
|
||||
input and this action is absent from the operator catalogue/durable operations.
|
||||
The 180-second lease bounds capture/dispatch, **not** the device's mode lifetime.
|
||||
A token receipt does not establish a mode change or fresh SIM identity.
|
||||
Physical qualification and termination semantics are recorded separately.
|
||||
|
||||
Version 0.1.35 publishes imported state with a single same-filesystem rename.
|
||||
A failed staging copy cannot expose a partial host identity, and restoration
|
||||
does not need a second full-size journal copy.
|
||||
|
||||
Version 0.1.34 adds portable, quiesced state export and empty-host import.
|
||||
The source stays fenced across service/OS restarts. TLS identity, ownership,
|
||||
registered devices and the entire durable journal move together. Import uses
|
||||
the exact matching installer and preserves the configured endpoint.
|
||||
|
||||
Version 0.1.33 makes service-code directory traversal independent of the root
|
||||
installer caller's umask. Private credentials and state retain their restricted
|
||||
permissions. It otherwise preserves the 0.1.32 durable maintenance runtime.
|
||||
|
||||
Version 0.1.31 accepts matching binary command token receipts through either
|
||||
admitted monitoring connection of the same B2, including a reconnected stream.
|
||||
ACK (code 6) remains distinct from a final result. Text replies, revoked devices,
|
||||
unknown sessions and other trackers cannot confirm a binary command.
|
||||
|
||||
Version 0.1.30 resumes only independent readback of a committed `configure-all`
|
||||
image after a VPS process restart or a new B2 connection, preserving its ID, target, original
|
||||
deadline and stage pacing. No image, SIM switch, restart or output action replays.
|
||||
Fresh readback can establish the target, the predecessor or an unknown image;
|
||||
an unavailable device still ends with an uncertain outcome. This is recovery of
|
||||
verification, not proof that the B2 modem can recover autonomously.
|
||||
|
||||
Version 0.1.29 additionally defers configuration commands on a silent monitoring
|
||||
stream until the B2 sends fresh input (within five monotonic seconds). A drained
|
||||
TCP queue alone does not prove a live cellular path. The original operation
|
||||
deadline is retained; dispatched stages never replay. Position/output command
|
||||
policy is unchanged. This is a transport admission guard, not a cellular latency
|
||||
guarantee.
|
||||
|
||||
Version 0.1.28 answers the observed empty HTTP opcode-7 request with current Unix
|
||||
UTC seconds from the owner's VPS, using the reference-qualified u32be envelope.
|
||||
Only an admitted model-231/0.01 identity with an active matching modem peer can
|
||||
receive it. It does not change settings, complete an operation or extend its
|
||||
deadline. The host clock must be correct. Device dialogue/repeated configuration
|
||||
acceptance is recorded separately; a clock response alone is not that acceptance.
|
||||
|
||||
Version 0.1.27 admits a new command only when the selected Linux socket has
|
||||
no unacknowledged kernel bytes or pending asyncio bytes. Among eligible streams
|
||||
the most recently active one wins. Blocked streams cannot steal a command from
|
||||
a drained stream; deadlines remain unchanged and dispatched commands never
|
||||
replay. Transport readiness does not confirm execution.
|
||||
|
||||
Version 0.1.26 adds immutable request deadlines for idempotent Core delivery,
|
||||
a durable bounded wait for undispatched position requests, and event-driven idle
|
||||
senders. Terminal operation history is indexed out of the packet/dispatch path.
|
||||
Commands already dispatched to a tracker are never automatically replayed.
|
||||
|
||||
The engineering `qualify_faults.py` harness checks crash recovery, lost HTTP
|
||||
responses, immutable expiry and no replay using the installed package with
|
||||
temporary SQLite and loopback sockets. It does not use production state or
|
||||
physical hardware. See [fault qualification](../../docs/arnavi_b2/FAULT_RECOVERY_20260927.md).
|
||||
|
||||
Version 0.1.25 bounds command bytes in the Linux TCP queue to the earlier of
|
||||
the operation deadline and 30 seconds after dispatch. HTTP settings replies
|
||||
have a 12-second transport bound, capped by the operation deadline. Monotonic
|
||||
watchdogs account for both asyncio and kernel buffers; abortive close prevents
|
||||
queued data from lingering after disconnect. TCP acknowledgement only releases
|
||||
the transport watchdog, never confirms device execution. Interrupted or expired
|
||||
actions are never replayed. Already received commands cannot be cancelled.
|
||||
|
||||
Version 0.1.24 adds exclusive SIM selection on qualified B2 model 231 / firmware
|
||||
0.01: fresh configuration preflight, one image write, exact readback, one restart,
|
||||
and fresh type-1 DS2 evidence of GPRS on the requested SIM over a new connection.
|
||||
The operation has a 360-second bound. Field 72 bits 10/20 prohibit data on the
|
||||
other SIM; this is not automatic failover. APNs and access credentials are kept
|
||||
unless explicitly edited. Interrupted writes/restarts are never replayed.
|
||||
Full cellular-only physical qualification is recorded separately in the ledger.
|
||||
|
||||
|
||||
Version 0.1.23 retains the independently registered numeric-ID reply, but removes
|
||||
the experimental empty settings response: physical 0.1.22 evidence showed an
|
||||
ID/settings loop, not completion. A settings image is still sent only during
|
||||
an explicit, bounded write. Startup qualification remains open.
|
||||
|
||||
Version 0.1.22 qualifies the continuous startup exchange: reply with the
|
||||
independently enrolled numeric device ID, then an empty settings response when
|
||||
no explicit image write is pending. Numeric IDs are immutable per IMEI and
|
||||
never inferred from its digits. Unknown IDs and unadmitted peers fail closed.
|
||||
An explicit pending write retains its single-image dispatch/readback contract.
|
||||
Physical qualification of the combined exchange is required before publication.
|
||||
|
||||
Version 0.1.21 admits the captured ten-byte command-1 response in a one-shot
|
||||
engineering lease. Its four-byte payload equals the independently known device
|
||||
ID. Product behavior is unchanged pending a fresh, unchanged device upload.
|
||||
|
||||
Version 0.1.20 admits one exact empty reply to the observed empty command-1
|
||||
request in the engineering observation lease. This follows the physical 2→1
|
||||
transition after an empty command-2 reply. No firmware image can be supplied,
|
||||
and normal product parsing remains closed until the exchange is qualified.
|
||||
|
||||
Version 0.1.19 admits one exact, zero-payload command-2 response only in
|
||||
the bounded engineering observation lease for no-image-response qualification.
|
||||
No product-channel behavior changes before physical verification.
|
||||
|
||||
Version 0.1.18 adds an engineering-only binary encoding of the documented
|
||||
read-only settings upload request (0109), to qualify post-restart behavior.
|
||||
It does not change the qualified product settings transport or retry writes.
|
||||
|
||||
Version 0.1.17 adds the qualified-model restart request (B2 manual §10, binary
|
||||
0107). Dispatch expires after three seconds; the request is never replayed.
|
||||
A token ACK is recorded separately. Only fresh type-1 telemetry measured after
|
||||
dispatch on a newly opened connection records return, with a 180-second deadline.
|
||||
This is observed network return, not proof of a hardware power cycle. Old sessions,
|
||||
archive packets and replies alone cannot complete the operation.
|
||||
|
||||
Version 0.1.16 spaces full-configuration stages and successive operations by
|
||||
15 seconds after each HTTP image exchange. The bench sometimes ignored a new
|
||||
SERV request shortly after an upload despite TCP acknowledgment. This pacing
|
||||
does not affect position/output commands or replay a settings write.
|
||||
|
||||
Version 0.1.15 adds complete configuration reads and profile writes on the
|
||||
qualified B2 model 231 / firmware 0.01 HTTP settings channel. It reads the
|
||||
current image before writing, requires an exact predecessor, preserves recovery
|
||||
channels, sends the image once and verifies by an independent full readback.
|
||||
Command-5 ACK is the captured seven-byte response with payload 01. Restart or
|
||||
timeout after dispatch does not silently replay a write. No manufacturer API
|
||||
is contacted by this runtime.
|
||||
|
||||
Version 0.1.14 chooses the active TCP session with the most recent incoming data
|
||||
for command dispatch. A half-open predecessor left by a device configuration
|
||||
reload cannot take a new command while a fresher session exists. It also allows
|
||||
a bounded engineering upload-ACK qualification using the observed reply-envelope
|
||||
structure, matching the complete validated upload body. Up to 64 observation
|
||||
leases are retained (four 16-KiB captures each); raw evidence remains private.
|
||||
|
||||
Version 0.1.13 qualifies the observed configuration reply framing with the
|
||||
shared B2 CRC/TLV codec. An engineering observation lease can serve a validated
|
||||
configuration once to a byte-identical admitted B2 settings request. Explicit
|
||||
close disarms the lease while retaining evidence. This is a real write path:
|
||||
prepare an exact baseline and rollback image and verify a fresh device upload;
|
||||
dispatch alone never establishes successful application. No vendor HTTP calls.
|
||||
|
||||
Version 0.1.12 additionally permits the documented `SERV*1.8` configuration
|
||||
download request for protocol qualification. It can apply a configuration from
|
||||
the device's configured endpoint; that endpoint must be owned and its payload
|
||||
qualified before use. The current observation lease serves only a captured
|
||||
identity answer, never a configuration. No firmware/erase/reset commands exist.
|
||||
|
||||
Version 0.1.11 adds an engineering-only, allowlisted B2 settings upload request
|
||||
(`SERV*1.9`), preserving active-session expiry and no replay. It also permits one
|
||||
captured seven-byte configuration identity answer to the exact corresponding
|
||||
21-byte request, under an authenticated 180-second observation lease. The device
|
||||
must be admitted; expiry, byte mismatch, duplicate HTTP framing and repeat
|
||||
dispatch fail closed. This is bounded protocol qualification, not a general
|
||||
proxy or full configuration support. The service never contacts a vendor.
|
||||
|
||||
Version 0.1.10 adds explicit `set-output` using the B2 manual section 10 FC
|
||||
command `password*SERV*8.PIN.STATE`. PIN4..6 only, strict boolean `enabled`,
|
||||
model 231 / firmware 0.01, instance password required. This sets a persistent
|
||||
output state; it is not a timed pulse or a physical-contact confirmation.
|
||||
It uses the existing active-session, three-second dispatch expiry and no-replay
|
||||
contract. Unknown fields and arbitrary commands are rejected. Bench operators
|
||||
must verify manual output mode and deliberately restore the observed baseline.
|
||||
|
||||
Version 0.1.9 adds the documented FC text encoding for the same bounded
|
||||
`pulse-output` operation: PIN4..6, 1..5 seconds, model 231 / firmware 0.01.
|
||||
An explicit `encoding: text` requires the instance's six-digit password; the
|
||||
generated command remains private. No arbitrary text is accepted. This format
|
||||
has no token-correlated confirmation: the receipt stays unconfirmed even when
|
||||
unrelated token or text replies arrive. Dispatch still requires a current
|
||||
session and expires after three seconds; commands never replay after restart.
|
||||
A text PIN5 pulse produced an operator- and subsequently camera-observed LED
|
||||
on/off transition. Earlier binary PIN4/PIN5 pulses had no visible effect.
|
||||
A token ACK alone is not relay feedback; other outputs require qualification.
|
||||
|
||||
Headless receiver owned by Mission Core, independently of any rover's onboard PC.
|
||||
Supported installation profile: **Ubuntu Server 24.04 amd64, Python 3.12,
|
||||
OpenSSL 3, systemd**. Other OS/architectures fail preflight. No pip, Docker, GUI,
|
||||
Node.js, compiler or vendor cloud is required. Minimal images missing OS
|
||||
prerequisites are rejected with the missing capability; no blind system repair.
|
||||
|
||||
## Reproduce
|
||||
|
||||
From this repository:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/build_vps_host.py --output /tmp/ndc-mission-vps.tar
|
||||
```
|
||||
|
||||
The builder produces both a `.tar` engineering archive and a single `.pyz`
|
||||
operator installer. Mission Core serves an explicitly published, checksum-verified
|
||||
`.pyz` in Equipment → root plus → VPS Host ARNavi. The same window contains the
|
||||
supported OS, installation instructions and pairing-key field. The installer
|
||||
carries no tracker identities, SIM data, address, keys or private evidence.
|
||||
|
||||
Copy the downloaded file to the VPS and run:
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --host trackers.example.org
|
||||
```
|
||||
|
||||
Use the actual downloaded filename. Omitting `--host` prompts for the public
|
||||
address. The wrapper runs the same preflight/plan/apply engine, with an exact
|
||||
plan digest; it does not require a separate installer GUI. The engineering tar
|
||||
retains the explicit plan/apply interface:
|
||||
|
||||
```sh
|
||||
python3 ndc-mission-vps/install.py plan --host trackers.example.org
|
||||
python3 ndc-mission-vps/install.py apply --host trackers.example.org --expect PLAN_SHA256
|
||||
```
|
||||
|
||||
Run apply as root. The exact current plan hash is required. DNS/IP is an install
|
||||
parameter, never source code. Use stable DNS so a VPS migration does not require
|
||||
rewriting thousands of trackers. Default ports: TCP 9922 (B2 INTERNAL), TLS 19443
|
||||
(Mission Core). Cloud firewall must allow these exact ports. The installer preserves existing services, including DeviceCore on 443/9921.
|
||||
For the detected legacy NODE.DC `nodedc_b2_vps` nftables policy it adds two
|
||||
comment-owned allow rules and a persistent include, checks predecessor hashes,
|
||||
and records a bounded rollback. It never flushes rules. Unknown firewall
|
||||
policies remain external and require public endpoint acceptance.
|
||||
Existing listener/foreign installation conflicts stop first install.
|
||||
|
||||
Installation paths:
|
||||
|
||||
- `/opt/nodedc-mission-vps/current`: immutable release selected by content digest.
|
||||
- **`/opt/nodedc-mission-vps/connect.key`**: fixed root-level pairing file,
|
||||
symlink to protected state; read as root.
|
||||
- `/var/lib/ndc-mission-vps`: host identity, TLS key, owner and durable journal,
|
||||
mode 0700, files 0600, owned by dedicated system user `ndc-mission-vps`.
|
||||
- `/etc/systemd/system/ndc-mission-vps.service`: versioned managed system unit.
|
||||
|
||||
Open an apparatus → Equipment → top plus → VPS Host ARNavi. Paste the key, choose a
|
||||
name and served apparatuses. It expires after 24 hours and is consumed once.
|
||||
The same VPS appears under every assigned rover. To attach an existing VPS to
|
||||
another rover, choose it in the connection dialog, or change the host's apparatus
|
||||
list in settings. One host retains one identity and one Mission Core owner.
|
||||
|
||||
An unused expired key can be renewed with the shipped CLI:
|
||||
|
||||
```sh
|
||||
cd /opt/nodedc-mission-vps/current
|
||||
sudo -u ndc-mission-vps /usr/bin/python3 -m ndc_vps invitation
|
||||
```
|
||||
|
||||
Paired hosts cannot silently regenerate/reassign ownership. Back up the whole
|
||||
private state directory and Mission Core fleet state. A new host has a new key.
|
||||
An update retains the same identity and queue. Applying the current release is
|
||||
a health-checking no-op. Failed updates restore the previous release and unit.
|
||||
Explicit rollback preserves private state and the journal:
|
||||
|
||||
```sh
|
||||
python3 ndc-mission-vps/install.py rollback --host trackers.example.org --expect INSTALLED_ARTIFACT_DIGEST
|
||||
```
|
||||
|
||||
For the first release rollback disables the new service; it does not delete
|
||||
identities, evidence or any unrelated service. Schema v1 updates are additive;
|
||||
a future incompatible migration must supply its own reversible migration.
|
||||
|
||||
## Clean product reinstallation
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --fresh
|
||||
```
|
||||
|
||||
This explicitly replaces this product's installation and identity. First the
|
||||
installer stops its own unit and creates a private, hash-recorded backup under
|
||||
`/var/backups/ndc-mission-vps/`. It preserves original application/state trees,
|
||||
then installs empty product state and creates a new pairing key. A failed fresh
|
||||
installation restores the backup and health-checks the old service. Foreign
|
||||
services and unrelated files are preserved. This is not an OS reimage.
|
||||
|
||||
In the Core admission form select the previous record under «После переустановки»
|
||||
and paste the new key. Replacement is explicit: duplicate live host records at
|
||||
the same endpoint are refused. The former record and telemetry journal remain
|
||||
in private history; only the newly paired identity is synchronized.
|
||||
|
||||
To restore a selected backup with the same installer:
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --host trackers.example.org --restore /var/backups/ndc-mission-vps/BACKUP_ID
|
||||
```
|
||||
|
||||
After a successful new pairing, restoring the server alone does not restore the
|
||||
Core's host registration. Restore a matching private Core fleet backup as part
|
||||
of disaster recovery; do not substitute identities or disclose tokens manually.
|
||||
|
||||
## Publish qualified downloads
|
||||
|
||||
The operator runtime keeps installers under its private fleet root, outside Git.
|
||||
Publishing a release only changes the download; it never installs on a board or
|
||||
VPS. Run the publisher with the exact SHA from the accepted build receipt:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/publish_fleet_installer.py \
|
||||
--fleet-root /path/to/operator/fleet --kind vps-arnavi \
|
||||
--file /path/to/qualified-vps.pyz --version 0.1.3 --sha256 ACCEPTED_SHA256
|
||||
```
|
||||
|
||||
For the onboard computer use `--kind node` and the version/SHA of the already
|
||||
qualified owner installer. Copy the finished installer back from the build host
|
||||
before publishing it. A source-build bundle is not an owner installer. Publishing
|
||||
the Node archive does not update the board. Catalog and download endpoints verify
|
||||
size and SHA; a missing or changed archive is unavailable instead of silently
|
||||
falling back to an older build.
|
||||
|
||||
## Tracker admission and delivery
|
||||
|
||||
Register/read a B2 over USB in Mission Core, select the registered VPS in its
|
||||
connection settings, save, then apply over USB. Slot 2 is initially proposed to
|
||||
preserve an existing slot 1. Profiles contain common settings, not IMEI/ICCID,
|
||||
SIM phone number or assignment. Firmware-qualified writer performs backup,
|
||||
identity/config preconditions, acknowledgement and independent readback.
|
||||
|
||||
Core synchronizes an allowlist of registered IMEIs assigned to that host's
|
||||
apparatuses and configured endpoint. Unknown devices receive no telemetry ACK.
|
||||
**IMEI is a claimed identity, not cryptographic tracker authentication**: legacy
|
||||
INTERNAL is plaintext. For untrusted deployments use an operator private APN or
|
||||
network protection; this release does not claim end-to-end tracker encryption.
|
||||
|
||||
VPS ACKs a B2 package only after a SQLite FULL commit. Core pulls a bounded batch,
|
||||
stores raw evidence, derives valid coordinates and advances its cursor in the
|
||||
same transaction, then acknowledges the VPS queue. Replays are idempotent;
|
||||
package sequence reuse cannot replace content. Header-time and package ACKs
|
||||
follow the published INTERNAL framing. No arbitrary tracker command API exists.
|
||||
|
||||
The authenticated VPS API also qualifies the allowlisted, read-only `GETP`
|
||||
command over an existing tracker TCP session. Commands have durable IDs and
|
||||
bounded expiry; a dispatched command is never automatically replayed after a
|
||||
restart. A text response means `reply_received`, not «settings applied».
|
||||
Version 0.1.6 adds the bounded `configure-server1` operation for B2 model 231 /
|
||||
firmware 0.01. Fresh GETP must match the expected primary endpoint and show this
|
||||
VPS as the secondary server. Only documented SETP #1 host/port is changed; a
|
||||
separate GETP must verify the endpoint and preservation of every other group.
|
||||
Operations bind to one TCP session, reject stale/duplicate responses, expire
|
||||
after 120 seconds and never replay writes after restart. Reversal is a separate
|
||||
preconditioned operation. FC has no correlation token: timestamp/session checks
|
||||
bound freshness but do not create cryptographic command attribution.
|
||||
Device clock skew is bounded to 10 seconds behind / 5 seconds ahead of VPS time;
|
||||
successive operation stages require strictly increasing device timestamps.
|
||||
After a dispatched SETP the host waits at least 15 seconds before its separate
|
||||
GETP. Only this read may bind to a new TCP session after tracker reconnection;
|
||||
SET P is never resent. Verification also runs when SETP's acknowledgement is lost.
|
||||
The 0.1.4 experiment stopped before writing because its timestamp comparison
|
||||
incorrectly required synchronized clocks; the measured B2 was about 4 s behind.
|
||||
|
||||
Full profiles, APN/active-channel migration, other server slots and disabling the
|
||||
vendor configurator remain unqualified. The authenticated API is private: raw
|
||||
GETP replies contain credentials and must never be proxied into the browser.
|
||||
See [network configuration audit](../../docs/arnavi_b2/NETWORK_CONFIGURATION.md).
|
||||
|
||||
The VPS queue has a 512 MiB budget and preserves a 256 MiB disk reserve. When
|
||||
full/unwritable it withholds ACK, never drops unconsumed packages. Receipts retain
|
||||
retransmission deduplication for seven days. Core must remain available often
|
||||
enough to drain the queue. Capacity for thousands of simultaneously active
|
||||
trackers has **not** been load-qualified; the first profile caps 256 connections
|
||||
and service memory at 192 MiB. Scale/retention qualification is a separate gate.
|
||||
|
||||
Core API uses TLS 1.3 with certificate fingerprint verified **before** sending a
|
||||
pairing secret or bearer token. Invitation is obtained through the owner's SSH
|
||||
channel. DNS resolves only to public IPv4. Redirects/ambient HTTP proxies are
|
||||
not followed. Node's private-network pairing contract is unchanged.
|
||||
|
||||
Coordinates are derived from valid packet tags. Missing/invalid/zero coordinates
|
||||
are not invented. Device measurement time and reception time remain separate;
|
||||
an older replay cannot move the map backwards in time. UI shows freshness and
|
||||
last contact, independently of the onboard computer.
|
||||
|
||||
## Acceptance boundary
|
||||
|
||||
`tests/test_vps_host.py` covers framing, partial TCP reads, checksum rejection,
|
||||
one-time enrollment, retry identity, admission, durable delivery, deduplication,
|
||||
Core cursor transaction, stale data and shared rover reassignment. Hardware and
|
||||
operator VPS acceptance are recorded separately in a private deployment ledger.
|
||||
A successful install on the existing Ubuntu VPS is not clean-image qualification.
|
||||
|
||||
## Portable transfer to a clean VPS
|
||||
|
||||
Use the same qualified installer file on both hosts. Upgrade the source to it
|
||||
first. Then on the source:
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --export-state /root/mission-vps-state.tar.gz
|
||||
```
|
||||
|
||||
This stops this service and persistently fences it before taking the snapshot.
|
||||
The source remains stopped, including after reboot. Export prints the archive's
|
||||
SHA-256. The archive contains credentials and the SQLite journal: keep it private
|
||||
and transfer it through the owner's SSH channel together with the installer.
|
||||
No executable, system unit, account ID or firewall configuration crosses hosts.
|
||||
A failure after fencing leaves the source stopped and preserves its state.
|
||||
|
||||
On the clean supported Ubuntu VPS:
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256
|
||||
```
|
||||
|
||||
Import checks the exact archive SHA, complete file manifest, matching installer
|
||||
release, TLS key/certificate identity and SQLite integrity before installation.
|
||||
Existing product paths are refused. It creates the system account, code and unit
|
||||
through the same installer and verifies service health. TLS identity and Core
|
||||
pairing survive; commands retain IDs, attempts, deadlines and stop markers.
|
||||
The normal runtime reconciles interrupted attempts; a snapshot is not proof of
|
||||
tracker execution. No old live TCP session is restored.
|
||||
|
||||
Keep the existing DNS name and ports, then direct that DNS name to the target
|
||||
after its health and external reachability checks. For an endpoint configured
|
||||
as a literal IP, this operation alone does not migrate Core or tracker addresses;
|
||||
a transferable IP or a separately verified endpoint change is required. Provider
|
||||
firewalls and DNS changes require their owner's controls/API and are not inferred
|
||||
from guest installation success. The receiving installation needs 2.25 GiB of
|
||||
free staging space; portable state is capped at 2 GiB.
|
||||
|
||||
To abandon migration, **stop the target first**, then explicitly resume the source:
|
||||
|
||||
```sh
|
||||
sudo python3 ndc-mission-vps.pyz --resume-source
|
||||
```
|
||||
|
||||
The source cannot observe the target across an outage. The installer therefore
|
||||
never resumes it automatically. Retain the private archive and exact installer
|
||||
for recovery. Do not run both identities simultaneously. A stale archive also
|
||||
cannot contain commands or confirmations recorded after its snapshot.
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Bounded migration of the observed NODE.DC B2 nftables policy; no flush."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG = Path("/etc/nftables.conf")
|
||||
FRAGMENT = Path("/etc/nftables.d/ndc-mission-vps.nft")
|
||||
BACKUP = Path("/opt/nodedc-mission-vps/firewall-before.json")
|
||||
INCLUDE = 'include "/etc/nftables.d/ndc-mission-vps.nft"'
|
||||
MARKER = "ndc-mission-vps-v1"
|
||||
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.run(args, check=True, capture_output=True, **kwargs)
|
||||
|
||||
|
||||
def plan():
|
||||
if not CONFIG.exists() or "table inet nodedc_b2_vps" not in CONFIG.read_text():
|
||||
# A clean host can use its own provider firewall. Unknown local policies
|
||||
# are not rewritten; public endpoint acceptance remains mandatory.
|
||||
return {"mode": "external", "config_sha256": None}
|
||||
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
||||
chain = next(x["chain"] for x in live["nftables"] if "chain" in x)
|
||||
if chain.get("policy") != "drop" or chain.get("hook") != "input":
|
||||
raise ValueError("unsupported legacy firewall policy")
|
||||
if FRAGMENT.exists() and MARKER not in FRAGMENT.read_text():
|
||||
raise ValueError("foreign firewall fragment conflict")
|
||||
return {
|
||||
"mode": "nodedc-b2-v1",
|
||||
"config_sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def rules(api, tracker):
|
||||
return (
|
||||
f"add rule inet nodedc_b2_vps input tcp dport {api} ct state new "
|
||||
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-api"\n'
|
||||
f"add rule inet nodedc_b2_vps input tcp dport {tracker} ct state new "
|
||||
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-tracker"\n'
|
||||
)
|
||||
|
||||
|
||||
def removal():
|
||||
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
||||
commands = []
|
||||
for item in live["nftables"]:
|
||||
rule = item.get("rule", {})
|
||||
if rule.get("comment") in (MARKER + "-api", MARKER + "-tracker"):
|
||||
commands.append(f"delete rule inet nodedc_b2_vps input handle {int(rule['handle'])}\n")
|
||||
return "".join(commands)
|
||||
|
||||
|
||||
def apply(proposal, api, tracker, atomic):
|
||||
if proposal["mode"] != "nodedc-b2-v1":
|
||||
return False
|
||||
if plan() != proposal:
|
||||
raise ValueError("firewall changed after plan")
|
||||
content = rules(api, tracker)
|
||||
if INCLUDE in CONFIG.read_text():
|
||||
if not FRAGMENT.exists() or FRAGMENT.read_text() != content:
|
||||
raise ValueError("managed firewall drift")
|
||||
# Reconcile only our named live rules if nftables was reloaded.
|
||||
run("nft", "-f", "-", input=(removal() + content).encode())
|
||||
return False
|
||||
original = CONFIG.read_text()
|
||||
desired = original.rstrip() + "\n\n" + INCLUDE + "\n"
|
||||
backup = {
|
||||
"before": original,
|
||||
"after_sha256": hashlib.sha256(desired.encode()).hexdigest(),
|
||||
"fragment_sha256": hashlib.sha256(content.encode()).hexdigest(),
|
||||
}
|
||||
atomic(BACKUP, json.dumps(backup).encode())
|
||||
FRAGMENT.parent.mkdir(mode=0o755, exist_ok=True)
|
||||
# Validate the live transaction before modifying persistent files.
|
||||
run("nft", "-c", "-f", "-", input=(removal() + content).encode())
|
||||
atomic(FRAGMENT, content.encode(), 0o644)
|
||||
atomic(CONFIG, desired.encode(), 0o644)
|
||||
run("nft", "-f", "-", input=(removal() + content).encode())
|
||||
return True
|
||||
|
||||
|
||||
def rollback(atomic):
|
||||
record = json.loads(BACKUP.read_text())
|
||||
if (
|
||||
hashlib.sha256(CONFIG.read_bytes()).hexdigest() != record["after_sha256"]
|
||||
or hashlib.sha256(FRAGMENT.read_bytes()).hexdigest() != record["fragment_sha256"]
|
||||
):
|
||||
raise ValueError("firewall changed; rollback will not overwrite foreign edits")
|
||||
commands = removal()
|
||||
if commands:
|
||||
run("nft", "-f", "-", input=commands.encode())
|
||||
atomic(CONFIG, record["before"].encode(), 0o644)
|
||||
FRAGMENT.unlink()
|
||||
@@ -0,0 +1,429 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Versioned Ubuntu 24.04 amd64 installer. Run plan, then apply its exact digest."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import pwd
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import firewall
|
||||
|
||||
ROOT = Path("/opt/nodedc-mission-vps")
|
||||
STATE = Path("/var/lib/ndc-mission-vps")
|
||||
UNIT = Path("/etc/systemd/system/ndc-mission-vps.service")
|
||||
USER = "ndc-mission-vps"
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
SERVICE = """# Managed by NODE.DC Mission VPS installer v1
|
||||
[Unit]
|
||||
Description=NODE.DC Mission VPS Host
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ndc-mission-vps
|
||||
Group=ndc-mission-vps
|
||||
WorkingDirectory=/opt/nodedc-mission-vps/current
|
||||
ExecStart=/usr/bin/python3 -m ndc_vps serve
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
ReadWritePaths=/var/lib/ndc-mission-vps
|
||||
MemoryMax=192M
|
||||
TasksMax=96
|
||||
LimitNOFILE=2048
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.run(args, check=True, capture_output=True, **kwargs)
|
||||
|
||||
|
||||
def digest():
|
||||
manifest = json.loads((SOURCE / "manifest.json").read_text())
|
||||
for name, expected in manifest["files"].items():
|
||||
if name.startswith("/") or ".." in Path(name).parts:
|
||||
raise ValueError("invalid manifest")
|
||||
if hashlib.sha256((SOURCE / name).read_bytes()).hexdigest() != expected:
|
||||
raise ValueError("artifact integrity mismatch")
|
||||
return hashlib.sha256((SOURCE / "manifest.json").read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def predecessor():
|
||||
return os.readlink(ROOT / "current") if (ROOT / "current").is_symlink() else None
|
||||
|
||||
|
||||
def plan(args):
|
||||
osrelease = dict(
|
||||
line.split("=", 1)
|
||||
for line in Path("/etc/os-release").read_text().splitlines()
|
||||
if "=" in line
|
||||
)
|
||||
if (
|
||||
osrelease.get("ID", "").strip('"') != "ubuntu"
|
||||
or osrelease.get("VERSION_ID", "").strip('"') != "24.04"
|
||||
or platform.machine() != "x86_64"
|
||||
):
|
||||
raise ValueError("supported environment: Ubuntu Server 24.04 amd64 only")
|
||||
if sys.version_info[:2] != (3, 12):
|
||||
raise ValueError("Python 3.12 required")
|
||||
for command in ("openssl", "systemctl", "useradd", "runuser"):
|
||||
if not shutil.which(command):
|
||||
raise ValueError("missing OS prerequisite: " + command)
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,48}", args.host):
|
||||
raise ValueError("public DNS name or IPv4 required (max 49 characters for B2)")
|
||||
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
|
||||
raise ValueError("foreign service conflict")
|
||||
if ROOT.exists() and not (ROOT / "installed.json").exists():
|
||||
raise ValueError("foreign installation root conflict")
|
||||
if STATE.exists() and not (STATE / "host.json").exists():
|
||||
raise ValueError("foreign state directory conflict")
|
||||
if (ROOT / "migration-fence.json").exists():
|
||||
raise ValueError("source fenced for migration; resume explicitly only with target stopped")
|
||||
old = predecessor()
|
||||
for port in (args.api_port, args.tracker_port):
|
||||
if port < 1024 or port > 65535:
|
||||
raise ValueError("ports must be 1024..65535")
|
||||
if not old:
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("0.0.0.0", port))
|
||||
if args.api_port == args.tracker_port:
|
||||
raise ValueError("ports must differ")
|
||||
configuration = {
|
||||
"public_host": args.host,
|
||||
"api_port": args.api_port,
|
||||
"tracker": {"host": args.host, "port": args.tracker_port},
|
||||
}
|
||||
if STATE.exists():
|
||||
existing = json.loads((STATE / "host.json").read_text())
|
||||
if any(existing[key] != val for key, val in configuration.items()):
|
||||
raise ValueError(
|
||||
"endpoint migration requires a separate planned operation; use stable DNS"
|
||||
)
|
||||
data = {
|
||||
"schema": "missioncore.vps-install-plan/v1",
|
||||
"firewall": firewall.plan(),
|
||||
"artifact": digest(),
|
||||
"previous": old,
|
||||
"configuration": configuration,
|
||||
"unit_sha256": hashlib.sha256(UNIT.read_bytes()).hexdigest() if UNIT.exists() else None,
|
||||
"environment": "ubuntu-24.04-amd64",
|
||||
"service": str(UNIT),
|
||||
"root": str(ROOT),
|
||||
"key_file": str(ROOT / "connect.key"),
|
||||
}
|
||||
data["plan_sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
|
||||
return data
|
||||
|
||||
|
||||
def atomic(path, value, mode=0o600):
|
||||
temporary = path.with_name(path.name + ".new")
|
||||
temporary.write_bytes(value)
|
||||
temporary.chmod(mode)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def select_release(release):
|
||||
temporary = ROOT / ".current"
|
||||
temporary.unlink(missing_ok=True)
|
||||
temporary.symlink_to(release)
|
||||
os.replace(temporary, ROOT / "current")
|
||||
|
||||
|
||||
def healthy():
|
||||
for _ in range(20):
|
||||
if subprocess.run(["systemctl", "is-active", "--quiet", "ndc-mission-vps"]).returncode == 0:
|
||||
try:
|
||||
config = json.loads((STATE / "host.json").read_text())
|
||||
ctx = ssl.create_default_context(cafile=str(STATE / "tls.crt"))
|
||||
ctx.check_hostname = False
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", config["api_port"]), 2) as sock,
|
||||
ctx.wrap_socket(sock) as secure,
|
||||
):
|
||||
secure.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n")
|
||||
if b"200 Result" in secure.recv(4096):
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise ValueError("service health check failed")
|
||||
|
||||
|
||||
def apply(args, proposal):
|
||||
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"]:
|
||||
raise ValueError("root and exact current plan digest required")
|
||||
old = proposal["previous"]
|
||||
installed = ROOT / "installed.json"
|
||||
if (
|
||||
old
|
||||
and Path(old).name == proposal["artifact"]
|
||||
and installed.exists()
|
||||
and json.loads(installed.read_text()).get("status") == "healthy"
|
||||
):
|
||||
healthy()
|
||||
print(json.dumps({"status": "already_current", "artifact": proposal["artifact"]}))
|
||||
return
|
||||
release = ROOT / "releases" / proposal["artifact"]
|
||||
ROOT.mkdir(mode=0o755, exist_ok=True)
|
||||
(ROOT / "releases").mkdir(mode=0o755, exist_ok=True)
|
||||
# mkdir's mode is filtered by the caller's umask. The unprivileged service
|
||||
# must traverse these owned code directories even under root's umask 0077.
|
||||
ROOT.chmod(0o755)
|
||||
(ROOT / "releases").chmod(0o755)
|
||||
old_unit = UNIT.read_bytes() if UNIT.exists() else None
|
||||
# Pre-create the ownership record: a failed first install can be inspected/retried.
|
||||
if not (ROOT / "installed.json").exists():
|
||||
atomic(
|
||||
ROOT / "installed.json",
|
||||
json.dumps({"schema": "missioncore.vps-install/v1", "status": "preparing"}).encode(),
|
||||
)
|
||||
try:
|
||||
pwd.getpwnam(USER)
|
||||
except KeyError:
|
||||
run("useradd", "--system", "--home-dir", str(STATE), "--shell", "/usr/sbin/nologin", USER)
|
||||
user = pwd.getpwnam(USER)
|
||||
if not release.exists():
|
||||
shutil.copytree(SOURCE, release, ignore=shutil.ignore_patterns("__pycache__"))
|
||||
release.chmod(0o755)
|
||||
for item in release.rglob("*"):
|
||||
item.chmod(0o755 if item.is_dir() else 0o644)
|
||||
if not STATE.exists():
|
||||
STATE.mkdir(mode=0o700)
|
||||
configuration = proposal["configuration"].copy()
|
||||
run(
|
||||
"openssl",
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"ed25519",
|
||||
"-nodes",
|
||||
"-days",
|
||||
"3650",
|
||||
"-subj",
|
||||
"/CN=NODE.DC Mission VPS Host",
|
||||
"-keyout",
|
||||
str(STATE / "tls.key"),
|
||||
"-out",
|
||||
str(STATE / "tls.crt"),
|
||||
)
|
||||
certificate = ssl.PEM_cert_to_DER_cert((STATE / "tls.crt").read_text())
|
||||
fingerprint = hashlib.sha256(certificate).hexdigest()
|
||||
configuration.update(
|
||||
fingerprint=fingerprint,
|
||||
host_id="vps_" + fingerprint,
|
||||
endpoint=f"https://{args.host}:{args.api_port}",
|
||||
)
|
||||
atomic(STATE / "host.json", json.dumps(configuration, indent=2).encode())
|
||||
os.chown(STATE, user.pw_uid, user.pw_gid)
|
||||
for item in STATE.iterdir():
|
||||
item.chmod(0o600)
|
||||
os.chown(item, user.pw_uid, user.pw_gid)
|
||||
if not (ROOT / "connect.key").is_symlink():
|
||||
(ROOT / "connect.key").symlink_to(STATE / "connect.key")
|
||||
firewall_added = False
|
||||
try:
|
||||
firewall_added = firewall.apply(
|
||||
proposal["firewall"], args.api_port, args.tracker_port, atomic
|
||||
)
|
||||
select_release(release)
|
||||
if not (STATE / "connect.key").exists():
|
||||
run(
|
||||
"runuser",
|
||||
"-u",
|
||||
USER,
|
||||
"--",
|
||||
"/usr/bin/python3",
|
||||
"-m",
|
||||
"ndc_vps",
|
||||
"invitation",
|
||||
cwd=release,
|
||||
)
|
||||
atomic(UNIT, SERVICE.encode(), 0o644)
|
||||
run("systemctl", "daemon-reload")
|
||||
run("systemctl", "enable", "ndc-mission-vps.service")
|
||||
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||
healthy()
|
||||
atomic(
|
||||
ROOT / "installed.json",
|
||||
json.dumps(
|
||||
{
|
||||
**proposal,
|
||||
"status": "healthy",
|
||||
"firewall_added": firewall_added,
|
||||
"installed_at": time.time(),
|
||||
},
|
||||
indent=2,
|
||||
).encode(),
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "healthy",
|
||||
"artifact": proposal["artifact"],
|
||||
"key_file": str(ROOT / "connect.key"),
|
||||
}
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
if firewall_added:
|
||||
firewall.rollback(atomic)
|
||||
if old:
|
||||
select_release(old)
|
||||
if old_unit:
|
||||
atomic(UNIT, old_unit, 0o644)
|
||||
run("systemctl", "daemon-reload")
|
||||
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||
healthy()
|
||||
else:
|
||||
subprocess.run(
|
||||
["systemctl", "disable", "--now", "ndc-mission-vps.service"], capture_output=True
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
def rollback(args):
|
||||
record = json.loads((ROOT / "installed.json").read_text())
|
||||
if os.geteuid() != 0 or args.expect != record["artifact"]:
|
||||
raise ValueError("root and installed artifact digest required")
|
||||
if record.get("firewall_added"):
|
||||
firewall.rollback(atomic)
|
||||
previous = record["previous"]
|
||||
if previous:
|
||||
path = Path(previous)
|
||||
if path.parent != ROOT / "releases" or not path.is_dir():
|
||||
raise ValueError("previous release unavailable")
|
||||
select_release(path)
|
||||
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||
healthy()
|
||||
else:
|
||||
run("systemctl", "disable", "--now", "ndc-mission-vps.service")
|
||||
# Preserve state, keys and journal even when uninstalling the first release.
|
||||
atomic(ROOT / "installed.json", json.dumps({**record, "status": "rolled_back"}).encode())
|
||||
print(json.dumps({"status": "rolled_back", "state_preserved": True}))
|
||||
|
||||
|
||||
BACKUPS = Path("/var/backups/ndc-mission-vps")
|
||||
|
||||
|
||||
def restore(backup):
|
||||
if os.geteuid() != 0 or backup.parent != BACKUPS or backup.is_symlink():
|
||||
raise ValueError("root and an installer-owned backup required")
|
||||
if (ROOT / "migration-fence.json").exists():
|
||||
raise ValueError("source fenced for migration")
|
||||
record = json.loads((backup / "backup.json").read_text())
|
||||
if record.get("schema") != "missioncore.vps-backup/v1":
|
||||
raise ValueError("invalid backup")
|
||||
# Verify before stopping anything. Never overwrite a foreign service.
|
||||
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
|
||||
raise ValueError("foreign service conflict")
|
||||
for name, expected in record["files"].items():
|
||||
file = backup / name
|
||||
if ".." in Path(name).parts or file.is_symlink():
|
||||
raise ValueError("invalid backup file")
|
||||
if hashlib.sha256(file.read_bytes()).hexdigest() != expected:
|
||||
raise ValueError("backup integrity mismatch")
|
||||
run("systemctl", "stop", "ndc-mission-vps.service")
|
||||
recovery = backup / ("replaced-" + uuid.uuid4().hex)
|
||||
recovery.mkdir(mode=0o700)
|
||||
for name, target in (("root", ROOT), ("state", STATE), ("unit", UNIT)):
|
||||
if target.exists():
|
||||
shutil.move(str(target), recovery / name)
|
||||
source = backup / name
|
||||
if source.is_dir():
|
||||
shutil.copytree(source, target, symlinks=True)
|
||||
else:
|
||||
shutil.copy2(source, target)
|
||||
user = pwd.getpwnam(USER)
|
||||
os.chown(STATE, user.pw_uid, user.pw_gid)
|
||||
for file in STATE.iterdir():
|
||||
os.chown(file, user.pw_uid, user.pw_gid)
|
||||
run("systemctl", "daemon-reload")
|
||||
run("systemctl", "enable", "ndc-mission-vps.service")
|
||||
run("systemctl", "restart", "ndc-mission-vps.service")
|
||||
healthy()
|
||||
print(json.dumps({"status": "restored", "backup": str(backup)}))
|
||||
|
||||
|
||||
def fresh(args, proposal):
|
||||
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"] or not proposal["previous"]:
|
||||
raise ValueError("fresh replacement requires an exact plan of an installed product")
|
||||
BACKUPS.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
backup = BACKUPS / (time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:8])
|
||||
backup.mkdir(mode=0o700)
|
||||
run("systemctl", "stop", "ndc-mission-vps.service")
|
||||
try:
|
||||
for name, path in (("root", ROOT), ("state", STATE)):
|
||||
shutil.copytree(path, backup / name, symlinks=True)
|
||||
shutil.copy2(UNIT, backup / "unit")
|
||||
files = {
|
||||
str(p.relative_to(backup)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in backup.rglob("*")
|
||||
if p.is_file() and not p.is_symlink()
|
||||
}
|
||||
atomic(
|
||||
backup / "backup.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": "missioncore.vps-backup/v1",
|
||||
"created_at": time.time(),
|
||||
"monotonic": time.monotonic(),
|
||||
"files": files,
|
||||
}
|
||||
).encode(),
|
||||
)
|
||||
except Exception:
|
||||
run("systemctl", "start", "ndc-mission-vps.service")
|
||||
raise
|
||||
try:
|
||||
# Complete verified private copy exists; move original trees too, never wildcard-delete.
|
||||
shutil.move(str(ROOT), backup / "original-root")
|
||||
shutil.move(str(STATE), backup / "original-state")
|
||||
shutil.move(str(UNIT), backup / "original-unit")
|
||||
new_plan = plan(args)
|
||||
args.expect = new_plan["plan_sha256"]
|
||||
apply(args, new_plan)
|
||||
except Exception:
|
||||
restore(backup)
|
||||
raise
|
||||
print(json.dumps({"status": "fresh_install", "backup": str(backup)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("plan", "apply", "rollback"))
|
||||
parser.add_argument("--host", required=True)
|
||||
parser.add_argument("--api-port", type=int, default=19443)
|
||||
parser.add_argument("--tracker-port", type=int, default=9922)
|
||||
parser.add_argument("--expect")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.action == "rollback":
|
||||
rollback(args)
|
||||
else:
|
||||
proposal = plan(args)
|
||||
if args.action == "plan":
|
||||
print(json.dumps(proposal, indent=2))
|
||||
else:
|
||||
apply(args, proposal)
|
||||
except Exception as error:
|
||||
print("Installation stopped: " + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Headless NODE.DC Mission VPS Host; Python 3.12 standard library only."""
|
||||
|
||||
VERSION = "0.1.41"
|
||||
@@ -0,0 +1,19 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from .service import Service
|
||||
from .store import Store
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("serve", "invitation", "status"))
|
||||
parser.add_argument("--state", default="/var/lib/ndc-mission-vps")
|
||||
args = parser.parse_args()
|
||||
store = Store(args.state)
|
||||
if args.action == "serve":
|
||||
asyncio.run(Service(store).run())
|
||||
elif args.action == "invitation":
|
||||
store.invitation()
|
||||
print("Invitation ready in /opt/nodedc-mission-vps/connect.key (valid 24 hours).")
|
||||
else:
|
||||
print(json.dumps(store.status()))
|
||||
@@ -0,0 +1,120 @@
|
||||
"""B2 manual §10 + INTERNAL SERVER_COM token envelope; no arbitrary commands."""
|
||||
|
||||
import re
|
||||
import secrets
|
||||
|
||||
KINDS = {
|
||||
"request-position",
|
||||
"restart",
|
||||
"pulse-output",
|
||||
"set-output",
|
||||
"upload-configuration",
|
||||
"download-configuration",
|
||||
"probe-diagnostic-mode",
|
||||
}
|
||||
|
||||
|
||||
def prepare(body):
|
||||
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||
raise ValueError("unqualified action firmware")
|
||||
allowed = {"id", "imei", "kind", "model", "firmware"}
|
||||
if body["kind"] == "probe-diagnostic-mode":
|
||||
# INTERNAL SERVER_COM 01 00. Engineering qualification only: neither
|
||||
# a SIM read nor a promise about this firmware's mode/termination.
|
||||
# Admission additionally requires an explicit live observation lease.
|
||||
allowed.add("observation_id")
|
||||
if not isinstance(body.get("observation_id"), str) or not re.fullmatch(
|
||||
r"[a-f0-9]{32}", body["observation_id"]
|
||||
):
|
||||
raise ValueError("diagnostic probe requires observation")
|
||||
command = b"\x01\x00"
|
||||
elif body["kind"] == "request-position":
|
||||
command = b"\x01\x01"
|
||||
elif body["kind"] == "restart":
|
||||
# B2 manual §10. A token receipt is not proof of a completed restart.
|
||||
command = b"\x01\x07"
|
||||
elif body["kind"] == "upload-configuration" and body.get("encoding") == "binary":
|
||||
# Documented read-only counterpart to SERV*1.9; no image is written.
|
||||
allowed.add("encoding")
|
||||
command = b"\x01\x09"
|
||||
elif body["kind"] in ("upload-configuration", "download-configuration"):
|
||||
allowed.add("password")
|
||||
password = body.get("password")
|
||||
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||
raise ValueError("invalid password")
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown action fields")
|
||||
# B2 manual §10: synchronize with the configured web endpoint. Download
|
||||
# may apply settings: the endpoint owns staged data and readback checks.
|
||||
number = 9 if body["kind"] == "upload-configuration" else 8
|
||||
return {"encoding": "text", "binary": f"{password}*SERV*1.{number}".encode().hex()}
|
||||
elif body["kind"] == "set-output":
|
||||
allowed |= {"pin", "enabled", "encoding", "password"}
|
||||
pin = body.get("pin")
|
||||
enabled = body.get("enabled")
|
||||
if type(pin) is not int or pin not in (4, 5, 6):
|
||||
raise ValueError("unsupported output")
|
||||
if type(enabled) is not bool:
|
||||
raise ValueError("enabled must be boolean")
|
||||
if body.get("encoding", "text") != "text":
|
||||
raise ValueError("set-output requires text encoding")
|
||||
password = body.get("password")
|
||||
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||
raise ValueError("invalid password")
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown action fields")
|
||||
# B2 manual section 10: explicit, persistent low-side output state.
|
||||
# The caller must request both transitions; there is no implicit retry.
|
||||
return {
|
||||
"encoding": "text",
|
||||
"binary": f"{password}*SERV*8.{pin}.{int(enabled)}".encode("ascii").hex(),
|
||||
}
|
||||
elif body["kind"] == "pulse-output":
|
||||
allowed |= {"pin", "seconds", "encoding"}
|
||||
pin, seconds = body["pin"], body["seconds"]
|
||||
if type(pin) is not int or pin not in (4, 5, 6):
|
||||
raise ValueError("unsupported output")
|
||||
if type(seconds) is not int or not 1 <= seconds <= 5:
|
||||
raise ValueError("pulse must be 1..5 seconds")
|
||||
command = bytes((0x18, pin, 0, seconds))
|
||||
encoding = body.get("encoding", "binary")
|
||||
if encoding not in ("binary", "text"):
|
||||
raise ValueError("unsupported action encoding")
|
||||
if encoding == "text":
|
||||
allowed.add("password")
|
||||
password = body.get("password")
|
||||
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
|
||||
raise ValueError("invalid password")
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown action fields")
|
||||
# B2 manual §10: FC text has no token envelope. A reply to an
|
||||
# unrelated command must never turn this into confirmed actuation.
|
||||
return {
|
||||
"encoding": "text",
|
||||
"binary": f"{password}*SERV*24.{pin}.0.{seconds}".encode("ascii").hex(),
|
||||
}
|
||||
else:
|
||||
raise ValueError("unsupported action")
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown action fields")
|
||||
result = {"token": secrets.randbits(32), "binary": command.hex()}
|
||||
if body["kind"] == "probe-diagnostic-mode":
|
||||
result["observation_id"] = body["observation_id"]
|
||||
return result
|
||||
|
||||
|
||||
def frame(value):
|
||||
if value.get("encoding") == "text":
|
||||
raw = bytes.fromhex(value["binary"])
|
||||
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
|
||||
raw = b"\xff" + value["token"].to_bytes(4, "little") + bytes.fromhex(value["binary"])
|
||||
return bytes((0x7B, len(raw), 0xFF, sum(raw) % 256)) + raw + b"}"
|
||||
|
||||
|
||||
def confirmations(raw):
|
||||
offset = 2
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
if raw[offset] == 9 and size == 5:
|
||||
yield raw[offset + 7], int.from_bytes(raw[offset + 8 : offset + 12], "little")
|
||||
offset += size + 8
|
||||
@@ -0,0 +1,585 @@
|
||||
"""Durable allowlisted B2 operations; no firmware or arbitrary text commands."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
|
||||
from . import actions, configuration, full_configuration, restart, sim_guard, sim_selection
|
||||
from .delivery import MAX_DELIVERY_SECONDS
|
||||
from .observation import Observation
|
||||
from .transport_evidence import TransportEvidence
|
||||
from .web_protocol import decode_request, numeric_id_reply, time_reply
|
||||
|
||||
COMMAND_SESSION_MAX_IDLE = 5
|
||||
CONFIGURATION_KINDS = full_configuration.KINDS | {
|
||||
"read-settings",
|
||||
"configure-server1",
|
||||
"upload-configuration",
|
||||
"download-configuration",
|
||||
}
|
||||
|
||||
|
||||
def frame(text):
|
||||
raw = text.encode("cp1251")
|
||||
if not 1 <= len(raw) <= 255:
|
||||
raise ValueError("command length")
|
||||
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
|
||||
|
||||
|
||||
class Commands:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
self.transport = TransportEvidence(store)
|
||||
self.sim_guard = sim_guard.SimGuard(store)
|
||||
self.sessions = {}
|
||||
self.session_started = {}
|
||||
self.session_activity = {}
|
||||
self.session_peers = {}
|
||||
self.session_ready = {}
|
||||
with store.db() as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS commands(id TEXT PRIMARY KEY, imei TEXT NOT NULL, "
|
||||
"digest TEXT NOT NULL, body TEXT NOT NULL)"
|
||||
)
|
||||
db.execute(
|
||||
"CREATE INDEX IF NOT EXISTS commands_active "
|
||||
"ON commands(imei,json_extract(body,'$.state'))"
|
||||
)
|
||||
# Effectful stages never replay. A committed full-image write may
|
||||
# resume its independent readback within the original deadline.
|
||||
for identifier, body in db.execute(
|
||||
"SELECT id,body FROM commands "
|
||||
"WHERE json_extract(body,'$.state') IN ('queued','dispatched')"
|
||||
).fetchall():
|
||||
value = json.loads(body)
|
||||
value = self.settle(db, identifier, value)
|
||||
if self.verification_recoverable(value):
|
||||
self.recover_verification(value)
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
elif (
|
||||
value["kind"] in actions.KINDS - {"request-position"}
|
||||
and value["state"] == "queued"
|
||||
):
|
||||
value.update(state="expired", reason="host_restarted")
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
elif (
|
||||
value["state"] == "dispatched"
|
||||
or value.get("stage") in ("write", "verify", "restart")
|
||||
and value["state"] == "queued"
|
||||
):
|
||||
value.update(state="uncertain", reason="host_restarted")
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def verification_recoverable(value):
|
||||
return (
|
||||
value["kind"] == "configure-all"
|
||||
and value.get("stage") == "verify"
|
||||
and bool(value.get("write_reply_sent_at"))
|
||||
and value["state"] in ("queued", "dispatched")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def recover_verification(value):
|
||||
value.update(
|
||||
state="queued",
|
||||
recovery_verification=True,
|
||||
recovery_at=time.time(),
|
||||
recovery_count=value.get("recovery_count", 0) + 1,
|
||||
not_before=max(value.get("not_before", 0), value.get("dispatched_at", 0) + 15),
|
||||
)
|
||||
value.pop("session", None)
|
||||
|
||||
def submit(self, body):
|
||||
# The original absolute deadline survives a lost HTTP reply and retry.
|
||||
# Keep it in the idempotency digest, outside the device command payload.
|
||||
original = body
|
||||
body = dict(body)
|
||||
not_after = body.pop("not_after", None)
|
||||
if not_after is not None and (
|
||||
type(not_after) not in (int, float) or not math.isfinite(not_after) or not_after <= 0
|
||||
):
|
||||
raise ValueError("invalid command deadline")
|
||||
identifier, imei = body["id"], body["imei"]
|
||||
kind = body["kind"]
|
||||
password = body.get("password", "")
|
||||
if (
|
||||
not re.fullmatch(r"[a-f0-9]{32}", identifier)
|
||||
or kind
|
||||
not in actions.KINDS | full_configuration.KINDS | {"read-settings", "configure-server1"}
|
||||
or not self.store.admitted(imei)
|
||||
):
|
||||
raise ValueError("unsupported command")
|
||||
if kind not in actions.KINDS and not re.fullmatch(r"[0-9]{6}", password):
|
||||
raise ValueError("invalid password")
|
||||
allowed = {"id", "imei", "password", "kind"}
|
||||
details = {}
|
||||
if kind in actions.KINDS:
|
||||
details = actions.prepare(body)
|
||||
allowed = set(body)
|
||||
elif kind in full_configuration.KINDS:
|
||||
details = full_configuration.prepare(body)
|
||||
allowed = set(body)
|
||||
elif kind == "configure-server1":
|
||||
allowed |= {"expected", "target", "model", "firmware"}
|
||||
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||
raise ValueError("unqualified firmware")
|
||||
details = {
|
||||
"expected": configuration.endpoint(body["expected"]),
|
||||
"target": configuration.endpoint(body["target"]),
|
||||
"stage": "preflight",
|
||||
}
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown command fields")
|
||||
payload = password + "*GETP"
|
||||
digest = hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest()
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
previous = db.execute(
|
||||
"SELECT digest,body FROM commands WHERE id=?", (identifier,)
|
||||
).fetchone()
|
||||
if previous:
|
||||
if previous[0] != digest:
|
||||
raise ValueError("idempotency conflict")
|
||||
value = self.public(self.settle(db, identifier, json.loads(previous[1])))
|
||||
value["transport"] = self.transport.read(db, identifier)
|
||||
return value
|
||||
if not_after is not None and not_after > time.time() + 600:
|
||||
raise ValueError("command deadline too distant")
|
||||
expired = not_after is not None and not_after <= time.time()
|
||||
if (
|
||||
not expired
|
||||
and kind in (actions.KINDS | full_configuration.KINDS) - {"request-position"}
|
||||
and not self.sessions.get(imei)
|
||||
):
|
||||
raise ValueError("device has no active session")
|
||||
last_configuration_at = 0
|
||||
for (encoded,) in db.execute("SELECT body FROM commands WHERE imei=?", (imei,)):
|
||||
pending = json.loads(encoded)
|
||||
if pending["kind"] in full_configuration.KINDS:
|
||||
last_configuration_at = max(
|
||||
last_configuration_at,
|
||||
pending.get("configuration_received_at", 0),
|
||||
pending.get("write_reply_sent_at", 0),
|
||||
)
|
||||
if not expired and self.active(db, imei):
|
||||
raise ValueError("command already pending")
|
||||
value = {
|
||||
"id": identifier,
|
||||
"kind": kind,
|
||||
**details,
|
||||
"state": "queued",
|
||||
"payload": payload,
|
||||
"password": password,
|
||||
"created_at": time.time(),
|
||||
"expires_at": time.time() + 120,
|
||||
"replies": [],
|
||||
"response_hashes": [],
|
||||
}
|
||||
if kind in actions.KINDS:
|
||||
value.update(expires_at=time.time() + 30, dispatch_deadline=time.time() + 3)
|
||||
if kind == "request-position":
|
||||
# A read may wait for reconnection until its original expiry.
|
||||
# Once dispatched it is never replayed, even after a crash.
|
||||
value["dispatch_deadline"] = value["expires_at"]
|
||||
if kind == "restart":
|
||||
value["expires_at"] = time.time() + 180
|
||||
value["allowed_sessions"] = list(self.sessions.get(imei, ()))
|
||||
value.pop("payload")
|
||||
value.pop("password")
|
||||
elif kind in full_configuration.KINDS:
|
||||
value["expires_at"] = time.time() + (360 if kind == "select-sim" else 180)
|
||||
value["not_before"] = last_configuration_at + 15
|
||||
if not_after is not None:
|
||||
value["expires_at"] = min(value["expires_at"], not_after)
|
||||
if "dispatch_deadline" in value:
|
||||
value["dispatch_deadline"] = min(value["dispatch_deadline"], not_after)
|
||||
if expired:
|
||||
value.update(state="expired", reason="request_deadline")
|
||||
elif kind == "probe-diagnostic-mode":
|
||||
lease_end = Observation.diagnostic_lease(
|
||||
db, value["observation_id"], identifier, bind_imei=imei
|
||||
)
|
||||
value["expires_at"] = min(value["expires_at"], lease_end)
|
||||
value["dispatch_deadline"] = min(value["dispatch_deadline"], lease_end)
|
||||
db.execute(
|
||||
"INSERT INTO commands VALUES(?,?,?,?)",
|
||||
(identifier, imei, digest, json.dumps(value)),
|
||||
)
|
||||
return self.public(value)
|
||||
|
||||
def settle(self, db, identifier, value):
|
||||
state = self.public(value)["state"]
|
||||
if state != value["state"]:
|
||||
value = {**value, "state": state}
|
||||
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
return value
|
||||
|
||||
def active(self, db, imei):
|
||||
# Terminal history never enters the per-packet/per-session hot path.
|
||||
rows = db.execute(
|
||||
"SELECT id,body FROM commands WHERE imei=? "
|
||||
"AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid",
|
||||
(imei,),
|
||||
).fetchall()
|
||||
result = []
|
||||
for identifier, encoded in rows:
|
||||
value = self.settle(db, identifier, json.loads(encoded))
|
||||
if value["state"] in ("queued", "dispatched"):
|
||||
result.append((identifier, value))
|
||||
return result
|
||||
|
||||
def wait_delay(self, imei):
|
||||
with self.store.db() as db:
|
||||
# Idle senders sleep until admission, a packet or a new command.
|
||||
# Active staged operations retain their existing bounded timers.
|
||||
return 1 if self.active(db, imei) else None
|
||||
|
||||
@staticmethod
|
||||
def public(value):
|
||||
value = dict(value)
|
||||
if (
|
||||
value["state"] == "queued"
|
||||
and value.get("dispatch_deadline", float("inf")) < time.time()
|
||||
):
|
||||
value["state"] = "expired"
|
||||
if value["expires_at"] < time.time() and value["state"] in ("queued", "dispatched"):
|
||||
value["state"] = (
|
||||
"uncertain"
|
||||
if value.get("write_reply_sent_at") or value.get("stage") == "restart"
|
||||
else "expired"
|
||||
if value["state"] == "queued"
|
||||
else "unconfirmed"
|
||||
)
|
||||
hidden = {
|
||||
"payload",
|
||||
"password",
|
||||
"before",
|
||||
"after",
|
||||
"response_hashes",
|
||||
"session",
|
||||
"binary",
|
||||
"token",
|
||||
"allowed_sessions",
|
||||
"restart_sessions",
|
||||
"target_configuration",
|
||||
"before_configuration",
|
||||
"sim_guard",
|
||||
}
|
||||
return {**{k: v for k, v in value.items() if k not in hidden}, "transport": []}
|
||||
|
||||
def get(self, identifier):
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT body FROM commands WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("unknown command")
|
||||
value = self.public(self.settle(db, identifier, json.loads(row[0])))
|
||||
value["transport"] = self.transport.read(db, identifier)
|
||||
return value
|
||||
|
||||
def take(self, imei, session="test"):
|
||||
delivery = self.take_delivery(imei, session)
|
||||
return delivery[0] if delivery else None
|
||||
|
||||
def take_delivery(self, imei, session, *, with_receipt=False):
|
||||
# A configuration reload can leave half-open old sockets beside the new
|
||||
# live ones. Never let whichever sender wakes first steal the command.
|
||||
active = tuple(self.sessions.get(imei, ()))
|
||||
eligible = [s for s in active if self.session_ready.get((imei, s), True)]
|
||||
if active and session not in eligible:
|
||||
return None
|
||||
observed = [s for s in eligible if (imei, s) in self.session_activity]
|
||||
if observed and session != max(
|
||||
observed, key=lambda s: (self.session_activity.get((imei, s), 0), s)
|
||||
):
|
||||
return None
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
for identifier, value in self.active(db, imei):
|
||||
if (
|
||||
self.verification_recoverable(value)
|
||||
and value["state"] == "dispatched"
|
||||
and session != value.get("session")
|
||||
and self.session_started.get((imei, session), 0) > value.get("monotonic", 0)
|
||||
):
|
||||
# A new B2 connection can outlive a half-open predecessor.
|
||||
# Only the independent read migrates, never the image write.
|
||||
self.recover_verification(value)
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
if (
|
||||
value["state"] == "queued"
|
||||
and value.get("dispatch_deadline", float("inf")) < time.time()
|
||||
):
|
||||
value["state"] = "expired"
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
continue
|
||||
if (
|
||||
value["kind"] == "configure-server1"
|
||||
and value.get("stage") == "write"
|
||||
and value["state"] == "dispatched"
|
||||
and time.time() - value["dispatched_at"] >= 15
|
||||
):
|
||||
# SETP may reconnect before its reply. Read-only verification can
|
||||
# move to a new TCP session; the write itself is never resent.
|
||||
value.update(stage="verify", state="queued")
|
||||
value.pop("session", None)
|
||||
if (
|
||||
value["state"] != "queued"
|
||||
or value["expires_at"] < time.time()
|
||||
or value.get("not_before", 0) > time.time()
|
||||
):
|
||||
continue
|
||||
if value.get("session") and value["session"] != session:
|
||||
continue
|
||||
if (
|
||||
value["kind"] in actions.KINDS - {"request-position"}
|
||||
and session not in value["allowed_sessions"]
|
||||
):
|
||||
continue
|
||||
if value["kind"] == "request-position" and session not in active:
|
||||
continue
|
||||
if value["kind"] in CONFIGURATION_KINDS and active:
|
||||
last_input = self.session_activity.get((imei, session))
|
||||
if last_input is None or not (
|
||||
0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
|
||||
):
|
||||
# A drained but silent TCP stream may already be dead.
|
||||
# Await fresh device input; retain the original deadline
|
||||
# and never replay a previously dispatched stage.
|
||||
continue
|
||||
if not self.store.admitted(imei):
|
||||
return None
|
||||
if value["kind"] == "probe-diagnostic-mode":
|
||||
try:
|
||||
Observation.diagnostic_lease(db, value["observation_id"], identifier)
|
||||
except ValueError:
|
||||
value.update(state="expired", reason="observation_closed")
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
continue
|
||||
if value.get("sim_guard") and value.get("stage") in ("write", "restart"):
|
||||
guard = self.sim_guard.check(imei, value["sim_guard"], db=db)
|
||||
if guard != "matched":
|
||||
if guard == "changed":
|
||||
value.update(state="rejected", reason="sim_card_changed")
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?",
|
||||
(json.dumps(value), identifier),
|
||||
)
|
||||
continue
|
||||
value.update(
|
||||
state="dispatched",
|
||||
dispatched_at=time.time(),
|
||||
monotonic=time.monotonic(),
|
||||
session=session,
|
||||
)
|
||||
restarting = value["kind"] == "restart" or (
|
||||
value["kind"] == "select-sim" and value.get("stage") == "restart"
|
||||
)
|
||||
if restarting:
|
||||
value["restart_sessions"] = list(self.sessions.get(imei, ()))
|
||||
if value["kind"] == "configure-server1":
|
||||
value["payload"] = configuration.payload(value)
|
||||
if value["stage"] == "write":
|
||||
value["write_dispatched_at"] = time.time()
|
||||
elif value["kind"] in full_configuration.KINDS and not restarting:
|
||||
value["payload"] = full_configuration.payload(value)
|
||||
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
data = (
|
||||
actions.frame(value)
|
||||
if value["kind"] in actions.KINDS or restarting
|
||||
else frame(value["payload"])
|
||||
)
|
||||
deadline = value["monotonic"] + min(
|
||||
MAX_DELIVERY_SECONDS, max(0, value["expires_at"] - value["dispatched_at"])
|
||||
)
|
||||
if with_receipt:
|
||||
ticket = self.transport.prepare(db, identifier, value.get("stage", "execute"))
|
||||
return data, deadline, ticket
|
||||
return data, deadline
|
||||
return None
|
||||
|
||||
def web_receive(self, raw, peer, *, with_deadline=False):
|
||||
"""Qualified B2 HTTP channel, scoped to an admitted active modem peer."""
|
||||
expires = time.time() + 12
|
||||
|
||||
def result(reply):
|
||||
if reply is None or not with_deadline:
|
||||
return reply
|
||||
return reply, time.monotonic() + max(0, expires - time.time())
|
||||
|
||||
imei, command, payload = decode_request(raw)
|
||||
if not self.store.admitted(imei) or not any(
|
||||
self.session_peers.get((imei, s)) == peer for s in tuple(self.sessions.get(imei, ()))
|
||||
):
|
||||
return None
|
||||
reply = bytes.fromhex("5b00030006025d") if command == 6 else None
|
||||
if command == 1:
|
||||
number = self.store.numeric_id(imei)
|
||||
return result(numeric_id_reply(number) if number is not None else None)
|
||||
if command == 7:
|
||||
# A clock request is independent of a settings transaction. It
|
||||
# cannot advance its stage, confirm a write or extend its deadline.
|
||||
return result(time_reply(int(time.time())))
|
||||
if command == 5:
|
||||
reply = bytes.fromhex("5b00030005015d")
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
for identifier, value in self.active(db, imei):
|
||||
if (
|
||||
value["kind"] not in full_configuration.KINDS
|
||||
or value["state"] != "dispatched"
|
||||
or value["expires_at"] <= time.time()
|
||||
):
|
||||
continue
|
||||
if command == 5 and value["stage"] in ("preflight", "verify"):
|
||||
full_configuration.upload(value, payload)
|
||||
elif command == 2 and value["stage"] == "write":
|
||||
guard = self.sim_guard.check(imei, value.get("sim_guard"), db=db)
|
||||
if guard != "matched":
|
||||
# No image bytes leave the process for a missing/replaced card.
|
||||
value.update(
|
||||
state="rejected" if guard == "changed" else "unconfirmed",
|
||||
reason="sim_card_changed"
|
||||
if guard == "changed"
|
||||
else "sim_identity_unavailable",
|
||||
)
|
||||
reply = None
|
||||
else:
|
||||
reply = full_configuration.download(value)
|
||||
else:
|
||||
continue
|
||||
expires = min(expires, value["expires_at"])
|
||||
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
break
|
||||
return result(reply)
|
||||
|
||||
def receive(self, imei, raw, session="test"):
|
||||
self.sim_guard.observe(imei, raw)
|
||||
self.receive_actions(imei, raw, session)
|
||||
started = self.session_started.get((imei, session))
|
||||
if started is not None:
|
||||
with self.store.db(write=True) as db:
|
||||
for identifier, value in self.active(db, imei):
|
||||
matched = (
|
||||
self.sim_guard.check(
|
||||
imei, value.get("sim_guard"), after=value.get("dispatched_at"), db=db
|
||||
)
|
||||
== "matched"
|
||||
)
|
||||
if (
|
||||
restart.observe(value, raw, session, started)
|
||||
or matched
|
||||
and sim_selection.observe(value, raw, session, started)
|
||||
):
|
||||
if value.get("sim_guard") and value["state"] == "sim_selected":
|
||||
value["sim_guard_verified"] = True
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
# Preserve text response evidence privately, never interpret receipt as settings applied.
|
||||
offset, replies = 2, []
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
if raw[offset] == 3:
|
||||
replies.append(
|
||||
(
|
||||
int.from_bytes(raw[offset + 3 : offset + 7], "little"),
|
||||
raw[offset + 7 : offset + 7 + size].decode("cp1251", errors="replace"),
|
||||
)
|
||||
)
|
||||
offset += size + 8
|
||||
if not replies:
|
||||
return
|
||||
with self.store.db(write=True) as db:
|
||||
for identifier, value in self.active(db, imei):
|
||||
if (
|
||||
value["kind"] in actions.KINDS | full_configuration.KINDS
|
||||
or value["state"] != "dispatched"
|
||||
or value["expires_at"] < time.time()
|
||||
or value.get("session") != session
|
||||
):
|
||||
continue
|
||||
accepted = []
|
||||
for measured, reply in replies:
|
||||
digest = hashlib.sha256(f"{measured}:{reply}".encode()).hexdigest()
|
||||
if (
|
||||
# This B2 timestamps text about 4 s behind the VPS clock.
|
||||
# Bound skew and require strictly newer evidence at every stage.
|
||||
measured < int(value["dispatched_at"]) - 10
|
||||
or measured > time.time() + 5
|
||||
or measured <= value.get("last_response_measured", 0)
|
||||
or digest in value.get("response_hashes", [])
|
||||
):
|
||||
continue
|
||||
value.setdefault("response_hashes", []).append(digest)
|
||||
if value["kind"] == "configure-server1":
|
||||
if configuration.response(value, reply, self.store.config["tracker"]):
|
||||
accepted.append(reply)
|
||||
break # Never use two messages from one packet for separate stages.
|
||||
elif reply.startswith("#1="):
|
||||
accepted.append(reply)
|
||||
if not accepted:
|
||||
continue
|
||||
value["last_response_measured"] = measured
|
||||
if value["kind"] == "read-settings":
|
||||
value.update(state="reply_received", replies=accepted)
|
||||
elif value["stage"] == "verify" and value["state"] == "queued":
|
||||
value.pop("session", None)
|
||||
value["not_before"] = max(
|
||||
value.get("not_before", 0), value["write_dispatched_at"] + 15
|
||||
)
|
||||
value.update(received_at=time.time())
|
||||
db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
|
||||
def receive_actions(self, imei, raw, session):
|
||||
replies = list(actions.confirmations(raw))
|
||||
# B2 publishes the same token receipt through both monitoring streams.
|
||||
# Correlate the device and token, not the socket that carried the request.
|
||||
# Text commands still have no such correlation and are excluded below.
|
||||
if (
|
||||
not replies
|
||||
or session not in self.sessions.get(imei, ())
|
||||
or not self.store.admitted(imei)
|
||||
):
|
||||
return
|
||||
with self.store.db(write=True) as db:
|
||||
for identifier, value in self.active(db, imei):
|
||||
if (
|
||||
value["kind"] not in actions.KINDS
|
||||
or value.get("encoding") == "text"
|
||||
or value["state"] != "dispatched"
|
||||
or value["expires_at"] < time.time()
|
||||
):
|
||||
continue
|
||||
for code, token in replies:
|
||||
if token != value["token"] or code > 9:
|
||||
continue
|
||||
value.update(
|
||||
received_at=time.time(),
|
||||
roundtrip_seconds=time.monotonic() - value["monotonic"],
|
||||
device_code=code,
|
||||
reply_via_alternate_session=session != value.get("session"),
|
||||
)
|
||||
if code == 6 or value["kind"] == "restart" and code == 0:
|
||||
value.setdefault("device_accepted_at", time.time())
|
||||
else:
|
||||
value["state"] = "device_confirmed" if code == 0 else "device_rejected"
|
||||
db.execute(
|
||||
"UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)
|
||||
)
|
||||
break
|
||||
@@ -0,0 +1,85 @@
|
||||
"""B2 231 / 0.01: documented SETP #1 only, with a surviving secondary uplink.
|
||||
|
||||
Never translate USB field numbers into SETP groups. No generic command escape.
|
||||
GETP contains secrets; only the explicit endpoint projection may reach Core UI.
|
||||
"""
|
||||
|
||||
import re
|
||||
import time
|
||||
|
||||
|
||||
def endpoint(value):
|
||||
if not isinstance(value, dict) or set(value) != {"host", "port"}:
|
||||
raise ValueError("invalid endpoint")
|
||||
host, port = value["host"], value["port"]
|
||||
if (
|
||||
not isinstance(host, str)
|
||||
or not 1 <= len(host) <= 32
|
||||
or not re.fullmatch(r"[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*", host)
|
||||
or type(port) is not int
|
||||
or not 1 <= port <= 65535
|
||||
):
|
||||
raise ValueError("invalid endpoint")
|
||||
return {"host": host, "port": port}
|
||||
|
||||
|
||||
def groups(reply):
|
||||
if not isinstance(reply, str) or not reply.startswith("#") or len(reply) > 4096:
|
||||
raise ValueError("invalid GETP")
|
||||
result = {}
|
||||
for part in reply.split("#")[1:]:
|
||||
key, sep, value = part.partition("=")
|
||||
if not sep or not key.isdecimal() or key in result:
|
||||
raise ValueError("invalid GETP group")
|
||||
result[key] = value
|
||||
if not {"1", "2", "5", "7", "26"} <= result.keys():
|
||||
raise ValueError("incomplete GETP")
|
||||
return result
|
||||
|
||||
|
||||
def server(value):
|
||||
parts = value.split(",")
|
||||
# Preserve the undocumented fifth value, accept only the qualified empty form.
|
||||
if len(parts) != 5 or parts[2:] != ["0", "0", ""]:
|
||||
raise ValueError("unsupported server settings")
|
||||
return endpoint({"host": parts[0], "port": int(parts[1])})
|
||||
|
||||
|
||||
def response(operation, reply, tracker):
|
||||
"""Advance only from complete, scoped read evidence. Caller persists atomically."""
|
||||
try:
|
||||
actual = groups(reply)
|
||||
primary, secondary = server(actual["1"]), server(actual["26"])
|
||||
except (ValueError, KeyError):
|
||||
return False
|
||||
stage = operation["stage"]
|
||||
if stage == "preflight":
|
||||
if primary != operation["expected"] or secondary != endpoint(tracker):
|
||||
operation.update(state="rejected", reason="configuration_changed")
|
||||
elif primary == operation["target"]:
|
||||
operation.update(state="verified", verified_at=time.time(), server1=primary)
|
||||
else:
|
||||
operation.update(before=actual, stage="write", state="queued")
|
||||
elif stage == "write":
|
||||
# SETP acknowledgement is never enough: issue a separate GETP after a drain interval.
|
||||
operation.update(stage="verify", state="queued", not_before=time.time() + 3)
|
||||
elif stage == "verify":
|
||||
before = operation["before"]
|
||||
preserved = {k: v for k, v in actual.items() if k != "1"} == {
|
||||
k: v for k, v in before.items() if k != "1"
|
||||
}
|
||||
operation["after"] = actual
|
||||
if primary == operation["target"] and preserved:
|
||||
operation.update(state="verified", verified_at=time.time(), server1=primary)
|
||||
elif actual == before:
|
||||
operation.update(state="not_applied", reason="settings_unchanged")
|
||||
else:
|
||||
operation.update(state="uncertain", reason="readback_mismatch")
|
||||
return True
|
||||
|
||||
|
||||
def payload(operation):
|
||||
if operation["stage"] == "write":
|
||||
target = operation["target"]
|
||||
return f"{operation['password']}*SETP*#1={target['host']},{target['port']}"
|
||||
return operation["password"] + "*GETP"
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Bound the lifetime of command bytes in a Linux TCP send queue.
|
||||
|
||||
TCP acknowledgement is transport evidence only, never command confirmation.
|
||||
All writes on the guarded stream must pass through write(), including ACKs.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import fcntl
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
MAX_DELIVERY_SECONDS = 30
|
||||
|
||||
|
||||
def queued_bytes(sock):
|
||||
if sys.platform != "linux":
|
||||
# Production is qualified on Ubuntu only. Other platforms conservatively
|
||||
# retain the deadline, without claiming TCP acknowledgement evidence.
|
||||
return None
|
||||
return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0]
|
||||
|
||||
|
||||
class Delivery:
|
||||
def __init__(self, writer):
|
||||
self.writer = writer
|
||||
self.sock = writer.get_extra_info("socket")
|
||||
# Also abort queued kernel data on EOF, task cancellation and shutdown.
|
||||
# transport.abort() alone discards only asyncio's own write buffer.
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
|
||||
if sys.platform == "linux":
|
||||
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000)
|
||||
self.written = 0
|
||||
self.pending = deque()
|
||||
self.timer = None
|
||||
|
||||
def ready(self):
|
||||
"""Do not enqueue a new command behind an unacknowledged stream prefix.
|
||||
|
||||
This is Linux transport admission, not device execution confirmation.
|
||||
Non-Linux engineering tests retain their conservative expiry watchdog.
|
||||
"""
|
||||
if self.writer.is_closing() or self.writer.transport.get_write_buffer_size():
|
||||
return False
|
||||
try:
|
||||
queued = queued_bytes(self.sock)
|
||||
return queued is None or queued == 0
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def write(self, data, deadline=None, observe=None):
|
||||
started = time.monotonic()
|
||||
|
||||
def note(phase, reason=None):
|
||||
if observe is not None:
|
||||
observe(phase, time.time(), time.monotonic() - started, reason)
|
||||
|
||||
if deadline is not None and deadline <= time.monotonic():
|
||||
note("unconfirmed", "expired_before_write")
|
||||
self.abort()
|
||||
raise TimeoutError("command delivery expired before write")
|
||||
try:
|
||||
self.writer.write(data)
|
||||
except (OSError, RuntimeError):
|
||||
note("unconfirmed", "write_failed")
|
||||
raise
|
||||
note("written")
|
||||
self.written += len(data)
|
||||
if deadline is not None:
|
||||
self.pending.append((self.written, deadline, note))
|
||||
self.check()
|
||||
|
||||
def check(self):
|
||||
self.cancel_timer()
|
||||
if not self.pending:
|
||||
return
|
||||
if self.writer.is_closing():
|
||||
self.abort()
|
||||
return
|
||||
try:
|
||||
queued = queued_bytes(self.sock)
|
||||
if queued is not None:
|
||||
acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size()
|
||||
while self.pending and self.pending[0][0] <= acknowledged:
|
||||
self.pending.popleft()[2]("tcp_acknowledged")
|
||||
if self.pending:
|
||||
remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic()
|
||||
if remaining <= 0:
|
||||
self.abort("delivery_deadline")
|
||||
else:
|
||||
self.timer = asyncio.get_running_loop().call_later(
|
||||
min(0.25, remaining), self.check
|
||||
)
|
||||
except OSError:
|
||||
self.abort("socket_error")
|
||||
|
||||
def cancel_timer(self):
|
||||
if self.timer is not None:
|
||||
self.timer.cancel()
|
||||
self.timer = None
|
||||
|
||||
def abort(self, reason="connection_closed"):
|
||||
self.cancel_timer()
|
||||
while self.pending:
|
||||
self.pending.popleft()[2]("unconfirmed", reason)
|
||||
self.writer.transport.abort()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Whole-image B2 transactions: fresh preflight, one write, independent readback."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import time
|
||||
|
||||
from . import sim_guard, sim_selection
|
||||
from .usb_protocol import decode_configuration
|
||||
from .web_protocol import settings_reply
|
||||
|
||||
KINDS = {"read-configuration", "configure-all", "select-sim"}
|
||||
|
||||
|
||||
def prepare(body):
|
||||
allowed = {"id", "imei", "kind", "password", "model", "firmware"}
|
||||
if body.get("model") != 231 or body.get("firmware") != "0.01":
|
||||
raise ValueError("unqualified configuration firmware")
|
||||
result = {"stage": "preflight"}
|
||||
if body["kind"] in ("configure-all", "select-sim"):
|
||||
allowed |= {"expected_sha256", "target_configuration"}
|
||||
if not re.fullmatch(r"[a-f0-9]{64}", body["expected_sha256"]):
|
||||
raise ValueError("invalid predecessor")
|
||||
raw = bytes.fromhex(body["target_configuration"])
|
||||
config = decode_configuration(raw)
|
||||
settings_reply(config) # transport-size admission, without a write
|
||||
result.update(expected_sha256=body["expected_sha256"], target_configuration=raw.hex())
|
||||
if "sim_guard" in body:
|
||||
allowed.add("sim_guard")
|
||||
result["sim_guard"] = sim_guard.prepare(body["sim_guard"])
|
||||
if body["kind"] != "select-sim" or body.get("sim_slot") != result["sim_guard"]["slot"]:
|
||||
raise ValueError("SIM guard requires exclusive selection of the same slot")
|
||||
if body["kind"] == "select-sim":
|
||||
allowed |= {"sim_slot", "sim_policy"}
|
||||
mask = (1 << 10) | (1 << 20)
|
||||
policy = body.get("sim_policy", "exclusive")
|
||||
if policy == "both":
|
||||
if "sim_slot" in body or config.integer(72, 4) & mask:
|
||||
raise ValueError("both SIMs must be permitted without an exclusive slot")
|
||||
result["sim_policy"] = policy
|
||||
elif policy == "exclusive":
|
||||
slot = body.get("sim_slot")
|
||||
if type(slot) is not int or slot not in (1, 2):
|
||||
raise ValueError("invalid SIM slot")
|
||||
if config.integer(72, 4) & mask != 1 << (20 if slot == 1 else 10):
|
||||
raise ValueError("SIM flags do not match requested slot")
|
||||
result["sim_slot"] = slot
|
||||
else:
|
||||
raise ValueError("invalid SIM policy")
|
||||
if set(body) - allowed:
|
||||
raise ValueError("unknown configuration fields")
|
||||
return result
|
||||
|
||||
|
||||
def payload(value):
|
||||
number = 8 if value["stage"] == "write" else 9
|
||||
return value["password"] + f"*SERV*1.{number}"
|
||||
|
||||
|
||||
def upload(value, raw):
|
||||
config = decode_configuration(raw)
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
value.update(
|
||||
configuration=raw.hex(), configuration_sha256=digest, configuration_received_at=time.time()
|
||||
)
|
||||
if value["kind"] == "read-configuration":
|
||||
value.update(state="observed", verified_at=time.time())
|
||||
elif value["stage"] == "preflight":
|
||||
value["before_configuration"] = raw.hex()
|
||||
target = decode_configuration(bytes.fromhex(value["target_configuration"]))
|
||||
# Preserve every unknown field and the recovery channels. Core controls
|
||||
# the reviewed profile fields; network migration of these requires its
|
||||
# own destination-admission transaction, not a blind full-image write.
|
||||
critical = (3, 4, 5, 8, 70, 71)
|
||||
if (
|
||||
digest != value["expected_sha256"]
|
||||
or [r.number for r in config.records] != [r.number for r in target.records]
|
||||
or any(config.value(n) != target.value(n) for n in critical)
|
||||
):
|
||||
value.update(state="rejected", reason="configuration_predecessor_mismatch")
|
||||
elif raw.hex() == value["target_configuration"]:
|
||||
value.update(state="verified", verified_at=time.time(), unchanged=True)
|
||||
if value["kind"] == "select-sim":
|
||||
sim_selection.queue_restart(value)
|
||||
else:
|
||||
value.update(state="queued", stage="write", not_before=time.time() + 15)
|
||||
value.pop("session", None)
|
||||
elif value["stage"] == "verify":
|
||||
state = (
|
||||
"verified"
|
||||
if raw.hex() == value["target_configuration"]
|
||||
else "not_applied"
|
||||
if raw.hex() == value["before_configuration"]
|
||||
else "uncertain"
|
||||
)
|
||||
value.update(state=state, verified_at=time.time())
|
||||
if state == "verified" and value["kind"] == "select-sim":
|
||||
sim_selection.queue_restart(value)
|
||||
|
||||
|
||||
def download(value):
|
||||
"""Call only inside the durable transaction, before writing the HTTP socket."""
|
||||
if value.get("write_reply_sent_at"):
|
||||
return None
|
||||
raw = settings_reply(decode_configuration(bytes.fromhex(value["target_configuration"])))
|
||||
value.update(
|
||||
write_reply_sent_at=time.time(),
|
||||
write_reply_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
stage="verify",
|
||||
state="queued",
|
||||
not_before=time.time() + 15,
|
||||
)
|
||||
value.pop("session", None)
|
||||
return raw
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Explicit, bounded interoperability evidence on the owned socket.
|
||||
|
||||
Disabled unless the authenticated owner arms a 180-second lease. Unknown traffic
|
||||
is never treated as telemetry. A captured identity reply may be replayed once,
|
||||
only to the byte-identical request of an admitted device. No vendor connection.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from .web_protocol import decode_request, decode_settings_reply
|
||||
|
||||
|
||||
class Observation:
|
||||
@staticmethod
|
||||
def diagnostic_lease(db, identifier, command_id, *, bind_imei=None):
|
||||
"""One fixed diagnostic command per explicitly armed evidence window.
|
||||
|
||||
Expiry bounds our dispatch/capture, not the device's service mode.
|
||||
No repeated toggle, arbitrary payload, or automatic device restart.
|
||||
"""
|
||||
if not db.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='observations'"
|
||||
).fetchone():
|
||||
raise ValueError("diagnostic observation unavailable")
|
||||
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("diagnostic observation unavailable")
|
||||
value = json.loads(row[0])
|
||||
if value["expires_at"] <= time.time() or value.get("reference"):
|
||||
raise ValueError("diagnostic observation unavailable")
|
||||
bound = value.get("diagnostic_command_id")
|
||||
if bound not in (None, command_id) or bind_imei is None and bound != command_id:
|
||||
raise ValueError("diagnostic observation already used")
|
||||
if bind_imei is not None:
|
||||
value.update(diagnostic_command_id=command_id, diagnostic_imei=bind_imei)
|
||||
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
return value["expires_at"]
|
||||
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
with store.db() as db:
|
||||
db.execute("CREATE TABLE IF NOT EXISTS observations(id TEXT PRIMARY KEY, body TEXT)")
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS observation_data(lease TEXT, sequence INTEGER, "
|
||||
"raw BLOB, metadata TEXT, PRIMARY KEY(lease,sequence))"
|
||||
)
|
||||
|
||||
def arm(self, body):
|
||||
if set(body) not in ({"id"}, {"id", "reference"}) or not re.fullmatch(
|
||||
r"[a-f0-9]{32}", body["id"]
|
||||
):
|
||||
raise ValueError("invalid observation")
|
||||
reference = body.get("reference")
|
||||
if "reference" in body:
|
||||
if not isinstance(reference, dict) or set(reference) != {"request", "response"}:
|
||||
raise ValueError("invalid reference")
|
||||
request = bytes.fromhex(reference["request"])
|
||||
response = bytes.fromhex(reference["response"])
|
||||
imei, command, _ = decode_request(request, observe_empty_check=True)
|
||||
if not self.store.admitted(imei):
|
||||
raise ValueError("unqualified reference exchange")
|
||||
if command == 6 and response == bytes.fromhex("5b00030006025d"):
|
||||
pass
|
||||
elif command == 1 and (
|
||||
response == bytes.fromhex("5b000200015d")
|
||||
or (
|
||||
len(response) == 10
|
||||
and response[:5] == bytes.fromhex("5b00060001")
|
||||
and response[-1:] == b"]"
|
||||
and int.from_bytes(response[5:9], "big") > 0
|
||||
)
|
||||
):
|
||||
# The captured four-byte response equals the bench's numeric
|
||||
# device ID. Qualify its exact replay once; no image payload.
|
||||
pass
|
||||
elif command == 2:
|
||||
if response != bytes.fromhex("5b000200025d"):
|
||||
decode_settings_reply(response)
|
||||
# Bounded qualification of a zero-payload no-image response.
|
||||
# Not admitted in the normal product channel until physically
|
||||
# verified; no CRC image or device configuration is supplied.
|
||||
elif command == 5 and response == bytes.fromhex("5b00030005015d"):
|
||||
# Byte-exact command-5 reply captured from the manufacturer
|
||||
# for the owner-approved return of its own configuration.
|
||||
pass
|
||||
else:
|
||||
raise ValueError("unqualified reference exchange")
|
||||
now = time.time()
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
if db.execute("SELECT 1 FROM observations WHERE id=?", (body["id"],)).fetchone():
|
||||
previous = json.loads(
|
||||
db.execute(
|
||||
"SELECT body FROM observations WHERE id=?", (body["id"],)
|
||||
).fetchone()[0]
|
||||
)
|
||||
if previous.get("reference") != reference:
|
||||
raise ValueError("observation idempotency conflict")
|
||||
return self.get(body["id"])
|
||||
if any(
|
||||
json.loads(r[0])["expires_at"] > now
|
||||
for r in db.execute("SELECT body FROM observations")
|
||||
):
|
||||
raise ValueError("observation already armed")
|
||||
if db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] >= 64:
|
||||
raise ValueError("observation evidence capacity reached")
|
||||
value = {"id": body["id"], "created_at": now, "expires_at": now + 180}
|
||||
if reference is not None:
|
||||
value["reference"] = reference
|
||||
db.execute("INSERT INTO observations VALUES(?,?)", (body["id"], json.dumps(value)))
|
||||
return self.get(body["id"])
|
||||
|
||||
def get(self, identifier):
|
||||
with self.store.db() as db:
|
||||
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("unknown observation")
|
||||
value = json.loads(row[0])
|
||||
value.pop("reference", None)
|
||||
value.pop("diagnostic_imei", None)
|
||||
value["captures"] = [
|
||||
json.loads(r[0])
|
||||
for r in db.execute(
|
||||
"SELECT metadata FROM observation_data WHERE lease=? ORDER BY sequence",
|
||||
(identifier,),
|
||||
)
|
||||
]
|
||||
return value
|
||||
|
||||
def close(self, identifier):
|
||||
"""Disarm without deleting private evidence or retrying a dispatch."""
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("unknown observation")
|
||||
value = json.loads(row[0])
|
||||
value["expires_at"] = min(value["expires_at"], time.time())
|
||||
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
|
||||
return self.get(identifier)
|
||||
|
||||
def reply(self, ticket, raw):
|
||||
"""Persist one dispatch before writing, including across service restarts."""
|
||||
request = http_body(raw)
|
||||
if request is None:
|
||||
return None
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT body FROM observations WHERE id=?", (ticket[0],)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
value = json.loads(row[0])
|
||||
reference = value.get("reference")
|
||||
if (
|
||||
not reference
|
||||
or value["expires_at"] <= time.time()
|
||||
or value.get("reply_dispatched_at")
|
||||
or request != bytes.fromhex(reference["request"])
|
||||
or not self.store.admitted(str(int.from_bytes(request[4:12], "little")))
|
||||
or not db.execute(
|
||||
"SELECT 1 FROM observation_data WHERE lease=? AND sequence=?", ticket
|
||||
).fetchone()
|
||||
):
|
||||
return None
|
||||
response = bytes.fromhex(reference["response"])
|
||||
value.update(
|
||||
reply_dispatched_at=time.time(),
|
||||
reply_monotonic=time.monotonic(),
|
||||
reply_sha256=hashlib.sha256(response).hexdigest(),
|
||||
reply_sequence=ticket[1],
|
||||
)
|
||||
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), ticket[0]))
|
||||
return response
|
||||
|
||||
def claim(self):
|
||||
with self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
for identifier, body in db.execute("SELECT id,body FROM observations"):
|
||||
if json.loads(body)["expires_at"] <= time.time():
|
||||
continue
|
||||
sequence = db.execute(
|
||||
"SELECT COUNT(*) FROM observation_data WHERE lease=?", (identifier,)
|
||||
).fetchone()[0]
|
||||
if sequence >= 4:
|
||||
return None
|
||||
metadata = {
|
||||
"sequence": sequence,
|
||||
"started_at": time.time(),
|
||||
"monotonic": time.monotonic(),
|
||||
"state": "receiving",
|
||||
}
|
||||
db.execute(
|
||||
"INSERT INTO observation_data VALUES(?,?,?,?)",
|
||||
(identifier, sequence, b"", json.dumps(metadata)),
|
||||
)
|
||||
return identifier, sequence
|
||||
return None
|
||||
|
||||
def finish(self, ticket, raw, events):
|
||||
if len(raw) > 16384:
|
||||
raise ValueError("observation limit")
|
||||
with self.store.db() as db:
|
||||
row = db.execute(
|
||||
"SELECT metadata FROM observation_data WHERE lease=? AND sequence=?", ticket
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError("unknown capture")
|
||||
value = json.loads(row[0])
|
||||
value.update(
|
||||
state="captured",
|
||||
completed_at=time.time(),
|
||||
bytes=len(raw),
|
||||
sha256=hashlib.sha256(raw).hexdigest(),
|
||||
events=events,
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE observation_data SET raw=?,metadata=? WHERE lease=? AND sequence=?",
|
||||
(raw, json.dumps(value), *ticket),
|
||||
)
|
||||
|
||||
|
||||
def http_body(raw):
|
||||
"""First complete, bounded B2 POST only; reject ambiguous HTTP framing."""
|
||||
header, separator, body = raw.partition(b"\r\n\r\n")
|
||||
if not separator or len(header) > 2048:
|
||||
return None
|
||||
lines = header.split(b"\r\n")
|
||||
if lines[0] != b"POST /c/index.php HTTP/1.1":
|
||||
return None
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
key, colon, value = line.partition(b":")
|
||||
key = key.lower()
|
||||
if not colon or key in headers:
|
||||
return None
|
||||
headers[key] = value.strip()
|
||||
size = headers.get(b"content-length", b"")
|
||||
if b"transfer-encoding" in headers or not size.isdigit():
|
||||
return None
|
||||
size = int(size)
|
||||
if not 1 <= size <= 16384 or len(body) < size:
|
||||
return None
|
||||
return bytes(body[:size])
|
||||
@@ -0,0 +1,492 @@
|
||||
"""Durable tracker-maintenance intents; bounded attempts belong to Commands.
|
||||
|
||||
An outage ends an attempt, not its owning intent. No downstream output action
|
||||
is admitted here. State changes reconcile the actual B2 image before retrying.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from . import actions, full_configuration, sim_selection
|
||||
|
||||
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
|
||||
PENDING = {"queued", "dispatched"}
|
||||
RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"}
|
||||
FACTS = {
|
||||
"transport",
|
||||
"stage",
|
||||
"dispatched_at",
|
||||
"received_at",
|
||||
"device_accepted_at",
|
||||
"device_code",
|
||||
"roundtrip_seconds",
|
||||
"reconnected_at",
|
||||
"reconnect_seconds",
|
||||
"verified_at",
|
||||
"configuration",
|
||||
"configuration_sha256",
|
||||
"configuration_received_at",
|
||||
"write_reply_sent_at",
|
||||
"active_sim",
|
||||
"telemetry_measured_at",
|
||||
"unchanged",
|
||||
"sim_guard_verified",
|
||||
}
|
||||
|
||||
|
||||
class Operations:
|
||||
def __init__(self, store, commands):
|
||||
self.store, self.commands = store, commands
|
||||
# Only local SQLite work under this lock; never sockets, sleeps or device I/O.
|
||||
self.lock = threading.RLock()
|
||||
with store.db() as db:
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS operations(
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,
|
||||
imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq);
|
||||
CREATE TABLE IF NOT EXISTS operation_attempts(
|
||||
operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL,
|
||||
body TEXT NOT NULL,PRIMARY KEY(operation,number));
|
||||
CREATE TABLE IF NOT EXISTS operation_modem(
|
||||
imei TEXT PRIMARY KEY,body TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL);
|
||||
""")
|
||||
|
||||
def save(self, value):
|
||||
with self.store.db() as db:
|
||||
encoded = json.dumps(value)
|
||||
db.execute(
|
||||
"UPDATE operations SET state=?,body=? WHERE id=? AND body<>?",
|
||||
(value["state"], encoded, value["id"], encoded),
|
||||
)
|
||||
|
||||
def submit(self, body):
|
||||
body = dict(body)
|
||||
if (
|
||||
not re.fullmatch(r"[a-f0-9]{32}", body.get("id", ""))
|
||||
or body.get("kind") not in KINDS
|
||||
or not self.store.admitted(body.get("imei"))
|
||||
):
|
||||
raise ValueError("unsupported operation")
|
||||
if body["kind"] in full_configuration.KINDS:
|
||||
if not re.fullmatch(r"[0-9]{6}", body.get("password", "")):
|
||||
raise ValueError("invalid password")
|
||||
full_configuration.prepare(body)
|
||||
else:
|
||||
actions.prepare(body)
|
||||
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
|
||||
with self.lock, self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
stopped = db.execute(
|
||||
"SELECT kind FROM operation_stops WHERE id=?", (body["id"],)
|
||||
).fetchone()
|
||||
if stopped:
|
||||
return {
|
||||
"id": body["id"],
|
||||
"kind": stopped[0],
|
||||
"state": "stopped",
|
||||
"durable": True,
|
||||
"runtime_phase": "stopped",
|
||||
"stop_requested": True,
|
||||
"attempt_count": 0,
|
||||
}
|
||||
old = db.execute(
|
||||
"SELECT digest,body FROM operations WHERE id=?", (body["id"],)
|
||||
).fetchone()
|
||||
if old:
|
||||
if old[0] != digest:
|
||||
raise ValueError("idempotency conflict")
|
||||
return self.public(json.loads(old[1]))
|
||||
count = db.execute(
|
||||
"SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')",
|
||||
(body["imei"],),
|
||||
).fetchone()[0]
|
||||
if count >= 32:
|
||||
raise ValueError("operation queue full")
|
||||
value = {
|
||||
"id": body["id"],
|
||||
"imei": body["imei"],
|
||||
"kind": body["kind"],
|
||||
"request": body,
|
||||
"created_at": time.time(),
|
||||
"state": "queued",
|
||||
"runtime_phase": "waiting-link",
|
||||
"attempt_count": 0,
|
||||
"next_attempt_at": 0,
|
||||
"phase": "execute",
|
||||
"result": {},
|
||||
}
|
||||
db.execute(
|
||||
"INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)",
|
||||
(body["id"], body["imei"], value["state"], digest, json.dumps(value)),
|
||||
)
|
||||
return self.public(value)
|
||||
|
||||
@staticmethod
|
||||
def public(value):
|
||||
result = {k: v for k, v in value.get("result", {}).items() if k in FACTS}
|
||||
result.update(
|
||||
{
|
||||
k: value[k]
|
||||
for k in (
|
||||
"id",
|
||||
"kind",
|
||||
"state",
|
||||
"created_at",
|
||||
"attempt_count",
|
||||
"runtime_phase",
|
||||
"next_attempt_at",
|
||||
"stop_requested",
|
||||
"reason",
|
||||
)
|
||||
if k in value
|
||||
}
|
||||
)
|
||||
result["durable"] = True
|
||||
if value.get("attempt"):
|
||||
result["attempt_id"] = value["attempt"]["id"]
|
||||
result["attempt_expires_at"] = value["attempt"]["not_after"]
|
||||
return result
|
||||
|
||||
def pending(self, imei):
|
||||
with self.store.db() as db:
|
||||
return (
|
||||
db.execute(
|
||||
"SELECT 1 FROM operations WHERE imei=? AND state IN "
|
||||
"('queued','dispatched') LIMIT 1",
|
||||
(imei,),
|
||||
).fetchone()
|
||||
is not None
|
||||
)
|
||||
|
||||
def fresh(self, imei):
|
||||
return any(
|
||||
0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30
|
||||
for s in tuple(self.commands.sessions.get(imei, ()))
|
||||
)
|
||||
|
||||
def wait_delay(self, imei):
|
||||
with self.store.db() as db:
|
||||
row = db.execute(
|
||||
"SELECT body FROM operations WHERE imei=? AND state IN "
|
||||
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
||||
(imei,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
value = json.loads(row[0])
|
||||
if value.get("attempt"):
|
||||
return 1
|
||||
return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None
|
||||
|
||||
def get(self, identifier):
|
||||
with self.store.db() as db:
|
||||
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
with self.store.db() as db:
|
||||
stopped = db.execute(
|
||||
"SELECT kind FROM operation_stops WHERE id=?", (identifier,)
|
||||
).fetchone()
|
||||
if stopped:
|
||||
return {
|
||||
"id": identifier,
|
||||
"kind": stopped[0],
|
||||
"state": "stopped",
|
||||
"durable": True,
|
||||
"runtime_phase": "stopped",
|
||||
"stop_requested": True,
|
||||
"attempt_count": 0,
|
||||
}
|
||||
raise ValueError("unknown operation")
|
||||
self.advance(json.loads(row[0])["imei"])
|
||||
with self.store.db() as db:
|
||||
value = json.loads(
|
||||
db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0]
|
||||
)
|
||||
result = self.public(value)
|
||||
attempt = value.get("attempt", value.get("result", {})).get("id")
|
||||
if attempt:
|
||||
result["transport"] = self.commands.transport.read(db, attempt)
|
||||
return result
|
||||
|
||||
def cancel(self, identifier, kind=None):
|
||||
if not re.fullmatch(r"[a-f0-9]{32}", identifier):
|
||||
raise ValueError("invalid operation identity")
|
||||
with self.lock, self.store.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
||||
if not row:
|
||||
if kind not in KINDS:
|
||||
raise ValueError("unknown operation")
|
||||
db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind))
|
||||
return {
|
||||
"id": identifier,
|
||||
"kind": kind,
|
||||
"state": "stopped",
|
||||
"durable": True,
|
||||
"runtime_phase": "stopped",
|
||||
"stop_requested": True,
|
||||
"attempt_count": 0,
|
||||
}
|
||||
value = json.loads(row[0])
|
||||
if value["state"] in PENDING:
|
||||
value["stop_requested"] = True
|
||||
if not value.get("attempt"):
|
||||
value.update(state="stopped", runtime_phase="stopped")
|
||||
db.execute(
|
||||
"UPDATE operations SET state=?,body=? WHERE id=?",
|
||||
(value["state"], json.dumps(value), identifier),
|
||||
)
|
||||
return self.get(identifier)
|
||||
|
||||
def history(self, identifier, before=2**63 - 1):
|
||||
with self.store.db() as db:
|
||||
rows = db.execute(
|
||||
"SELECT number,body FROM operation_attempts WHERE operation=? "
|
||||
"AND number<? ORDER BY number DESC LIMIT 21",
|
||||
(identifier, before),
|
||||
).fetchall()
|
||||
items = [json.loads(r[1]) for r in rows[:20]]
|
||||
for item in items:
|
||||
# Transport observations may be persisted just after the device
|
||||
# reply already completed this attempt. Read their current facts.
|
||||
item["transport"] = self.commands.transport.read(db, item["id"])
|
||||
return {
|
||||
"items": items,
|
||||
"next_before": rows[19][0] if len(rows) > 20 else None,
|
||||
}
|
||||
|
||||
def note_attempt(self, value, result):
|
||||
item = {k: result[k] for k in FACTS - {"configuration"} if k in result}
|
||||
item.update(
|
||||
id=value["attempt"]["id"],
|
||||
number=value["attempt_count"],
|
||||
phase=value["phase"],
|
||||
state=result["state"],
|
||||
)
|
||||
with self.store.db() as db:
|
||||
old = db.execute(
|
||||
"SELECT body FROM operation_attempts WHERE id=?", (item["id"],)
|
||||
).fetchone()
|
||||
if old:
|
||||
previous = json.loads(old[0])
|
||||
previous.pop("observed_at", None)
|
||||
if previous == item:
|
||||
return
|
||||
item["observed_at"] = time.time()
|
||||
db.execute(
|
||||
"INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) "
|
||||
"DO UPDATE SET body=excluded.body",
|
||||
(value["id"], value["attempt_count"], item["id"], json.dumps(item)),
|
||||
)
|
||||
|
||||
def observe(self, imei, raw):
|
||||
offset = 2
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||
payload = raw[offset + 7 : offset + 7 + size]
|
||||
if raw[offset] == 1 and 0 <= time.time() - measured <= 30:
|
||||
for index in range(0, len(payload) - 4, 5):
|
||||
if payload[index] != 99:
|
||||
continue
|
||||
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
|
||||
value = {
|
||||
"active_sim": 1 + ((ds2 >> 5) & 1),
|
||||
"gprs": (ds2 >> 2) & 7,
|
||||
"measured_at": measured,
|
||||
}
|
||||
with self.store.db() as db:
|
||||
db.execute(
|
||||
"INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) "
|
||||
"DO UPDATE SET body=excluded.body WHERE "
|
||||
"json_extract(excluded.body, '$.measured_at') >= "
|
||||
"json_extract(operation_modem.body, '$.measured_at')",
|
||||
(imei, json.dumps(value)),
|
||||
)
|
||||
offset += size + 8
|
||||
|
||||
def selected(self, value):
|
||||
if (
|
||||
self.commands.sim_guard.check(
|
||||
value["imei"], value["request"].get("sim_guard"), after=value["created_at"]
|
||||
)
|
||||
!= "matched"
|
||||
):
|
||||
return None
|
||||
with self.store.db() as db:
|
||||
row = db.execute(
|
||||
"SELECT body FROM operation_modem WHERE imei=?", (value["imei"],)
|
||||
).fetchone()
|
||||
data = json.loads(row[0]) if row else {}
|
||||
return (
|
||||
data
|
||||
if sim_selection.matches(value["request"], data.get("active_sim"))
|
||||
and data.get("gprs") == 4
|
||||
and data.get("measured_at", 0) > value["created_at"]
|
||||
and 0 <= time.time() - data["measured_at"] <= 30
|
||||
else None
|
||||
)
|
||||
|
||||
def reconcile(self, value, result):
|
||||
request = value["request"]
|
||||
digest = result.get("configuration_sha256")
|
||||
target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest()
|
||||
if digest == target:
|
||||
if value["kind"] == "configure-all":
|
||||
value.update(state="verified", runtime_phase="complete", result=result)
|
||||
elif selected := self.selected(value):
|
||||
value.update(
|
||||
state="sim_selected",
|
||||
runtime_phase="complete",
|
||||
result={
|
||||
**result,
|
||||
"active_sim": selected["active_sim"],
|
||||
"telemetry_measured_at": selected["measured_at"],
|
||||
"sim_guard_verified": bool(request.get("sim_guard")),
|
||||
},
|
||||
)
|
||||
else:
|
||||
value.update(phase="execute", retry_predecessor=target)
|
||||
elif digest == request["expected_sha256"]:
|
||||
value.update(phase="execute", retry_predecessor=digest)
|
||||
else:
|
||||
value.update(
|
||||
state="rejected",
|
||||
reason="configuration_conflict",
|
||||
runtime_phase="complete",
|
||||
result=result,
|
||||
)
|
||||
|
||||
def advance(self, imei):
|
||||
with self.lock:
|
||||
with self.store.db() as db:
|
||||
row = db.execute(
|
||||
"SELECT body FROM operations WHERE imei=? AND state IN "
|
||||
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
||||
(imei,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return
|
||||
value = json.loads(row[0])
|
||||
if not self.store.admitted(imei):
|
||||
value.update(state="rejected", reason="device_revoked", runtime_phase="complete")
|
||||
self.save(value)
|
||||
return
|
||||
if value.get("attempt"):
|
||||
# Idempotent submission covers a crash before/after attempt admission.
|
||||
# Read first: the accepted attempt may have completed while Core was away.
|
||||
try:
|
||||
result = self.commands.get(value["attempt"]["id"])
|
||||
except ValueError:
|
||||
if value.get("stop_requested"):
|
||||
value.pop("attempt", None)
|
||||
value.update(state="stopped", runtime_phase="stopped")
|
||||
self.save(value)
|
||||
return
|
||||
try:
|
||||
result = self.commands.submit(value["attempt"])
|
||||
except ValueError:
|
||||
return # A legacy operation/session admission still owns the channel.
|
||||
value["result"] = result
|
||||
self.note_attempt(value, result)
|
||||
if result["state"] in PENDING:
|
||||
value.update(
|
||||
state=result["state"],
|
||||
runtime_phase="checking-result"
|
||||
if value["phase"] == "inspect"
|
||||
else "executing",
|
||||
)
|
||||
self.save(value)
|
||||
return
|
||||
if value["phase"] == "inspect" and result["state"] == "observed":
|
||||
self.reconcile(value, result)
|
||||
elif result["state"] in {
|
||||
"device_confirmed",
|
||||
"observed",
|
||||
"verified",
|
||||
"sim_selected",
|
||||
"reconnected",
|
||||
}:
|
||||
value.update(state=result["state"], runtime_phase="complete")
|
||||
elif (
|
||||
value["kind"] == "restart"
|
||||
and result.get("device_code") == 0
|
||||
and result.get("device_accepted_at")
|
||||
):
|
||||
value.update(state="accepted", runtime_phase="complete")
|
||||
elif (
|
||||
result["state"] in RETRY
|
||||
or result.get("device_code") == 7
|
||||
or result.get("reason") == "configuration_predecessor_mismatch"
|
||||
):
|
||||
if value["kind"] in {"configure-all", "select-sim"}:
|
||||
value["phase"] = "inspect"
|
||||
else:
|
||||
value.update(state=result["state"], runtime_phase="complete")
|
||||
if result.get("reason") == "sim_card_changed":
|
||||
value["reason"] = "sim_card_changed"
|
||||
value.pop("attempt", None)
|
||||
if value["state"] in PENDING:
|
||||
value.update(
|
||||
state="stopped" if value.get("stop_requested") else "queued",
|
||||
runtime_phase="stopped" if value.get("stop_requested") else "retry-wait",
|
||||
next_attempt_at=time.time()
|
||||
+ min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)),
|
||||
)
|
||||
self.save(value)
|
||||
return
|
||||
if value.get("stop_requested"):
|
||||
value.update(state="stopped", runtime_phase="stopped")
|
||||
self.save(value)
|
||||
return
|
||||
if value["next_attempt_at"] > time.time():
|
||||
return
|
||||
if not self.fresh(imei):
|
||||
if value["runtime_phase"] != "waiting-link":
|
||||
value.update(runtime_phase="waiting-link")
|
||||
self.save(value)
|
||||
return
|
||||
if value["phase"] == "execute" and value["request"].get("sim_guard"):
|
||||
guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"])
|
||||
if guard != "matched":
|
||||
if guard == "changed":
|
||||
value.update(
|
||||
state="rejected", runtime_phase="complete", reason="sim_card_changed"
|
||||
)
|
||||
else:
|
||||
value.update(runtime_phase="waiting-identity")
|
||||
self.save(value)
|
||||
return
|
||||
attempt = {**value["request"], "id": uuid.uuid4().hex}
|
||||
if value["phase"] == "inspect":
|
||||
attempt = {
|
||||
k: v
|
||||
for k, v in attempt.items()
|
||||
if k in {"id", "imei", "password", "model", "firmware"}
|
||||
}
|
||||
attempt["kind"] = "read-configuration"
|
||||
elif value.get("retry_predecessor"):
|
||||
attempt["expected_sha256"] = value["retry_predecessor"]
|
||||
lifetime = (
|
||||
360
|
||||
if attempt["kind"] == "select-sim"
|
||||
else 30
|
||||
if attempt["kind"] == "request-position"
|
||||
else 180
|
||||
)
|
||||
attempt["not_after"] = time.time() + lifetime
|
||||
value.update(
|
||||
attempt=attempt,
|
||||
attempt_count=value["attempt_count"] + 1,
|
||||
result={},
|
||||
runtime_phase="checking-result" if value["phase"] == "inspect" else "executing",
|
||||
)
|
||||
# The plan is durable before the attempt's separate transaction.
|
||||
self.save(value)
|
||||
self.advance(imei)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Observe return after a restart request without claiming CPU/power-cycle proof."""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def observe(value, raw, session, started):
|
||||
if (
|
||||
value.get("kind") != "restart"
|
||||
or value["state"] != "dispatched"
|
||||
or value["expires_at"] < time.time()
|
||||
or session in value["restart_sessions"]
|
||||
or started <= value["monotonic"]
|
||||
):
|
||||
return False
|
||||
# Only type-1 telemetry measured after dispatch establishes fresh return.
|
||||
# A new header, old archive, text reply or token ACK cannot complete this.
|
||||
offset = 2
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
|
||||
value.update(
|
||||
state="reconnected",
|
||||
reconnected_at=time.time(),
|
||||
reconnect_seconds=time.monotonic() - value["monotonic"],
|
||||
telemetry_measured_at=measured,
|
||||
)
|
||||
return True
|
||||
offset += size + 8
|
||||
return False
|
||||
@@ -0,0 +1,402 @@
|
||||
"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
import ssl
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import suppress
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from . import arnavi
|
||||
from .commands import COMMAND_SESSION_MAX_IDLE, Commands
|
||||
from .delivery import Delivery
|
||||
from .observation import Observation, http_body
|
||||
from .operations import Operations
|
||||
|
||||
|
||||
class Service:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
self.connections = 0
|
||||
self.commands = Commands(store)
|
||||
self.operations = Operations(store, self.commands)
|
||||
self.observation = Observation(store)
|
||||
self.wake = {}
|
||||
|
||||
async def tracker(self, reader, writer):
|
||||
self.connections += 1
|
||||
session = uuid.uuid4().hex
|
||||
sender = None
|
||||
delivery = None
|
||||
imei = None
|
||||
try:
|
||||
if self.connections > 256:
|
||||
return
|
||||
async with asyncio.timeout(10):
|
||||
header = await reader.readexactly(10)
|
||||
if header[:2] != b"\xff\x23":
|
||||
if (
|
||||
not await self.observe_configuration(reader, header, writer)
|
||||
and header == b"POST /c/in"
|
||||
):
|
||||
delivery = Delivery(writer)
|
||||
await self.configuration_http(reader, writer, header, delivery)
|
||||
return
|
||||
imei = arnavi.identity(header)
|
||||
if not await asyncio.to_thread(self.store.admitted, imei):
|
||||
return
|
||||
delivery = Delivery(writer)
|
||||
self.commands.sessions.setdefault(imei, set()).add(session)
|
||||
self.commands.session_started[imei, session] = time.monotonic()
|
||||
self.commands.session_activity[imei, session] = time.monotonic()
|
||||
self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0]
|
||||
self.commands.session_ready[imei, session] = False
|
||||
delivery.write(arnavi.header_ack(int(time.time())))
|
||||
await writer.drain()
|
||||
sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery))
|
||||
buffer = b""
|
||||
while True:
|
||||
async with asyncio.timeout(180):
|
||||
chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer)))
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
while buffer:
|
||||
parsed = arnavi.parse_package(buffer)
|
||||
if parsed is None:
|
||||
break
|
||||
length, packets = parsed
|
||||
self.commands.session_activity[imei, session] = time.monotonic()
|
||||
await asyncio.to_thread(
|
||||
self.accept_package, imei, buffer[:length], packets, session
|
||||
)
|
||||
self.notify(imei)
|
||||
delivery.write(arnavi.package_ack(buffer[1]))
|
||||
await writer.drain()
|
||||
buffer = buffer[length:]
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
OSError,
|
||||
sqlite3.Error,
|
||||
TimeoutError,
|
||||
asyncio.IncompleteReadError,
|
||||
asyncio.LimitOverrunError,
|
||||
):
|
||||
pass # Deliberately no raw identity/data/credentials in logs.
|
||||
finally:
|
||||
if imei:
|
||||
self.commands.sessions.get(imei, set()).discard(session)
|
||||
self.commands.session_started.pop((imei, session), None)
|
||||
self.commands.session_activity.pop((imei, session), None)
|
||||
self.commands.session_peers.pop((imei, session), None)
|
||||
self.commands.session_ready.pop((imei, session), None)
|
||||
if not self.commands.sessions.get(imei):
|
||||
self.commands.sessions.pop(imei, None)
|
||||
if sender:
|
||||
sender.cancel()
|
||||
await asyncio.gather(sender, return_exceptions=True)
|
||||
self.connections -= 1
|
||||
if delivery:
|
||||
delivery.abort()
|
||||
else:
|
||||
writer.close()
|
||||
|
||||
def accept_package(self, imei, raw, packets, session):
|
||||
# Core may fetch/ack packages concurrently. Publish the packet and its
|
||||
# command evidence together before either Core or B2 can consume it.
|
||||
with self.store.packet_transaction():
|
||||
self.store.append(imei, raw, packets)
|
||||
self.commands.receive(imei, raw, session)
|
||||
self.operations.observe(imei, raw)
|
||||
|
||||
async def observe_configuration(self, reader, header, writer=None):
|
||||
ticket = await asyncio.to_thread(self.observation.claim)
|
||||
if ticket is None:
|
||||
return False
|
||||
raw = bytearray(header)
|
||||
events = [
|
||||
{"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()}
|
||||
]
|
||||
try:
|
||||
async with asyncio.timeout(8):
|
||||
while len(raw) < 16384:
|
||||
chunk = await reader.read(min(4096, 16384 - len(raw)))
|
||||
if not chunk:
|
||||
break
|
||||
events.append(
|
||||
{
|
||||
"offset": len(raw),
|
||||
"bytes": len(chunk),
|
||||
"at": time.time(),
|
||||
"monotonic": time.monotonic(),
|
||||
}
|
||||
)
|
||||
raw.extend(chunk)
|
||||
if writer is not None:
|
||||
reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw))
|
||||
if reply is not None:
|
||||
writer.write(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||
+ b"Connection: keep-alive\r\n\r\n"
|
||||
+ reply
|
||||
)
|
||||
await writer.drain()
|
||||
except (TimeoutError, OSError):
|
||||
pass
|
||||
finally:
|
||||
await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events)
|
||||
return True
|
||||
|
||||
async def configuration_http(self, reader, writer, initial, delivery):
|
||||
if initial != b"POST /c/in":
|
||||
return
|
||||
peer = writer.get_extra_info("peername")[0]
|
||||
for _ in range(8):
|
||||
async with asyncio.timeout(12):
|
||||
header = initial + await reader.readuntil(b"\r\n\r\n")
|
||||
initial = b""
|
||||
if len(header) > 2048:
|
||||
return
|
||||
lengths = [
|
||||
line.split(b":", 1)[1].strip()
|
||||
for line in header.split(b"\r\n")
|
||||
if line.lower().startswith(b"content-length:")
|
||||
]
|
||||
if len(lengths) != 1 or not lengths[0].isdigit():
|
||||
return
|
||||
size = int(lengths[0])
|
||||
if not 20 <= size <= 16384:
|
||||
return
|
||||
body = http_body(header + await reader.readexactly(size))
|
||||
if body is None:
|
||||
return
|
||||
response = await asyncio.to_thread(
|
||||
self.commands.web_receive, body, peer, with_deadline=True
|
||||
)
|
||||
self.notify(str(int.from_bytes(body[4:12], "little")))
|
||||
if response is None:
|
||||
return
|
||||
reply, deadline = response
|
||||
delivery.write(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
|
||||
+ f"Content-Length: {len(reply)}\r\n".encode()
|
||||
+ b"Connection: keep-alive\r\n\r\n"
|
||||
+ reply,
|
||||
deadline,
|
||||
)
|
||||
await writer.drain()
|
||||
|
||||
async def send_commands(self, imei, writer, session, delivery):
|
||||
event = asyncio.Event()
|
||||
observations = []
|
||||
|
||||
def observe(ticket, phase, at, elapsed, reason):
|
||||
# The socket timer never opens SQLite or waits for filesystem I/O.
|
||||
observations.append((ticket, phase, at, elapsed, reason))
|
||||
event.set()
|
||||
|
||||
async def persist():
|
||||
if observations:
|
||||
batch = observations[:]
|
||||
observations.clear()
|
||||
commit = asyncio.create_task(
|
||||
asyncio.to_thread(self.commands.transport.record, batch)
|
||||
)
|
||||
try:
|
||||
await asyncio.shield(commit)
|
||||
except asyncio.CancelledError:
|
||||
# EOF cancels this sender. Finish the extracted batch before
|
||||
# the finally block records closure of its remaining bytes.
|
||||
await commit
|
||||
raise
|
||||
|
||||
self.wake.setdefault(imei, set()).add(event)
|
||||
try:
|
||||
while not writer.is_closing():
|
||||
event.clear()
|
||||
await persist()
|
||||
last_input = self.commands.session_activity.get((imei, session))
|
||||
self.commands.session_ready[imei, session] = (
|
||||
delivery.ready()
|
||||
and last_input is not None
|
||||
and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
|
||||
)
|
||||
await asyncio.to_thread(self.operations.advance, imei)
|
||||
dispatch = await asyncio.to_thread(
|
||||
self.commands.take_delivery, imei, session, with_receipt=True
|
||||
)
|
||||
if dispatch:
|
||||
data, deadline, ticket = dispatch
|
||||
delivery.write(
|
||||
data,
|
||||
deadline,
|
||||
lambda phase, at, elapsed, reason, ticket=ticket: observe(
|
||||
ticket, phase, at, elapsed, reason
|
||||
),
|
||||
)
|
||||
await writer.drain()
|
||||
await persist()
|
||||
delay = await asyncio.to_thread(self.commands.wait_delay, imei)
|
||||
operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei)
|
||||
delay = (
|
||||
min(d for d in (delay, operation_delay) if d is not None)
|
||||
if (delay is not None or operation_delay is not None)
|
||||
else None
|
||||
)
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(event.wait(), delay)
|
||||
finally:
|
||||
self.wake.get(imei, set()).discard(event)
|
||||
if not self.wake.get(imei):
|
||||
self.wake.pop(imei, None)
|
||||
delivery.abort()
|
||||
await persist()
|
||||
|
||||
def notify(self, imei):
|
||||
for event in self.wake.get(imei, ()):
|
||||
event.set()
|
||||
|
||||
async def api(self, reader, writer):
|
||||
status, value = 400, {"error": "invalid_request"}
|
||||
try:
|
||||
async with asyncio.timeout(15):
|
||||
header = await reader.readuntil(b"\r\n\r\n")
|
||||
if len(header) > 8192:
|
||||
raise ValueError
|
||||
lines = header.decode("ascii").split("\r\n")
|
||||
method, target, _ = lines[0].split(" ")
|
||||
headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line)
|
||||
size = int(headers.get("content-length", "0"))
|
||||
if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers:
|
||||
raise ValueError
|
||||
payload = await reader.readexactly(size) if size else b"{}"
|
||||
body = json.loads(payload)
|
||||
route = urlsplit(target)
|
||||
token = headers.get("authorization", "").removeprefix("bearer ")
|
||||
# Header values must retain case for bearer credentials.
|
||||
for line in lines[1:]:
|
||||
if line.lower().startswith("authorization: bearer "):
|
||||
token = line[len("authorization: bearer ") :]
|
||||
if method == "GET" and route.path == "/health":
|
||||
value = {"ok": True, "service": "ndc-mission-vps-host"}
|
||||
elif method == "POST" and route.path == "/v1/pair":
|
||||
value = await asyncio.to_thread(self.store.pair, body)
|
||||
else:
|
||||
if not await asyncio.to_thread(self.store.authorize, token):
|
||||
raise PermissionError
|
||||
if method == "GET" and route.path == "/v1/status":
|
||||
value = await asyncio.to_thread(self.store.status)
|
||||
elif method == "PUT" and route.path == "/v1/devices":
|
||||
await asyncio.to_thread(self.store.set_devices, body["items"])
|
||||
value = {"ok": True}
|
||||
elif method == "GET" and route.path == "/v1/packets":
|
||||
after = int(parse_qs(route.query).get("after", ["0"])[0])
|
||||
value = await asyncio.to_thread(self.store.fetch, max(0, after))
|
||||
elif method == "POST" and route.path == "/v1/commands":
|
||||
if await asyncio.to_thread(self.operations.pending, body["imei"]):
|
||||
raise ValueError("durable operation owns device queue")
|
||||
value = await asyncio.to_thread(self.commands.submit, body)
|
||||
self.notify(body["imei"])
|
||||
elif method == "POST" and route.path == "/v1/operations":
|
||||
value = await asyncio.to_thread(self.operations.submit, body)
|
||||
self.notify(body["imei"])
|
||||
elif (
|
||||
method == "POST"
|
||||
and route.path.startswith("/v1/operations/")
|
||||
and route.path.endswith("/cancel")
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.cancel, route.path.split("/")[-2], body.get("kind")
|
||||
)
|
||||
elif (
|
||||
method == "GET"
|
||||
and route.path.startswith("/v1/operations/")
|
||||
and route.path.endswith("/attempts")
|
||||
):
|
||||
before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0])
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.history, route.path.split("/")[-2], before
|
||||
)
|
||||
elif method == "GET" and route.path.startswith("/v1/operations/"):
|
||||
value = await asyncio.to_thread(
|
||||
self.operations.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "POST" and route.path == "/v1/configuration-observations":
|
||||
value = await asyncio.to_thread(self.observation.arm, body)
|
||||
elif (
|
||||
method == "POST"
|
||||
and route.path.startswith("/v1/configuration-observations/")
|
||||
and route.path.endswith("/close")
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.observation.close, route.path.split("/")[-2]
|
||||
)
|
||||
elif method == "GET" and route.path.startswith(
|
||||
"/v1/configuration-observations/"
|
||||
):
|
||||
value = await asyncio.to_thread(
|
||||
self.observation.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "GET" and route.path.startswith("/v1/commands/"):
|
||||
value = await asyncio.to_thread(
|
||||
self.commands.get, route.path.rsplit("/", 1)[1]
|
||||
)
|
||||
elif method == "POST" and route.path == "/v1/ack":
|
||||
if type(body["through"]) is not int or body["through"] < 0:
|
||||
raise ValueError
|
||||
await asyncio.to_thread(self.store.acknowledge, body["through"])
|
||||
value = {"ok": True}
|
||||
else:
|
||||
raise ValueError
|
||||
status = 200
|
||||
except PermissionError:
|
||||
status, value = 403, {"error": "not_authorized"}
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
UnicodeError,
|
||||
asyncio.IncompleteReadError,
|
||||
asyncio.LimitOverrunError,
|
||||
TimeoutError,
|
||||
):
|
||||
pass
|
||||
except (OSError, sqlite3.Error):
|
||||
status, value = 503, {"error": "storage_unavailable"}
|
||||
try:
|
||||
payload = json.dumps(value).encode()
|
||||
writer.write(
|
||||
(
|
||||
f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: {len(payload)}\r\nConnection: close\r\n"
|
||||
"Cache-Control: no-store\r\n\r\n"
|
||||
).encode()
|
||||
+ payload
|
||||
)
|
||||
await writer.drain()
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
async def run(self):
|
||||
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
tls.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key")
|
||||
api = await asyncio.start_server(
|
||||
self.api,
|
||||
"0.0.0.0",
|
||||
self.store.config["api_port"],
|
||||
ssl=tls,
|
||||
ssl_handshake_timeout=8,
|
||||
limit=8192,
|
||||
)
|
||||
tracker = await asyncio.start_server(
|
||||
self.tracker, "0.0.0.0", self.store.config["tracker"]["port"]
|
||||
)
|
||||
async with api, tracker:
|
||||
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Durable firmware SID bindings, checked at the last configuration write boundary."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from .sim_network import binding, decode_pairs, merge
|
||||
|
||||
|
||||
def prepare(value):
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != {"slot", "sid"}
|
||||
or type(value["slot"]) is not int
|
||||
or value["slot"] not in (1, 2)
|
||||
or not isinstance(value["sid"], str)
|
||||
or not re.fullmatch(r"89[0-9]{18}", value["sid"])
|
||||
):
|
||||
raise ValueError("invalid SIM identity guard")
|
||||
return dict(value)
|
||||
|
||||
|
||||
class SimGuard:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
with store.db() as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS sim_bindings(imei TEXT PRIMARY KEY,body TEXT NOT NULL)"
|
||||
)
|
||||
|
||||
def observe(self, imei, raw):
|
||||
# Called only for validated INTERNAL frames in the packet commit transaction.
|
||||
with self.store.db(write=True) as db:
|
||||
old = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
|
||||
value = json.loads(old[0]) if old else None
|
||||
offset, now = 2, time.time()
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||
payload = raw[offset + 7 : offset + 7 + size]
|
||||
if raw[offset] == 1:
|
||||
tags = {}
|
||||
for i in range(0, len(payload) - 4, 5):
|
||||
tags.setdefault(payload[i], set()).add(payload[i + 1 : i + 5])
|
||||
status = {}
|
||||
if len(tags.get(99, ())) == 1:
|
||||
ds = int.from_bytes(next(iter(tags[99])), "little")
|
||||
status = {"sim_states": {"1": (ds >> 6) & 7, "2": (ds >> 9) & 7}}
|
||||
value = merge(
|
||||
value,
|
||||
{
|
||||
"measured_at": measured,
|
||||
"cellular": {"status": status},
|
||||
"sim_identifiers": decode_pairs(tags),
|
||||
},
|
||||
host_id="local",
|
||||
sequence=0,
|
||||
received=now,
|
||||
tracker=imei,
|
||||
)
|
||||
offset += size + 8
|
||||
if value:
|
||||
db.execute(
|
||||
"INSERT OR REPLACE INTO sim_bindings VALUES(?,?)", (imei, json.dumps(value))
|
||||
)
|
||||
|
||||
def check(self, imei, guard, *, after=None, db=None):
|
||||
if guard is None:
|
||||
return "matched"
|
||||
if db is None:
|
||||
with self.store.db() as connection:
|
||||
return self.check(imei, guard, after=after, db=connection)
|
||||
row = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
|
||||
value = json.loads(row[0]) if row else None
|
||||
sid = binding(value, str(guard["slot"]), now=time.time())
|
||||
if sid is None:
|
||||
return "waiting"
|
||||
if sid != guard["sid"]:
|
||||
return "changed"
|
||||
observed = value["slots"][str(guard["slot"])]["observation"]
|
||||
if after is not None and observed["measured_at"] <= after:
|
||||
return "waiting"
|
||||
return "matched"
|
||||
@@ -0,0 +1,55 @@
|
||||
"""SIM permissions: verified flags, one restart, fresh modem evidence."""
|
||||
|
||||
import time
|
||||
|
||||
from . import actions
|
||||
|
||||
|
||||
def matches(value, slot):
|
||||
return (
|
||||
type(slot) is int
|
||||
and slot in (1, 2)
|
||||
and (value.get("sim_policy") == "both" or slot == value.get("sim_slot"))
|
||||
)
|
||||
|
||||
|
||||
def queue_restart(value):
|
||||
value.update(actions.prepare({"kind": "restart", "model": 231, "firmware": "0.01"}))
|
||||
value.update(stage="restart", state="queued", not_before=time.time())
|
||||
value.pop("session", None)
|
||||
|
||||
|
||||
def observe(value, raw, session, started):
|
||||
if (
|
||||
value.get("kind") != "select-sim"
|
||||
or value.get("stage") != "restart"
|
||||
or value["state"] != "dispatched"
|
||||
or value["expires_at"] <= time.time()
|
||||
or session in value["restart_sessions"]
|
||||
or started <= value["monotonic"]
|
||||
):
|
||||
return False
|
||||
# Validated INTERNAL packages only. ACKs, archives, old sockets, old and
|
||||
# future measurements, and GPRS on the wrong SIM cannot confirm selection.
|
||||
offset = 2
|
||||
while offset < len(raw) - 1:
|
||||
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
||||
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
||||
payload = raw[offset + 7 : offset + 7 + size]
|
||||
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
|
||||
for index in range(0, len(payload) - 4, 5):
|
||||
if payload[index] != 99:
|
||||
continue
|
||||
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
|
||||
slot = 1 + ((ds2 >> 5) & 1)
|
||||
if matches(value, slot) and (ds2 >> 2) & 7 == 4:
|
||||
value.update(
|
||||
state="sim_selected",
|
||||
active_sim=slot,
|
||||
verified_at=time.time(),
|
||||
telemetry_measured_at=measured,
|
||||
reconnect_seconds=time.monotonic() - value["monotonic"],
|
||||
)
|
||||
return True
|
||||
offset += size + 8
|
||||
return False
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Durable receiver journal. Acknowledgements follow SQLite FULL commits."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def private_write(path, data):
|
||||
temporary = path.with_name(path.name + ".new")
|
||||
with open(temporary, "wb") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
fd = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, root):
|
||||
self.root = Path(root)
|
||||
self.config = json.loads((self.root / "host.json").read_text())
|
||||
self.path = self.root / "journal.sqlite3"
|
||||
self._packet = threading.local()
|
||||
with self.db() as db:
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS devices(imei TEXT PRIMARY KEY, instance TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS device_ids(
|
||||
imei TEXT PRIMARY KEY, number INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS packages(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
imei TEXT NOT NULL, instance TEXT NOT NULL, digest TEXT UNIQUE NOT NULL,
|
||||
received REAL NOT NULL, raw BLOB NOT NULL, packets TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS receipts(digest TEXT PRIMARY KEY, at REAL NOT NULL);
|
||||
""")
|
||||
self.path.chmod(0o600)
|
||||
|
||||
@contextmanager
|
||||
def db(self, *, write=False):
|
||||
# Packet consumers run together on one worker thread. No partial
|
||||
# receipt or modem state may become visible to Core or the sender.
|
||||
current = getattr(self._packet, "connection", None)
|
||||
if current is not None:
|
||||
yield current
|
||||
return
|
||||
connection = sqlite3.connect(self.path, timeout=10)
|
||||
try:
|
||||
connection.execute("PRAGMA synchronous=FULL")
|
||||
with connection:
|
||||
if write:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
yield connection
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@contextmanager
|
||||
def packet_transaction(self):
|
||||
"""Synchronous packet ingestion only: no sockets, awaits or API work."""
|
||||
if getattr(self._packet, "connection", None) is not None:
|
||||
raise RuntimeError("nested packet transaction")
|
||||
with self.db(write=True) as connection:
|
||||
self._packet.connection = connection
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
del self._packet.connection
|
||||
|
||||
def invitation(self):
|
||||
secret = secrets.token_urlsafe(32)
|
||||
expires = int(time.time()) + 86400
|
||||
with self.db() as db:
|
||||
if db.execute("SELECT 1 FROM state WHERE key='owner'").fetchone():
|
||||
raise ValueError("host already paired; restore its Core identity instead")
|
||||
db.execute(
|
||||
"INSERT OR REPLACE INTO state VALUES('invitation',?)",
|
||||
(
|
||||
json.dumps(
|
||||
{"hash": hashlib.sha256(secret.encode()).hexdigest(), "expires_at": expires}
|
||||
),
|
||||
),
|
||||
)
|
||||
code = {
|
||||
"schema": "missioncore.vps-pairing/v1",
|
||||
"host_id": self.config["host_id"],
|
||||
"endpoint": self.config["endpoint"],
|
||||
"fingerprint": self.config["fingerprint"],
|
||||
"secret": secret,
|
||||
"expires_at": expires,
|
||||
}
|
||||
encoded = "MCV1." + base64.urlsafe_b64encode(json.dumps(code).encode()).decode().rstrip("=")
|
||||
private_write(self.root / "connect.key", (encoded + "\n").encode())
|
||||
|
||||
def pair(self, body):
|
||||
core, token, secret = body["core_id"], body["token"], body["secret"]
|
||||
if not all(isinstance(v, str) and 32 <= len(v) <= 100 for v in (core, token, secret)):
|
||||
raise ValueError("invalid pairing")
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
with self.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
current = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
|
||||
if current:
|
||||
owner = json.loads(current[0])
|
||||
if owner["core_id"] != core or not hmac.compare_digest(owner["token"], digest):
|
||||
raise PermissionError("already paired")
|
||||
else:
|
||||
row = db.execute("SELECT value FROM state WHERE key='invitation'").fetchone()
|
||||
invite = json.loads(row[0]) if row else {}
|
||||
if invite.get("expires_at", 0) <= time.time() or not hmac.compare_digest(
|
||||
invite.get("hash", ""), hashlib.sha256(secret.encode()).hexdigest()
|
||||
):
|
||||
raise PermissionError("invalid invitation")
|
||||
db.execute(
|
||||
"INSERT INTO state VALUES('owner',?)",
|
||||
(json.dumps({"core_id": core, "token": digest}),),
|
||||
)
|
||||
db.execute("DELETE FROM state WHERE key='invitation'")
|
||||
private_write(
|
||||
self.root / "connect.key", b"PAIRED: key consumed; use the connected Mission Core.\n"
|
||||
)
|
||||
return self.status()
|
||||
|
||||
def authorize(self, token):
|
||||
with self.db() as db:
|
||||
row = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
|
||||
return bool(
|
||||
row
|
||||
and hmac.compare_digest(
|
||||
json.loads(row[0])["token"], hashlib.sha256(token.encode()).hexdigest()
|
||||
)
|
||||
)
|
||||
|
||||
def status(self):
|
||||
from . import VERSION
|
||||
|
||||
with self.db() as db:
|
||||
count, latest = db.execute("SELECT COUNT(*),MAX(received) FROM packages").fetchone()
|
||||
devices = db.execute("SELECT COUNT(*) FROM devices").fetchone()[0]
|
||||
return {
|
||||
"schema": "missioncore.vps-host/v1",
|
||||
"host_id": self.config["host_id"],
|
||||
"version": VERSION,
|
||||
"tracker": self.config["tracker"],
|
||||
"pending_packages": count,
|
||||
"last_packet_at": latest,
|
||||
"devices": devices,
|
||||
"capabilities": [
|
||||
"arnavi-b2-internal",
|
||||
"arnavi-b2-durable-operations-v1",
|
||||
"arnavi-b2-sim-guard-v1",
|
||||
],
|
||||
}
|
||||
|
||||
def set_devices(self, items):
|
||||
if not isinstance(items, list) or len(items) > 10000:
|
||||
raise ValueError("invalid devices")
|
||||
rows, identities = [], []
|
||||
for item in items:
|
||||
imei, instance = item["imei"], item["instance_id"]
|
||||
if (
|
||||
not isinstance(imei, str)
|
||||
or not imei.isascii()
|
||||
or not imei.isdigit()
|
||||
or len(imei) != 15
|
||||
):
|
||||
raise ValueError("invalid identity")
|
||||
if not isinstance(instance, str) or len(instance) != 32:
|
||||
raise ValueError("invalid instance")
|
||||
rows.append((imei, instance))
|
||||
if "device_id" in item:
|
||||
number = item["device_id"]
|
||||
if type(number) is not int or not 1 <= number <= 0xFFFFFFFF:
|
||||
raise ValueError("invalid numeric device identity")
|
||||
identities.append((imei, number))
|
||||
if len({r[0] for r in rows}) != len(rows):
|
||||
raise ValueError("duplicate identity")
|
||||
with self.db() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
for imei, number in identities:
|
||||
previous = db.execute(
|
||||
"SELECT number FROM device_ids WHERE imei=?", (imei,)
|
||||
).fetchone()
|
||||
if previous and previous[0] != number:
|
||||
raise ValueError("numeric device identity conflict")
|
||||
db.execute("INSERT OR IGNORE INTO device_ids VALUES(?,?)", (imei, number))
|
||||
db.execute("DELETE FROM devices")
|
||||
db.executemany("INSERT INTO devices VALUES(?,?)", rows)
|
||||
|
||||
def numeric_id(self, imei):
|
||||
with self.db() as db:
|
||||
row = db.execute(
|
||||
"SELECT number FROM device_ids JOIN devices USING(imei) WHERE imei=?", (imei,)
|
||||
).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def admitted(self, imei):
|
||||
with self.db() as db:
|
||||
row = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def append(self, imei, raw, packets):
|
||||
# Reserve disk for system services. Refuse ACK when durable storage cannot accept data.
|
||||
if os.statvfs(self.root).f_bavail * os.statvfs(self.root).f_frsize < 256 * 1024**2:
|
||||
raise OSError("journal storage reserve")
|
||||
digest = hashlib.sha256(imei.encode() + raw).hexdigest()
|
||||
with self.db(write=True) as db:
|
||||
device = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
|
||||
if not device:
|
||||
raise PermissionError("device not admitted")
|
||||
if db.execute("SELECT 1 FROM receipts WHERE digest=?", (digest,)).fetchone():
|
||||
return
|
||||
# Fixed 512 MiB journal budget; backpressure, never drop unacknowledged data.
|
||||
pages = db.execute("PRAGMA page_count").fetchone()[0]
|
||||
free = db.execute("PRAGMA freelist_count").fetchone()[0]
|
||||
page_size = db.execute("PRAGMA page_size").fetchone()[0]
|
||||
if (pages - free) * page_size > 512 * 1024**2:
|
||||
raise OSError("journal full")
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO packages(imei,instance,digest,received,raw,packets) "
|
||||
"VALUES(?,?,?,?,?,?)",
|
||||
(imei, device[0], digest, time.time(), raw, json.dumps(packets)),
|
||||
)
|
||||
|
||||
def fetch(self, after):
|
||||
with self.db() as db:
|
||||
rows = db.execute(
|
||||
"SELECT id,instance,digest,received,raw,packets FROM packages "
|
||||
"WHERE id>? ORDER BY id LIMIT 20",
|
||||
(after,),
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": r[0],
|
||||
"instance_id": r[1],
|
||||
"digest": r[2],
|
||||
"received_at": r[3],
|
||||
"raw": base64.b64encode(r[4]).decode(),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
}
|
||||
|
||||
def acknowledge(self, through):
|
||||
with self.db() as db:
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO receipts SELECT digest,received FROM packages WHERE id<=?",
|
||||
(through,),
|
||||
)
|
||||
db.execute("DELETE FROM packages WHERE id<=?", (through,))
|
||||
db.execute("DELETE FROM receipts WHERE at<?", (time.time() - 7 * 86400,))
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Private-free transport observations, independent of device execution state."""
|
||||
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
class TransportEvidence:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
with store.db(write=True) as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS command_transport("
|
||||
"seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,"
|
||||
"command TEXT NOT NULL,state TEXT NOT NULL,body TEXT NOT NULL)"
|
||||
)
|
||||
db.execute(
|
||||
"CREATE INDEX IF NOT EXISTS transport_command ON command_transport(command,seq)"
|
||||
)
|
||||
db.execute("CREATE INDEX IF NOT EXISTS transport_pending ON command_transport(state)")
|
||||
# A process crash cannot tell us whether buffered bytes reached B2.
|
||||
# It must never synthesize a TCP ACK or alter command retry policy.
|
||||
for identifier, body in db.execute(
|
||||
"SELECT id,body FROM command_transport WHERE state IN ('prepared','written')"
|
||||
).fetchall():
|
||||
value = json.loads(body)
|
||||
value.update(state="unconfirmed", reason="host_restarted", closed_at=time.time())
|
||||
db.execute(
|
||||
"UPDATE command_transport SET state=?,body=? WHERE id=?",
|
||||
(value["state"], json.dumps(value), identifier),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def prepare(db, command, stage):
|
||||
value = dict(id=uuid.uuid4().hex, stage=stage, state="prepared", prepared_at=time.time())
|
||||
db.execute(
|
||||
"INSERT INTO command_transport(id,command,state,body) VALUES(?,?,?,?)",
|
||||
(value["id"], command, value["state"], json.dumps(value)),
|
||||
)
|
||||
return value["id"]
|
||||
|
||||
def record(self, events):
|
||||
with self.store.db(write=True) as db:
|
||||
for identifier, phase, at, elapsed, reason in events:
|
||||
row = db.execute(
|
||||
"SELECT body FROM command_transport WHERE id=?", (identifier,)
|
||||
).fetchone()
|
||||
if not row or phase not in {"written", "tcp_acknowledged", "unconfirmed"}:
|
||||
continue
|
||||
value = json.loads(row[0])
|
||||
if value["state"] in {"tcp_acknowledged", "unconfirmed"}:
|
||||
continue
|
||||
if phase == "written":
|
||||
value.setdefault("written_at", at)
|
||||
elif phase == "tcp_acknowledged":
|
||||
value.update(tcp_acknowledged_at=at, tcp_ack_seconds=elapsed)
|
||||
else:
|
||||
value.update(closed_at=at, reason=reason)
|
||||
value["state"] = phase
|
||||
db.execute(
|
||||
"UPDATE command_transport SET state=?,body=? WHERE id=?",
|
||||
(phase, json.dumps(value), identifier),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def read(db, command):
|
||||
rows = db.execute(
|
||||
"SELECT body FROM command_transport WHERE command=? ORDER BY seq DESC LIMIT 32",
|
||||
(command,),
|
||||
).fetchall()
|
||||
return [json.loads(row[0]) for row in reversed(rows)]
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Single-file headless installer entry point, using the same plan/apply engine."""
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Install VPS Host ARNavi on Ubuntu Server 24.04 amd64"
|
||||
)
|
||||
parser.add_argument("--host", help="Public DNS name or IPv4 of this VPS")
|
||||
actions = parser.add_mutually_exclusive_group()
|
||||
actions.add_argument(
|
||||
"--fresh", action="store_true", help="Back up and replace this product installation"
|
||||
)
|
||||
actions.add_argument("--restore", help="Restore the private backup created by --fresh")
|
||||
actions.add_argument("--export-state", help="Stop and fence this VPS; export private state")
|
||||
actions.add_argument("--import-state", help="Restore exported state on an empty Ubuntu VPS")
|
||||
actions.add_argument(
|
||||
"--resume-source",
|
||||
action="store_true",
|
||||
help="Cancel migration fencing; target must already be stopped",
|
||||
)
|
||||
parser.add_argument("--sha256", help="Required SHA-256 of --import-state archive")
|
||||
args = parser.parse_args()
|
||||
if os.geteuid() != 0:
|
||||
parser.error("Run: sudo python3 " + Path(sys.argv[0]).name)
|
||||
# Serialize all owner installer actions, including crash recovery/migration.
|
||||
with open("/run/lock/ndc-mission-vps-installer.lock", "a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
parser.error("Another VPS installer operation is running")
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-install-") as directory:
|
||||
with zipfile.ZipFile(sys.argv[0]) as archive:
|
||||
for name in archive.namelist():
|
||||
if name.startswith("payload/"):
|
||||
relative = Path(name).relative_to("payload")
|
||||
if ".." in relative.parts:
|
||||
raise ValueError("Invalid installer payload")
|
||||
target = Path(directory) / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(archive.read(name))
|
||||
sys.path.insert(0, directory)
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"installer", Path(directory) / "install.py"
|
||||
)
|
||||
engine = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(engine)
|
||||
if args.export_state or args.import_state or args.resume_source:
|
||||
import portable_state
|
||||
|
||||
if args.export_state:
|
||||
portable_state.export_state(engine, Path(args.export_state))
|
||||
elif args.import_state:
|
||||
if args.host or not args.sha256:
|
||||
parser.error("Import preserves the endpoint; provide --sha256, not --host")
|
||||
portable_state.import_state(engine, Path(args.import_state), args.sha256)
|
||||
else:
|
||||
portable_state.resume_source(engine)
|
||||
return
|
||||
if args.restore:
|
||||
engine.restore(Path(args.restore))
|
||||
return
|
||||
host = args.host or input("Public DNS name or IPv4 of this VPS: ").strip()
|
||||
options = argparse.Namespace(host=host, api_port=19443, tracker_port=9922, expect=None)
|
||||
proposal = engine.plan(options)
|
||||
print(
|
||||
json.dumps(
|
||||
{k: proposal[k] for k in ("environment", "configuration", "artifact")}, indent=2
|
||||
)
|
||||
)
|
||||
options.expect = proposal["plan_sha256"]
|
||||
if args.fresh:
|
||||
engine.fresh(options, proposal)
|
||||
else:
|
||||
engine.apply(options, proposal)
|
||||
print(
|
||||
"VPS Host ARNavi ready. Copy the key from "
|
||||
"/opt/nodedc-mission-vps/connect.key into Mission Core."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,311 @@
|
||||
"""Private, quiesced state transfer. Code and system configuration come from the installer."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import ssl
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA = "missioncore.vps-portable-state/v1"
|
||||
FILES = {"host.json", "tls.crt", "tls.key", "connect.key", "journal.sqlite3"}
|
||||
MAX_BYTES = 2 * 1024**3
|
||||
SERVICE = "ndc-mission-vps.service"
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
fd = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def durable_json(path, value):
|
||||
temporary = path.with_name(path.name + ".new")
|
||||
with temporary.open("wb") as stream:
|
||||
temporary.chmod(0o600)
|
||||
stream.write(json.dumps(value, sort_keys=True, indent=2).encode())
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
sync_directory(path.parent)
|
||||
|
||||
|
||||
def options(config):
|
||||
return argparse.Namespace(
|
||||
host=config["public_host"],
|
||||
api_port=config["api_port"],
|
||||
tracker_port=config["tracker"]["port"],
|
||||
expect=None,
|
||||
)
|
||||
|
||||
|
||||
def check_state(state):
|
||||
config = json.loads((state / "host.json").read_text())
|
||||
fingerprint = hashlib.sha256(
|
||||
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
|
||||
).hexdigest()
|
||||
if config["fingerprint"] != fingerprint or config["host_id"] != "vps_" + fingerprint:
|
||||
raise ValueError("state TLS identity mismatch")
|
||||
if (
|
||||
config["endpoint"] != f"https://{config['public_host']}:{config['api_port']}"
|
||||
or config["tracker"]["host"] != config["public_host"]
|
||||
):
|
||||
raise ValueError("inconsistent state endpoints")
|
||||
cert = subprocess.run(
|
||||
["openssl", "x509", "-in", str(state / "tls.crt"), "-pubkey", "-noout"],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
).stdout
|
||||
key = subprocess.run(
|
||||
["openssl", "pkey", "-in", str(state / "tls.key"), "-pubout"],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
).stdout
|
||||
if cert != key:
|
||||
raise ValueError("state private key mismatch")
|
||||
with sqlite3.connect((state / "journal.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
|
||||
if db.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
|
||||
raise ValueError("state journal integrity failure")
|
||||
# Enforce the known state boundary without rewriting its IDs or deadlines.
|
||||
for table in (
|
||||
"state",
|
||||
"devices",
|
||||
"packages",
|
||||
"receipts",
|
||||
"commands",
|
||||
"operations",
|
||||
"operation_attempts",
|
||||
"operation_stops",
|
||||
):
|
||||
db.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()
|
||||
return config
|
||||
|
||||
|
||||
def export_state(engine, destination):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("root required")
|
||||
destination = destination.absolute()
|
||||
if destination.exists() or destination.is_symlink() or not destination.parent.is_dir():
|
||||
raise ValueError("new archive path in an existing directory required")
|
||||
config = json.loads((engine.STATE / "host.json").read_text())
|
||||
proposal = engine.plan(options(config))
|
||||
if not proposal["previous"] or Path(proposal["previous"]).name != proposal["artifact"]:
|
||||
raise ValueError("install this exact release before exporting its state")
|
||||
if (
|
||||
"ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json"
|
||||
not in engine.UNIT.read_text()
|
||||
):
|
||||
raise ValueError("installed service has no persistent migration fence")
|
||||
engine.healthy()
|
||||
allowed = FILES | {"journal.sqlite3-wal", "journal.sqlite3-shm", "journal.sqlite3-journal"}
|
||||
if any(
|
||||
p.name not in allowed or p.is_symlink() or not p.is_file() for p in engine.STATE.iterdir()
|
||||
):
|
||||
raise ValueError("unrecognized private state; export refuses to omit it")
|
||||
required = sum((engine.STATE / name).stat().st_size for name in FILES)
|
||||
if (
|
||||
required > MAX_BYTES
|
||||
or shutil.disk_usage(destination.parent).free < required * 2 + 256 * 1024**2
|
||||
):
|
||||
raise ValueError("insufficient archive space or state exceeds portable limit")
|
||||
fence = engine.ROOT / "migration-fence.json"
|
||||
record = {
|
||||
"schema": SCHEMA,
|
||||
"migration_id": uuid.uuid4().hex,
|
||||
"created_at": time.time(),
|
||||
"monotonic": time.monotonic(),
|
||||
"artifact": proposal["artifact"],
|
||||
"status": "quiescing",
|
||||
}
|
||||
# Persistent unit condition blocks manual/automatic starts and host reboots.
|
||||
# Failure after this point stays fenced; the operator can explicitly resume.
|
||||
durable_json(fence, record)
|
||||
engine.run("systemctl", "stop", SERVICE)
|
||||
active = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True).stdout.strip()
|
||||
if active not in (b"inactive", b"failed"):
|
||||
raise ValueError("source did not stop; migration remains fenced")
|
||||
with tempfile.TemporaryDirectory(prefix=".ndc-vps-export-", dir=destination.parent) as work:
|
||||
work = Path(work)
|
||||
state = work / "state"
|
||||
state.mkdir(mode=0o700)
|
||||
for name in FILES - {"journal.sqlite3"}:
|
||||
shutil.copyfile(engine.STATE / name, state / name)
|
||||
(state / name).chmod(0o600)
|
||||
with (
|
||||
sqlite3.connect(
|
||||
(engine.STATE / "journal.sqlite3").as_uri() + "?mode=ro", uri=True
|
||||
) as src,
|
||||
sqlite3.connect(state / "journal.sqlite3") as dst,
|
||||
):
|
||||
src.backup(dst)
|
||||
(state / "journal.sqlite3").chmod(0o600)
|
||||
check_state(state)
|
||||
record.update(
|
||||
status="source_fenced",
|
||||
files={
|
||||
"state/" + name: {
|
||||
"sha256": sha(state / name),
|
||||
"size": (state / name).stat().st_size,
|
||||
}
|
||||
for name in sorted(FILES)
|
||||
},
|
||||
)
|
||||
durable_json(work / "manifest.json", record)
|
||||
archive = work / "state.tar.gz"
|
||||
with tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as tar:
|
||||
for name in ["manifest.json", *record["files"]]:
|
||||
info = tar.gettarinfo(work / name, arcname=name)
|
||||
info.mode = 0o600
|
||||
info.mtime = int(info.mtime)
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = ""
|
||||
with (work / name).open("rb") as stream:
|
||||
tar.addfile(info, stream)
|
||||
archive.chmod(0o600)
|
||||
with archive.open("rb") as stream:
|
||||
os.fsync(stream.fileno())
|
||||
# Atomic publication without ever overwriting an existing backup.
|
||||
os.link(archive, destination)
|
||||
sync_directory(destination.parent)
|
||||
digest = sha(destination)
|
||||
durable_json(fence, {**record, "archive_sha256": digest})
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "source_fenced",
|
||||
"archive": str(destination),
|
||||
"sha256": digest,
|
||||
"migration_id": record["migration_id"],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def unpack(archive, expected, directory, artifact):
|
||||
if not re.fullmatch(r"[a-f0-9]{64}", expected) or archive.is_symlink() or not archive.is_file():
|
||||
raise ValueError("regular archive and exact SHA-256 required")
|
||||
if archive.stat().st_size > MAX_BYTES or sha(archive) != expected:
|
||||
raise ValueError("archive digest or size mismatch")
|
||||
expected_names = {"manifest.json"} | {"state/" + name for name in FILES}
|
||||
seen, total = set(), 0
|
||||
# Never extract paths/links/modes supplied by an archive or deserialize code.
|
||||
with tarfile.open(archive, "r:gz") as tar:
|
||||
for member in tar:
|
||||
if (
|
||||
member.name not in expected_names
|
||||
or member.name in seen
|
||||
or not member.isfile()
|
||||
or member.pax_headers
|
||||
):
|
||||
raise ValueError("invalid portable archive member")
|
||||
total += member.size
|
||||
limit = MAX_BYTES if member.name == "state/journal.sqlite3" else 1024 * 1024
|
||||
if member.size > limit or total > MAX_BYTES:
|
||||
raise ValueError("portable archive size limit")
|
||||
seen.add(member.name)
|
||||
target = directory / member.name
|
||||
target.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
with target.open("xb") as stream, tar.extractfile(member) as source:
|
||||
target.chmod(0o600)
|
||||
shutil.copyfileobj(source, stream, 1024 * 1024)
|
||||
if seen != expected_names:
|
||||
raise ValueError("incomplete portable archive")
|
||||
record = json.loads((directory / "manifest.json").read_text())
|
||||
if (
|
||||
record.get("schema") != SCHEMA
|
||||
or record.get("status") != "source_fenced"
|
||||
or record.get("artifact") != artifact
|
||||
or set(record.get("files", {})) != expected_names - {"manifest.json"}
|
||||
):
|
||||
raise ValueError("archive requires its exact installer release and complete manifest")
|
||||
for name, item in record["files"].items():
|
||||
if item != {"sha256": sha(directory / name), "size": (directory / name).stat().st_size}:
|
||||
raise ValueError("state integrity mismatch")
|
||||
return record, check_state(directory / "state")
|
||||
|
||||
|
||||
def import_state(engine, archive, expected):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("root required")
|
||||
for path in (engine.ROOT, engine.STATE, engine.UNIT):
|
||||
if path.exists() or path.is_symlink():
|
||||
raise ValueError("portable import requires an empty product installation")
|
||||
if shutil.disk_usage(engine.STATE.parent).free < MAX_BYTES + 256 * 1024**2:
|
||||
raise ValueError("portable import requires 2.25 GiB free staging space")
|
||||
with tempfile.TemporaryDirectory(prefix=".ndc-vps-import-", dir=engine.STATE.parent) as work:
|
||||
work = Path(work)
|
||||
record, config = unpack(archive, expected, work, engine.digest())
|
||||
args = options(config)
|
||||
proposal = engine.plan(args) # OS, prerequisites, ports and firewall, before mutation.
|
||||
args.expect = proposal["plan_sha256"]
|
||||
# Install this shipped code and unit, creating the target's system account.
|
||||
# Only identity/journal state crosses hosts; no old executable/unit/firewall does.
|
||||
staged_state = work / "state"
|
||||
staged_state.chmod(0o700)
|
||||
for path in staged_state.iterdir():
|
||||
with path.open("rb") as stream:
|
||||
os.fsync(stream.fileno())
|
||||
sync_directory(staged_state)
|
||||
# Same-filesystem rename publishes all state at once. A failed copy
|
||||
# must not leave a partial identity or require twice the journal space.
|
||||
os.rename(staged_state, engine.STATE)
|
||||
sync_directory(engine.STATE.parent)
|
||||
engine.apply(args, proposal)
|
||||
durable_json(
|
||||
engine.ROOT / "imported-state.json",
|
||||
{
|
||||
"schema": SCHEMA,
|
||||
"migration_id": record["migration_id"],
|
||||
"archive_sha256": expected,
|
||||
"imported_at": time.time(),
|
||||
"endpoint_preserved": True,
|
||||
},
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "imported",
|
||||
"identity_preserved": True,
|
||||
"migration_id": record["migration_id"],
|
||||
"endpoint_preserved": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def resume_source(engine):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("root required")
|
||||
fence = engine.ROOT / "migration-fence.json"
|
||||
record = json.loads(fence.read_text())
|
||||
if record.get("schema") != SCHEMA or record.get("artifact") != engine.digest():
|
||||
raise ValueError("source fence requires the same installer")
|
||||
fence.unlink()
|
||||
sync_directory(fence.parent)
|
||||
try:
|
||||
engine.run("systemctl", "start", SERVICE)
|
||||
engine.healthy()
|
||||
except Exception:
|
||||
durable_json(fence, record)
|
||||
engine.run("systemctl", "stop", SERVICE)
|
||||
raise
|
||||
durable_json(
|
||||
engine.ROOT / "migration-cancelled.json",
|
||||
{"migration_id": record["migration_id"], "resumed_at": time.time()},
|
||||
)
|
||||
print(json.dumps({"status": "source_resumed", "migration_id": record["migration_id"]}))
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Bounded HTTP clock exchange over real loopback streams; no physical B2."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps.commands import frame
|
||||
from ndc_vps.service import Service
|
||||
from ndc_vps.store import Store
|
||||
from ndc_vps.web_protocol import time_reply
|
||||
|
||||
|
||||
async def qualify():
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-clock-") as directory:
|
||||
root = Path(directory)
|
||||
(root / "host.json").write_text(
|
||||
json.dumps(
|
||||
{"host_id": "vps_" + "a" * 64, "tracker": {"host": "example.org", "port": 9922}}
|
||||
)
|
||||
)
|
||||
store = Store(root)
|
||||
imei = "123456789012345"
|
||||
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
||||
service = Service(store)
|
||||
server = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
||||
writers = []
|
||||
try:
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
monitor, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
writers.append(writer)
|
||||
writer.write(b"\xff\x23" + int(imei).to_bytes(8, "little"))
|
||||
await writer.drain()
|
||||
assert (await monitor.readexactly(9))[0] == 0x7B
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
writers.append(writer)
|
||||
request = (
|
||||
b"[\x01\x00\x0f"
|
||||
+ int(imei).to_bytes(8, "little")
|
||||
+ bytes.fromhex("0001e7020000075d")
|
||||
)
|
||||
for _ in range(2):
|
||||
before = int(time.time())
|
||||
writer.write(b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + request)
|
||||
await writer.drain()
|
||||
header = await reader.readuntil(b"\r\n\r\n")
|
||||
assert header.startswith(b"HTTP/1.1 200 OK\r\n")
|
||||
assert b"Content-Length: 10\r\n" in header
|
||||
body = await reader.readexactly(10)
|
||||
seconds = int.from_bytes(body[5:9], "big")
|
||||
assert before <= seconds <= int(time.time())
|
||||
assert body == time_reply(seconds)
|
||||
with store.db() as db:
|
||||
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 0
|
||||
session = next(iter(service.commands.sessions[imei]))
|
||||
service.commands.session_activity[imei, session] = time.monotonic() - 20
|
||||
original = service.commands.submit(
|
||||
{"id": "d" * 32, "imei": imei, "kind": "read-settings", "password": "123456"}
|
||||
)
|
||||
service.notify(imei)
|
||||
await asyncio.sleep(0.1)
|
||||
assert service.commands.get("d" * 32)["state"] == "queued"
|
||||
# A real incoming telemetry frame wakes the waiting sender.
|
||||
data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0"
|
||||
writers[0].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]")
|
||||
await writers[0].drain()
|
||||
expected = frame("123456*GETP")
|
||||
received = await monitor.readexactly(len(expected) + 4)
|
||||
assert received in (b"{\x00\x01}" + expected, expected + b"{\x00\x01}")
|
||||
receipt = service.commands.get("d" * 32)
|
||||
assert receipt["state"] == "dispatched"
|
||||
assert receipt["expires_at"] == original["expires_at"]
|
||||
assert service.commands.take(imei, session) is None
|
||||
finally:
|
||||
server.close()
|
||||
for writer in writers:
|
||||
writer.close()
|
||||
await asyncio.gather(
|
||||
*(writer.wait_closed() for writer in writers), return_exceptions=True
|
||||
)
|
||||
for _ in range(30):
|
||||
if service.connections == 0:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert service.connections == 0 and not service.wake
|
||||
await server.wait_closed()
|
||||
return {
|
||||
"ok": True,
|
||||
"clock_replies": 2,
|
||||
"same_http_connection": True,
|
||||
"clock_commands_created": 0,
|
||||
"stale_configuration_deferred": True,
|
||||
"fresh_packet_dispatched_once": True,
|
||||
"physical_devices_used": False,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 8)), sort_keys=True))
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Bounded Linux loopback qualification; no tracker, firewall or service changes.
|
||||
|
||||
Run with the unpacked release's Python. Two ephemeral local TCP connections,
|
||||
at most 64 KiB synthetic data, no dependencies or persistent state.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from ndc_vps.delivery import Delivery, queued_bytes
|
||||
|
||||
|
||||
async def qualify(blocked):
|
||||
loop = asyncio.get_running_loop()
|
||||
accepted = loop.create_future()
|
||||
finished = asyncio.Event()
|
||||
handler_done = asyncio.Event()
|
||||
|
||||
async def handler(reader, writer):
|
||||
accepted.set_result(writer)
|
||||
try:
|
||||
await finished.wait()
|
||||
finally:
|
||||
writer.transport.abort()
|
||||
handler_done.set()
|
||||
|
||||
server = await asyncio.start_server(handler, "127.0.0.1", 0)
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
|
||||
client.setblocking(False)
|
||||
guard = None
|
||||
try:
|
||||
await loop.sock_connect(client, server.sockets[0].getsockname())
|
||||
writer = await asyncio.wait_for(accepted, 2)
|
||||
sock = writer.get_extra_info("socket")
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
|
||||
aborted = []
|
||||
|
||||
class ObservedDelivery(Delivery):
|
||||
def abort(self, reason="connection_closed"):
|
||||
aborted.append(time.monotonic())
|
||||
super().abort(reason)
|
||||
|
||||
guard = ObservedDelivery(writer)
|
||||
assert guard.ready()
|
||||
started = time.monotonic()
|
||||
deadline = started + 0.75
|
||||
payload = b"x" * (65536 if blocked else 12)
|
||||
guard.write(payload, deadline)
|
||||
if not blocked:
|
||||
assert await asyncio.wait_for(loop.sock_recv(client, 12), 1) == payload
|
||||
await asyncio.sleep(0.15)
|
||||
kernel = queued_bytes(sock)
|
||||
buffered = writer.transport.get_write_buffer_size()
|
||||
if blocked:
|
||||
assert kernel > 0, "The peer did not actually block TCP delivery"
|
||||
assert not guard.ready(), "An unacknowledged prefix must block a new command"
|
||||
else:
|
||||
assert guard.ready(), "A fully acknowledged stream should accept a new command"
|
||||
await asyncio.sleep(0.85)
|
||||
if blocked:
|
||||
assert writer.is_closing() and sock.fileno() == -1
|
||||
assert aborted and 0 <= aborted[0] - deadline < 0.25
|
||||
reset = False
|
||||
async with asyncio.timeout(2):
|
||||
try:
|
||||
while await loop.sock_recv(client, 4096):
|
||||
pass
|
||||
except ConnectionResetError:
|
||||
reset = True
|
||||
assert reset, "Expected abortive close, not graceful buffered delivery"
|
||||
else:
|
||||
assert not writer.is_closing() and not aborted and not guard.pending
|
||||
return {
|
||||
"case": "blocked-receiver" if blocked else "transport-ack-without-device-reply",
|
||||
"bytes": len(payload),
|
||||
"kernel_queued_before_deadline": kernel,
|
||||
"asyncio_queued_before_deadline": buffered,
|
||||
"deadline_seconds": deadline - started,
|
||||
"abort_seconds": aborted[0] - started if aborted else None,
|
||||
"peer_reset": reset if blocked else False,
|
||||
"passed": True,
|
||||
}
|
||||
finally:
|
||||
if guard:
|
||||
guard.abort()
|
||||
client.close()
|
||||
finished.set()
|
||||
if accepted.done():
|
||||
await asyncio.wait_for(handler_done.wait(), 2)
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
|
||||
|
||||
async def main():
|
||||
assert sys.platform == "linux", "Qualify on the supported Linux host"
|
||||
result = {
|
||||
"session_id": str(uuid.uuid4()),
|
||||
"version": VERSION,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"cases": [],
|
||||
}
|
||||
for blocked in (False, True):
|
||||
result["cases"].append(await qualify(blocked))
|
||||
result["completed_utc"] = datetime.now(UTC).isoformat()
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,286 @@
|
||||
"""Crash and response-loss qualification on isolated loopback sockets and SQLite.
|
||||
|
||||
Uses the installed ndc_vps package unchanged. One synthetic tracker at a time,
|
||||
no production database, TLS endpoint, firewall, physical device or service change.
|
||||
The internal HTTP loopback harness does not qualify production TLS transport.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from ndc_vps.service import Service
|
||||
from ndc_vps.store import Store
|
||||
|
||||
IMEI = "123456789012345"
|
||||
TOKEN = "synthetic-owner-token-" + "a" * 32
|
||||
|
||||
|
||||
def initialize(root):
|
||||
(root / "host.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"host_id": "vps_" + "a" * 64,
|
||||
"tracker": {"host": "synthetic.example", "port": 9922},
|
||||
}
|
||||
)
|
||||
)
|
||||
store = Store(root)
|
||||
store.set_devices([{"imei": IMEI, "instance_id": "c" * 32}])
|
||||
with store.db() as db:
|
||||
db.execute(
|
||||
"INSERT INTO state VALUES('owner',?)",
|
||||
(
|
||||
json.dumps(
|
||||
{
|
||||
"core_id": "synthetic",
|
||||
"token": hashlib.sha256(TOKEN.encode()).hexdigest(),
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
return store
|
||||
|
||||
|
||||
async def child(root):
|
||||
service = Service(Store(root))
|
||||
api = await asyncio.start_server(service.api, "127.0.0.1", 0)
|
||||
tracker = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
||||
print(
|
||||
json.dumps(
|
||||
{"api": api.sockets[0].getsockname()[1], "tracker": tracker.sockets[0].getsockname()[1]}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
async with api, tracker:
|
||||
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, root):
|
||||
self.root, self.process, self.peer = root, None, None
|
||||
self.store = initialize(root)
|
||||
self.frames = []
|
||||
|
||||
async def start(self):
|
||||
self.process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
str(Path(__file__).resolve()),
|
||||
"--child",
|
||||
str(self.root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
line = await asyncio.wait_for(self.process.stdout.readline(), 8)
|
||||
if not line:
|
||||
raise RuntimeError((await self.process.stderr.read()).decode())
|
||||
self.ports = json.loads(line)
|
||||
|
||||
async def stop(self):
|
||||
if self.peer:
|
||||
self.peer[1].transport.abort()
|
||||
self.peer = None
|
||||
if self.process and self.process.returncode is None:
|
||||
self.process.kill() # Deliberately no graceful drain or in-memory handoff.
|
||||
await asyncio.wait_for(self.process.wait(), 5)
|
||||
|
||||
async def restart(self):
|
||||
await self.stop()
|
||||
await self.start()
|
||||
|
||||
def body(self, **extra):
|
||||
return {
|
||||
"id": uuid.uuid4().hex,
|
||||
"imei": IMEI,
|
||||
"kind": "request-position",
|
||||
"model": 231,
|
||||
"firmware": "0.01",
|
||||
"not_after": time.time() + 15,
|
||||
**extra,
|
||||
}
|
||||
|
||||
async def http(self, method, path, body=None, *, loss=None):
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", self.ports["api"])
|
||||
data = json.dumps(body or {}).encode()
|
||||
header = (
|
||||
f"{method} {path} HTTP/1.1\r\nHost: localhost\r\n"
|
||||
f"Authorization: Bearer {TOKEN}\r\nContent-Length: {len(data)}\r\n\r\n"
|
||||
).encode()
|
||||
try:
|
||||
writer.write(header + (data[:-4] if loss == "before-body" else data))
|
||||
await writer.drain()
|
||||
if loss == "before-body":
|
||||
return None
|
||||
if loss == "after-commit":
|
||||
async with asyncio.timeout(3):
|
||||
while True:
|
||||
with self.store.db() as db:
|
||||
exists = db.execute(
|
||||
"SELECT 1 FROM commands WHERE id=?", (body["id"],)
|
||||
).fetchone()
|
||||
if exists:
|
||||
return None # The client intentionally never observes the HTTP result.
|
||||
await asyncio.sleep(0.02)
|
||||
raw = await asyncio.wait_for(reader.read(), 4)
|
||||
head, payload = raw.split(b"\r\n\r\n", 1)
|
||||
return int(head.split()[1]), json.loads(payload)
|
||||
finally:
|
||||
writer.transport.abort()
|
||||
|
||||
async def get(self, body):
|
||||
status, result = await self.http("GET", "/v1/commands/" + body["id"])
|
||||
assert status == 200, result
|
||||
return result
|
||||
|
||||
async def submit(self, body, **kwargs):
|
||||
value = await self.http("POST", "/v1/commands", body, **kwargs)
|
||||
if value is not None:
|
||||
assert value[0] == 200, value
|
||||
return value[1]
|
||||
|
||||
async def connect(self):
|
||||
if self.peer:
|
||||
self.peer[1].transport.abort()
|
||||
self.peer = await asyncio.open_connection("127.0.0.1", self.ports["tracker"])
|
||||
self.peer[1].write(b"\xff\x23" + int(IMEI).to_bytes(8, "little"))
|
||||
await self.peer[1].drain()
|
||||
assert len(await asyncio.wait_for(self.peer[0].readexactly(9), 2)) == 9
|
||||
|
||||
async def frame(self):
|
||||
first = await asyncio.wait_for(self.peer[0].readexactly(4), 3)
|
||||
raw = first + await asyncio.wait_for(self.peer[0].readexactly(first[1] + 1), 2)
|
||||
assert raw[0] == 0x7B and raw[-1] == 0x7D
|
||||
self.frames.append(raw)
|
||||
return raw
|
||||
|
||||
async def no_frame(self):
|
||||
try:
|
||||
data = await asyncio.wait_for(self.peer[0].read(1), 0.35)
|
||||
except TimeoutError:
|
||||
return
|
||||
raise AssertionError(f"Unexpected data or connection loss: {data.hex()}")
|
||||
|
||||
async def reply(self, frame):
|
||||
payload = struct.pack("<I", int(time.time())) + b"\0" + frame[5:9]
|
||||
raw = b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]"
|
||||
self.peer[1].write(raw)
|
||||
await self.peer[1].drain()
|
||||
assert await asyncio.wait_for(self.peer[0].readexactly(4), 2) == b"{\0\x01}"
|
||||
|
||||
|
||||
async def qualify():
|
||||
result = {
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"version": VERSION,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"physical_devices_used": False,
|
||||
"production_state_used": False,
|
||||
"cases": [],
|
||||
}
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-faults-") as name:
|
||||
harness = Harness(Path(name))
|
||||
await harness.start()
|
||||
try:
|
||||
# Lost upload before any accepted operation.
|
||||
body = harness.body()
|
||||
await harness.submit(body, loss="before-body")
|
||||
status, _ = await harness.http("GET", "/v1/commands/" + body["id"])
|
||||
assert status == 400
|
||||
await harness.submit(body)
|
||||
await harness.connect()
|
||||
await harness.reply(await harness.frame())
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
result["cases"].append({"name": "lost-request-retry-same-id", "passed": True})
|
||||
|
||||
# Lose HTTP result, then kill the process with a durable queued read.
|
||||
await harness.restart()
|
||||
body = harness.body()
|
||||
await harness.submit(body, loss="after-commit")
|
||||
await harness.restart()
|
||||
queued = await harness.submit(body)
|
||||
assert queued["state"] == "queued" and queued["expires_at"] == body["not_after"]
|
||||
await harness.connect()
|
||||
frame = await harness.frame()
|
||||
await harness.submit(body)
|
||||
await harness.no_frame()
|
||||
await harness.reply(frame)
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
result["cases"].append({"name": "lost-http-response-crash-queued-read", "passed": True})
|
||||
|
||||
# No tracker until after the original deadline, even across SIGKILL.
|
||||
await harness.restart()
|
||||
body = harness.body(not_after=time.time() + 0.8)
|
||||
await harness.submit(body)
|
||||
await harness.restart()
|
||||
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||
await harness.connect()
|
||||
await harness.no_frame()
|
||||
assert (await harness.submit(body))["state"] == "expired"
|
||||
result["cases"].append({"name": "offline-expiry-not-extended-by-crash", "passed": True})
|
||||
|
||||
# TCP accepted the bytes; no command ACK. The runtime must not say success.
|
||||
body = harness.body(not_after=time.time() + 0.8)
|
||||
await harness.submit(body)
|
||||
await harness.frame()
|
||||
await asyncio.sleep(max(0, body["not_after"] - time.time()) + 0.1)
|
||||
assert (await harness.get(body))["state"] == "unconfirmed"
|
||||
await harness.restart()
|
||||
await harness.connect()
|
||||
await harness.no_frame()
|
||||
assert (await harness.submit(body))["state"] == "unconfirmed"
|
||||
result["cases"].append({"name": "tcp-ack-without-command-reply", "passed": True})
|
||||
|
||||
# Effect bytes were received by the synthetic peer; crash before a reply.
|
||||
body = harness.body(kind="set-output", pin=4, enabled=True, password="123456")
|
||||
await harness.submit(body)
|
||||
frame = await harness.frame()
|
||||
assert frame[2] == 0xFC and b"*SERV*8.4.1" in frame
|
||||
await harness.restart()
|
||||
await harness.connect()
|
||||
assert (await harness.submit(body))["state"] == "uncertain"
|
||||
await harness.no_frame()
|
||||
result["cases"].append({"name": "dispatched-output-crash-no-replay", "passed": True})
|
||||
|
||||
# A fresh independent read still works on the same identity after recovery.
|
||||
body = harness.body()
|
||||
await harness.submit(body)
|
||||
await harness.reply(await harness.frame())
|
||||
assert (await harness.get(body))["state"] == "device_confirmed"
|
||||
with harness.store.db() as db:
|
||||
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 6
|
||||
assert (
|
||||
db.execute("SELECT instance FROM devices WHERE imei=?", (IMEI,)).fetchone()[0]
|
||||
== "c" * 32
|
||||
)
|
||||
result["cases"].append(
|
||||
{"name": "identity-and-history-survive-recovery", "passed": True}
|
||||
)
|
||||
assert len(harness.frames) == 5
|
||||
result["received_command_frames"] = len(harness.frames)
|
||||
finally:
|
||||
await harness.stop()
|
||||
result.update(
|
||||
completed_utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - result["monotonic"],
|
||||
ok=True,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--child":
|
||||
asyncio.run(child(Path(sys.argv[2])))
|
||||
else:
|
||||
print(json.dumps(asyncio.run(qualify()), indent=2))
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Durable intent versus attempts over real isolated sockets and hard process loss."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from qualify_faults import Harness
|
||||
|
||||
|
||||
async def qualify():
|
||||
result = {
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"version": VERSION,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"physical_devices_used": False,
|
||||
"production_state_used": False,
|
||||
}
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-operations-") as name:
|
||||
h = Harness(Path(name))
|
||||
await h.start()
|
||||
try:
|
||||
body = h.body()
|
||||
body.pop("not_after")
|
||||
|
||||
async def get():
|
||||
status, value = await h.http("GET", "/v1/operations/" + body["id"])
|
||||
assert status == 200, value
|
||||
return value
|
||||
|
||||
# Truncated client request admits nothing. Stable ID recovers admission.
|
||||
await h.http("POST", "/v1/operations", body, loss="before-body")
|
||||
assert (await h.http("GET", "/v1/operations/" + body["id"]))[0] == 400
|
||||
assert (await h.http("POST", "/v1/operations", body))[0] == 200
|
||||
await h.restart()
|
||||
assert (await get())["attempt_count"] == 0
|
||||
await h.connect()
|
||||
first = await h.frame()
|
||||
assert (await get())["state"] == "dispatched"
|
||||
# Lose response, hard kill VPS. The user job survives its uncertain attempt.
|
||||
await h.restart()
|
||||
pending = await get()
|
||||
assert pending["state"] == "queued" and pending["attempt_count"] == 1
|
||||
await asyncio.sleep(max(0, pending["next_attempt_at"] - time.time()) + 0.1)
|
||||
await h.connect()
|
||||
second = await h.frame()
|
||||
assert first[5:9] != second[5:9]
|
||||
await h.reply(first) # Delayed receipt must not finish a newer attempt.
|
||||
assert (await get())["state"] == "dispatched"
|
||||
await h.reply(second)
|
||||
confirmed = await get()
|
||||
assert confirmed["state"] == "device_confirmed" and confirmed["attempt_count"] == 2
|
||||
await h.no_frame()
|
||||
await h.restart()
|
||||
assert await get() == confirmed
|
||||
assert (await h.http("POST", "/v1/operations", body))[1] == confirmed
|
||||
status, history = await h.http("GET", "/v1/operations/" + body["id"] + "/attempts")
|
||||
assert status == 200 and len(history["items"]) == 2
|
||||
assert [i["state"] for i in history["items"]] == ["device_confirmed", "uncertain"]
|
||||
# Cancellation arriving before a delayed POST survives a crash as a tombstone.
|
||||
stopped = {**body, "id": uuid.uuid4().hex}
|
||||
await h.http(
|
||||
"POST", "/v1/operations/" + stopped["id"] + "/cancel", {"kind": stopped["kind"]}
|
||||
)
|
||||
await h.restart()
|
||||
assert (await h.http("POST", "/v1/operations", stopped))[1]["state"] == "stopped"
|
||||
with h.store.db() as db:
|
||||
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
|
||||
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
|
||||
result.update(
|
||||
passed=True,
|
||||
attempts=2,
|
||||
intents=1,
|
||||
hard_restart_recovery=True,
|
||||
late_receipt_isolated=True,
|
||||
cancelled_post_not_admitted=True,
|
||||
elapsed_seconds=time.monotonic() - result["monotonic"],
|
||||
)
|
||||
return result
|
||||
finally:
|
||||
await h.stop()
|
||||
|
||||
|
||||
async def main():
|
||||
async with asyncio.timeout(25):
|
||||
print(json.dumps(await qualify(), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Two real loopback streams, one synthetic B2, no physical commands or state."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import struct
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from qualify_faults import Harness
|
||||
|
||||
|
||||
async def qualify():
|
||||
result = {
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"version": VERSION,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"physical_devices_used": False,
|
||||
"production_state_used": False,
|
||||
}
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-receipts-") as name:
|
||||
harness = Harness(Path(name))
|
||||
alternate = None
|
||||
await harness.start()
|
||||
try:
|
||||
await harness.connect()
|
||||
alternate = harness.peer
|
||||
harness.peer = None # Keep the first monitoring stream open.
|
||||
await harness.connect()
|
||||
body = harness.body()
|
||||
await harness.submit(body)
|
||||
wire = await harness.frame() # Most recently active stream wins dispatch.
|
||||
|
||||
async def reply(code):
|
||||
data = struct.pack("<I", int(time.time())) + bytes((code,)) + wire[5:9]
|
||||
alternate[1].write(b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]")
|
||||
await alternate[1].drain()
|
||||
assert await asyncio.wait_for(alternate[0].readexactly(4), 2) == b"{\0\x01}"
|
||||
|
||||
await reply(6)
|
||||
accepted = await harness.get(body)
|
||||
assert accepted["state"] == "dispatched" and accepted["device_code"] == 6
|
||||
assert accepted["reply_via_alternate_session"] is True
|
||||
await reply(0)
|
||||
confirmed = await harness.get(body)
|
||||
assert confirmed["state"] == "device_confirmed"
|
||||
assert confirmed["device_accepted_at"] == accepted["device_accepted_at"]
|
||||
await reply(5) # A duplicate cannot downgrade a committed result.
|
||||
assert await harness.get(body) == confirmed
|
||||
await harness.no_frame()
|
||||
alternate[1].transport.abort()
|
||||
alternate = None
|
||||
await harness.restart()
|
||||
assert await harness.get(body) == confirmed
|
||||
with harness.store.db() as db:
|
||||
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
|
||||
result.update(
|
||||
passed=True,
|
||||
sends=len(harness.frames),
|
||||
alternate_stream_confirmed=True,
|
||||
ack_not_final=True,
|
||||
result_survived_sigkill=True,
|
||||
elapsed_seconds=time.monotonic() - result["monotonic"],
|
||||
)
|
||||
return result
|
||||
finally:
|
||||
if alternate:
|
||||
alternate[1].transport.abort()
|
||||
await harness.stop()
|
||||
|
||||
|
||||
async def main():
|
||||
async with asyncio.timeout(20):
|
||||
print(json.dumps(await qualify(), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,158 @@
|
||||
"""SIGKILL during full-image verification; isolated synthetic B2 and SQLite."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps import VERSION
|
||||
from ndc_vps.commands import frame
|
||||
from ndc_vps.usb_protocol import Configuration, Setting
|
||||
from ndc_vps.web_protocol import decode_settings_reply
|
||||
from qualify_faults import IMEI, Harness
|
||||
|
||||
|
||||
async def web(harness, opcode, payload=b""):
|
||||
data = int(IMEI).to_bytes(8, "little") + bytes.fromhex("0001e7020000")
|
||||
data += bytes([opcode]) + payload
|
||||
body = b"[\x01" + len(data).to_bytes(2, "big") + data + b"]"
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", harness.ports["tracker"])
|
||||
try:
|
||||
writer.write(
|
||||
b"POST /c/index.php HTTP/1.1\r\n"
|
||||
+ f"Content-Length: {len(body)}\r\n\r\n".encode()
|
||||
+ body
|
||||
)
|
||||
await writer.drain()
|
||||
try:
|
||||
header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 3)
|
||||
except asyncio.IncompleteReadError as error:
|
||||
assert not error.partial
|
||||
return None
|
||||
except ConnectionResetError:
|
||||
return None # Linux abortive close when no settings image is authorized.
|
||||
size = next(
|
||||
int(line.split(b":")[1])
|
||||
for line in header.split(b"\r\n")
|
||||
if line.lower().startswith(b"content-length:")
|
||||
)
|
||||
return await asyncio.wait_for(reader.readexactly(size), 3)
|
||||
finally:
|
||||
writer.transport.abort()
|
||||
|
||||
|
||||
async def stage(harness, body, expected):
|
||||
pending = await harness.get(body)
|
||||
await asyncio.sleep(max(0, pending.get("not_before", 0) - time.time()) + 0.05)
|
||||
# Fresh telemetry wakes the sender after stage pacing, as in production.
|
||||
data = int(time.time()).to_bytes(4, "little") + b"\x63\0\0\0\0"
|
||||
harness.peer[1].write(b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]")
|
||||
await harness.peer[1].drain()
|
||||
assert await asyncio.wait_for(harness.peer[0].readexactly(4), 3) == b"{\0\x01}"
|
||||
assert await harness.frame() == frame("123456*SERV*1." + str(expected))
|
||||
|
||||
|
||||
async def qualify():
|
||||
start = time.monotonic()
|
||||
result = {
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"started_utc": datetime.now(UTC).isoformat(),
|
||||
"started_monotonic": start,
|
||||
"version": VERSION,
|
||||
"physical_devices_used": False,
|
||||
"production_state_used": False,
|
||||
}
|
||||
before = Configuration(
|
||||
tuple(
|
||||
Setting(n, v)
|
||||
for n, v in (
|
||||
(3, b"example.org"),
|
||||
(4, b"\x26\xc2"),
|
||||
(5, b"123456"),
|
||||
(8, b"\0"),
|
||||
(70, b"example.org"),
|
||||
(71, b"\x26\xc2"),
|
||||
(25, b"\0\x0f"),
|
||||
(222, b"opaque"),
|
||||
)
|
||||
)
|
||||
)
|
||||
target = Configuration(
|
||||
tuple(Setting(r.number, b"\0\x10" if r.number == 25 else r.value) for r in before.records)
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-recovery-") as name:
|
||||
harness = Harness(Path(name))
|
||||
await harness.start()
|
||||
try:
|
||||
await harness.connect()
|
||||
body = harness.body(
|
||||
kind="configure-all",
|
||||
password="123456",
|
||||
not_after=time.time() + 150,
|
||||
expected_sha256=hashlib.sha256(before.encode()).hexdigest(),
|
||||
target_configuration=target.encode().hex(),
|
||||
)
|
||||
accepted = await harness.submit(body)
|
||||
assert await harness.frame() == frame("123456*SERV*1.9")
|
||||
assert await web(harness, 5, before.encode()) == bytes.fromhex("5b00030005015d")
|
||||
await stage(harness, body, 8)
|
||||
assert decode_settings_reply(await web(harness, 2)).encode() == target.encode()
|
||||
await harness.restart() # image received, readback not yet dispatched
|
||||
pending = await harness.get(body)
|
||||
assert pending["state"] == "queued" and pending["recovery_count"] == 1
|
||||
assert pending["expires_at"] == accepted["expires_at"]
|
||||
await harness.connect()
|
||||
assert await web(harness, 2) is None # never re-serve the settings image
|
||||
await stage(harness, body, 9)
|
||||
await harness.restart() # readback sent, but no result yet
|
||||
pending = await harness.submit(body) # same immutable operation
|
||||
assert pending["state"] == "queued" and pending["recovery_count"] == 2
|
||||
assert pending["expires_at"] == accepted["expires_at"]
|
||||
await harness.connect()
|
||||
assert await web(harness, 2) is None
|
||||
await stage(harness, body, 9)
|
||||
# B2-side reconnect after a read dispatch, with the VPS still alive.
|
||||
await harness.connect()
|
||||
pending = await harness.get(body)
|
||||
assert pending["expires_at"] == accepted["expires_at"]
|
||||
await stage(harness, body, 9)
|
||||
assert await web(harness, 2) is None
|
||||
assert await web(harness, 5, target.encode()) == bytes.fromhex("5b00030005015d")
|
||||
final = await harness.get(body)
|
||||
assert final["state"] == "verified" and final["recovery_verification"]
|
||||
assert final["configuration"] == target.encode().hex()
|
||||
await harness.restart()
|
||||
assert await harness.get(body) == final
|
||||
await harness.connect()
|
||||
await harness.no_frame()
|
||||
assert len(harness.frames) == 5
|
||||
assert harness.frames.count(frame("123456*SERV*1.8")) == 1
|
||||
with harness.store.db() as db:
|
||||
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
|
||||
result.update(
|
||||
ok=True,
|
||||
crashes_during_operation=2,
|
||||
image_writes=1,
|
||||
independent_readbacks_sent=3,
|
||||
tracker_reconnects_during_verification=1,
|
||||
original_deadline_preserved=True,
|
||||
durable_final_result=True,
|
||||
command_rows=1,
|
||||
)
|
||||
finally:
|
||||
await harness.stop()
|
||||
result.update(
|
||||
completed_utc=datetime.now(UTC).isoformat(), elapsed_seconds=time.monotonic() - start
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
print(json.dumps(asyncio.run(asyncio.wait_for(qualify(), 80)), indent=2))
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Bounded release self-check on isolated synthetic state; no physical tracker."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import struct
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ndc_vps.commands import Commands
|
||||
from ndc_vps.service import Service
|
||||
from ndc_vps.store import Store
|
||||
|
||||
|
||||
async def qualify():
|
||||
started = time.monotonic()
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-vps-runtime-") as directory:
|
||||
root = Path(directory)
|
||||
(root / "host.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"host_id": "vps_" + "a" * 64,
|
||||
"tracker": {"host": "synthetic.example", "port": 9922},
|
||||
}
|
||||
)
|
||||
)
|
||||
store = Store(root)
|
||||
imei = "123456789012345"
|
||||
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
||||
body = {
|
||||
"id": "a" * 32,
|
||||
"imei": imei,
|
||||
"kind": "request-position",
|
||||
"model": 231,
|
||||
"firmware": "0.01",
|
||||
"not_after": time.time() + 20,
|
||||
}
|
||||
commands = Commands(store)
|
||||
first = commands.submit(body)
|
||||
commands = Commands(store)
|
||||
assert commands.get(body["id"])["state"] == "queued"
|
||||
assert commands.submit(body) == first
|
||||
commands.sessions[imei] = {"new"}
|
||||
wire = commands.take(imei, "new")
|
||||
assert wire and commands.take(imei, "new") is None
|
||||
data = struct.pack("<I", int(time.time())) + b"\0" + wire[5:9]
|
||||
reply = b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
|
||||
commands.sessions[imei].add("second-monitoring-stream")
|
||||
commands.receive(imei, reply, "second-monitoring-stream")
|
||||
assert commands.submit(body)["state"] == "device_confirmed"
|
||||
assert commands.take(imei, "new") is None
|
||||
assert Commands(store).get(body["id"])["state"] == "device_confirmed"
|
||||
with store.db() as db:
|
||||
assert db.execute("SELECT COUNT(*) FROM commands").fetchone()[0] == 1
|
||||
plan = db.execute(
|
||||
"EXPLAIN QUERY PLAN SELECT id,body FROM commands WHERE imei=? "
|
||||
"AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid",
|
||||
(imei,),
|
||||
).fetchall()
|
||||
assert any("USING INDEX commands_active" in r[-1] for r in plan)
|
||||
effect = {**body, "id": "b" * 32, "kind": "pulse-output", "pin": 4, "seconds": 1}
|
||||
commands.submit(effect)
|
||||
assert commands.take(imei, "new")
|
||||
commands = Commands(store)
|
||||
commands.sessions[imei] = {"after-crash"}
|
||||
assert commands.submit(effect)["state"] == "uncertain"
|
||||
assert commands.take(imei, "after-crash") is None
|
||||
late = {**effect, "id": "d" * 32, "not_after": time.time() - 1}
|
||||
assert commands.submit(late)["state"] == "expired"
|
||||
assert commands.take(imei, "after-crash") is None
|
||||
assert commands.wait_delay(imei) is None
|
||||
|
||||
service = Service(store)
|
||||
service.commands.sessions[imei] = {"idle"}
|
||||
original = service.commands.take_delivery
|
||||
polls = []
|
||||
written = asyncio.Event()
|
||||
frames = []
|
||||
|
||||
def take(*args):
|
||||
polls.append(time.monotonic())
|
||||
return original(*args)
|
||||
|
||||
service.commands.take_delivery = take
|
||||
|
||||
class Writer:
|
||||
def is_closing(self):
|
||||
return False
|
||||
|
||||
async def drain(self):
|
||||
pass
|
||||
|
||||
class Delivery:
|
||||
def ready(self):
|
||||
return True
|
||||
|
||||
def write(self, data, deadline):
|
||||
frames.append(data)
|
||||
written.set()
|
||||
|
||||
def abort(self):
|
||||
pass
|
||||
|
||||
task = asyncio.create_task(service.send_commands(imei, Writer(), "idle", Delivery()))
|
||||
try:
|
||||
await asyncio.sleep(1.1)
|
||||
assert len(polls) == 1
|
||||
service.commands.submit({**body, "id": "f" * 32})
|
||||
service.notify(imei)
|
||||
await asyncio.wait_for(written.wait(), 1)
|
||||
assert len(frames) == 1
|
||||
finally:
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
assert not service.wake
|
||||
return {
|
||||
"ok": True,
|
||||
"monotonic_seconds": time.monotonic() - started,
|
||||
"queued_read_survived_restart": True,
|
||||
"duplicate_post_single_operation": True,
|
||||
"dispatched_effect_not_replayed": True,
|
||||
"expired_effect_not_dispatched": True,
|
||||
"active_query_uses_index": True,
|
||||
"idle_checks_over_1_second": 1,
|
||||
"new_command_woke_idle_sender": True,
|
||||
"physical_devices_used": False,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(asyncio.run(qualify()), sort_keys=True))
|
||||
@@ -0,0 +1,191 @@
|
||||
# Автоматическая настройка связи B2
|
||||
|
||||
Дата: 2026-09-28. Статус: проект полного решения по требованию владельца.
|
||||
Первый цикл применения уже принят в ограниченной области:
|
||||
[выбор карты, подбор доступа и проверка результата через VPS 0.1.38](CARD_ACCESS_APPLICATION_20260928.md).
|
||||
Не следует считать это приёмкой всех пунктов данного проекта.
|
||||
|
||||
Последующее уточнение владельца: [обе карты разрешены, выбор задаёт
|
||||
предпочтение с автоматическим резервом](SIM_PREFERENCE_AND_FALLBACK_20260928.md).
|
||||
Ранее проверенный выбор через запрет второй SIM этому требованию не
|
||||
соответствует. Новая семантика не считается реализованной переименованием
|
||||
существующего селектора; сначала нужен подтверждённый исполнитель в B2 или
|
||||
независимый локальный канал.
|
||||
|
||||
Первый программный этап реализован в
|
||||
[журнале наблюдений SIM](SIM_OBSERVATION_RUNTIME_20260928.md): источники
|
||||
идентичности разделены, полные сведения не затираются неполным чтением,
|
||||
история не выдаётся за текущее положение карты. Широкий каталог, офлайн-подбор
|
||||
и фоновая реакция на замену карты ниже остаются проектом.
|
||||
|
||||
Продолжение: [полные SID двух SIM в стартовых пакетах собственного VPS](NETWORK_SIM_IDENTITY_20260928.md).
|
||||
Они сопоставлены с USB-наблюдениями двух расстановок; Core хранит их время и
|
||||
не выдаёт старый пакет за свежий. Это позволяет узнавать известную карту
|
||||
в другом слоте по сети. В 0.1.38 эта привязка используется при явном сохранении
|
||||
настроек, с проверкой карты на VPS перед записью и при подтверждении результата.
|
||||
|
||||
## Требование
|
||||
|
||||
Владелец меняет SIM или переставляет её между слотами; система определяет
|
||||
доступные данные о карте, выбирает подходящие параметры и проверяет выход на
|
||||
собственный VPS. Пользователь не должен каждый раз назначать операторов слотам.
|
||||
Справочник операторов должен обновляться и редактироваться отдельно от прошивки.
|
||||
|
||||
План отдельной ручной записи МТС в SIM 1 остановлен до отправки конфигурации
|
||||
после уточнения владельца. Повторное USB-чтение на том этапе, когда обе SIM
|
||||
были извлечены, подтвердило исходный образ; записи не было. В последующем
|
||||
[опыте с МТС в SIM 2](MTS_MODEM_DIAGNOSTIC_20260928.md) связь с собственным VPS
|
||||
заработала с тем же образом конфигурации и сохранилась после отключения USB.
|
||||
Это квалификация данного подключения, а не автоматической настройки новой SIM.
|
||||
|
||||
## Что уже известно
|
||||
|
||||
- Код содержит два неизменяемых публичных пресета: МТС и МегаФон.
|
||||
- Модель 231/0.01 позволяет читать и задавать APN, логин и пароль отдельно
|
||||
для слотов (поля 67–69 и 89–91). Наличие этих полей не доказывает встроенный
|
||||
каталог APN или исполнение собственного кода в B2.
|
||||
- INTERNAL передаёт коды обслуживающих сетей и состояние SIM. Обслуживающая
|
||||
сеть не всегда определяет поставщика SIM или тариф; нельзя подменять
|
||||
неопределённого оператора именем из сохранённого APN.
|
||||
- Ранние USB-ответы SID содержали неполные идентификаторы. Они не
|
||||
являются доказанным полным ICCID и не дают оснований угадывать префикс
|
||||
оператора. `MN` — IMEI модема, не IMSI карты. В последующей пассивной записи
|
||||
запуска с МТС в SIM 2 (сессия `mts-modem-diagnostic-b0fb46ee12a849ff96fe25db140f4d0f`)
|
||||
наблюдались ответы внутреннего модема на `AT+CCID` и `AT+CIMI`: полный
|
||||
20-значный ICCID и 15-значный IMSI с префиксом, согласованным с сетью МТС.
|
||||
Наш наблюдатель этих AT-команд не отправлял. Это подтверждает доступность
|
||||
идентификаторов в данном потоке запуска, но ещё не является квалификацией
|
||||
запроса по требованию, двух SIM одновременно или распознавания всех MVNO.
|
||||
Последующая [перестановка той же карты](SIM_SLOT_IDENTITY_20260928.md)
|
||||
подтвердила полный ICCID штатным запросом `I 7` в обоих слотах, в том числе
|
||||
без интернета. Идентификатор совпал с ответом модема на `AT+CCID`; при возврате
|
||||
карта снова определилась во втором слоте. Это закрывает запрос ICCID и
|
||||
привязку к слоту для одной испытанной МТС, установленной без второй карты.
|
||||
Следующий [опыт с двумя SIM](DUAL_SIM_IDENTITY_20260928.md) подтвердил
|
||||
распознавание обеих карт и операторов в потоке запуска до и после обмена
|
||||
слотами, но выявил ограничение `I 7`: для первого слота он возвращал 12 цифр,
|
||||
для второго — 20, в том числе при повторном чтении. Кроме того, сырой CCID
|
||||
МегаФона содержит 18 цифр и `ff`, а SID прошивки — отличающееся 20-значное
|
||||
число. Поэтому ни длина SID, ни его совпадение с номером слота не являются
|
||||
достаточным основанием для автоматической записи. Запрос IMSI по требованию,
|
||||
канонизация нестандартного CCID и произвольные операторы ещё не квалифицированы.
|
||||
- Чтение по USB работает и без SIM/мобильного интернета. При этом нынешний
|
||||
продуктовый USB-адаптер поддерживает Mac оператора, не бортовой Linux.
|
||||
- Нативный автоматический подбор APN на B2 пока не подтверждён. В руководстве
|
||||
описаны явная настройка и очистка APN; семантика `auto` или пустого значения
|
||||
как автоматического режима для этой прошивки не установлена.
|
||||
|
||||
## Предлагаемая структура справочника
|
||||
|
||||
Отделить опубликованные параметры доступа от идентичности карты, положения
|
||||
в слоте и политики выбора активной SIM.
|
||||
|
||||
Каждая неизменяемая редакция записи содержит:
|
||||
|
||||
- стабильный идентификатор оператора/варианта услуги и номер редакции;
|
||||
- название, страну и область применения (обычная SIM, корпоративная услуга);
|
||||
- APN, способ авторизации и публичные данные доступа, если они предусмотрены;
|
||||
- источник, дату проверки и отдельный статус проверки на физическом B2;
|
||||
- правила распознавания с указанием необходимого доказательства;
|
||||
- известные альтернативные параметры того же оператора и порядок проверки;
|
||||
- ограничения применимости (тариф, регион, тип SIM/устройства).
|
||||
|
||||
Публичная документация оператора не означает успешного испытания данного
|
||||
тарифа на модеме B2. Требуемые оператором параметры, которые наш интерфейс
|
||||
устройства пока не умеет задавать, должны оставаться явно не квалифицированы.
|
||||
|
||||
Редактор в Mission Core должен создавать новую редакцию, позволять добавить
|
||||
собственную запись и вернуть предыдущую. Пользовательские/корпоративные
|
||||
пароли хранятся приватно, отдельно от общих переносимых профилей.
|
||||
Обновление общей базы не затирает собственные настройки организации и не
|
||||
перезаписывает немедленно работающие трекеры.
|
||||
|
||||
Созданная операция содержит снимок выбранных параметров и редакцию каталога.
|
||||
Редактирование справочника не меняет содержимое уже ожидающей команды.
|
||||
Изменение назначения SIM делает старую операцию неприменимой к новой карте;
|
||||
отложенная команда не должна следовать за номером слота на другую SIM.
|
||||
|
||||
## Первичные источники для первоначального наполнения
|
||||
|
||||
Параметры ниже — кандидаты для справочника; полный цикл на B2 для всех этих
|
||||
операторов не проверен. Это не перечень автоматически распознаваемых SIM.
|
||||
|
||||
| Оператор | Опубликованный APN | Учётные данные | Источник |
|
||||
| --- | --- | --- | --- |
|
||||
| МТС | `internet.mts.ru` | публичные `mts` / `mts` | [МТС, настройки интернета](https://support.mts.ru/mts_mobilnyy_internet/nastroiki-mobilnogo-interneta/kak-nastroit-internet-na-telefone) |
|
||||
| МегаФон | `internet` | действующий пресет: публичные `gdata` / `gdata` | Существующая квалификация и источник в `connectivity.py`; не переопределять по данным других операторов |
|
||||
| билайн | `internet.beeline.ru` | публичные `beeline` / `beeline`, PAP | [билайн, ручные настройки](https://moskva.beeline.ru/customers/support/mobile/mobilniy-internet/nastrojki/nastrojka-telefona/) |
|
||||
| t2 | `internet` | пустые | [t2, Android](https://msk.t2.ru/help/article/android-setup) |
|
||||
| Т-Мобайл | `tt` | без авторизации по инструкции активации | [Т-Мобайл, активация SIM](https://www.tbank.ru/mobile-operator/help/communication/sim-card/start-using/activate-sim/) |
|
||||
| Yota | `internet.yota` | пустые | [Yota, проверка интернета](https://www.yota.ru/support/mobile/ne-rabotaet-internet-apn) |
|
||||
|
||||
В официальных материалах также встречаются `internet.t2.ru` для
|
||||
[Windows Phone](https://msk.t2.ru/help/article/winphone-setup) и `m.tinkoff` на
|
||||
[странице eSIM](https://www.tbank.ru/mobile-operator/sim/esim/). Эти различия
|
||||
нужно сохранить как различия источников/применимости, не объявлять универсальными
|
||||
резервами для любого тарифа. Приоритет — конкретная актуальная инструкция,
|
||||
затем подтверждение реальным подключением. Отдельного испытания с этими SIM
|
||||
в текущем оборудовании не было.
|
||||
|
||||
## Кто выполняет подбор
|
||||
|
||||
| Размещение исполнителя | Что возможно | Граница |
|
||||
| --- | --- | --- |
|
||||
| Прошивка B2 | Автономно восстановить интернет при питании от адаптера | Сначала подтвердить нативную функцию и её точные параметры; загрузка нашего справочника/исполнителя штатным API не установлена |
|
||||
| Локальный компьютер, USB с данными | Хранить каталог офлайн, читать устройство, применять и проверять кандидатов без мобильного интернета | Нужны достаточные данные о SIM и квалификация полного цикла; Mac-адаптер ещё не означает поддержку Node/Linux |
|
||||
| Только VPS | Настраивать доступный B2 и выдавать актуальную базу клиентам | Если единственный канал B2 уже не работает, этот же канал не доставит исправление |
|
||||
| Независимый SMS-канал | Возможный отдельный способ начальной настройки/восстановления | Требует работающих SMS, адресации SIM и отдельного исполнителя; инфраструктура не реализована и не квалифицирована |
|
||||
|
||||
USB в блок питания не создаёт исполнителя или канал данных к нашему ПО.
|
||||
Для основного сценария самостоятельного B2 нельзя скрыто вводить обязательный
|
||||
бортовой компьютер. Если нативного режима нет, это реальная граница выбранного
|
||||
железа: необходим независимый канал настройки или изменение прошивки/оборудования.
|
||||
|
||||
Коммуникационная архитектура сохраняется: Core обращается к VPS и опрашивает
|
||||
его; VPS не подключается входящим соединением к Core. B2 сам открывает свой TCP.
|
||||
Каталог кэшируется на локальном исполнителе до исчезновения мобильной связи.
|
||||
|
||||
## Предлагаемый алгоритм
|
||||
|
||||
1. Получить свежие сведения о карте, слоте, регистрации и доступном канале
|
||||
управления. Не считать отсутствие свежей телеметрии доказательством замены SIM.
|
||||
2. Если доказательств недостаточно, показать неопределённость. Код базовой сети
|
||||
может сузить кандидатов, но не даёт права уверенно назвать MVNO или тариф.
|
||||
3. Для подтверждённой той же карты сначала использовать ранее проверенный
|
||||
вариант. Затем — применимые записи из кэша каталога. Не перебирать всех
|
||||
операторов подряд; корпоративные параметры не угадывать.
|
||||
4. До записи сохранить исходную конфигурацию, намерение, редакцию каталога,
|
||||
сведения о карте и стадии попытки. По устройству работает один исполнитель.
|
||||
5. Применить только необходимые поля и проверить чтением. Число попыток и
|
||||
таймеры ограничены; конкретные значения определяются аппаратными испытаниями.
|
||||
6. Проверить свежую связь именно этого B2 с нашим VPS. Запись APN, регистрация
|
||||
в сети или индикатор GPRS сами по себе не означают успех. Нет регистрации
|
||||
в сети — сначала диагностика сети, а не циклическая смена APN.
|
||||
7. После разрыва/перезапуска прочитать состояние и продолжить журнал. Если
|
||||
запись могла состояться, сначала сверка факта, затем решение о повторе.
|
||||
8. При неуспехе сохранить причину и восстановить прежнюю конфигурацию через
|
||||
доступный независимый канал. Не обещать удалённый откат по исчезнувшей связи.
|
||||
|
||||
Кэш успешных настроек переносится вместе с доказанно той же картой, а не с
|
||||
номером слота. Нельзя строить глобальную идентичность SIM из усечённого SID.
|
||||
|
||||
Наблюдения идентичности должны различать сырой ответ модема CCID, SID прошивки,
|
||||
IMSI, домашний код сети и обслуживающую сеть, а также слот, сеанс запуска,
|
||||
источник и время. Не подменять один источник другим и не нормализовать `ff`
|
||||
без квалифицированного правила. При двух SIM короткий ответ `I 7` не должен
|
||||
затирать полный исходный снимок или подтверждать, что SIM после перестановки
|
||||
осталась той же. Для разрешения записи нужны согласованные свежие доказательства.
|
||||
|
||||
## Порядок реализации и приёмки
|
||||
|
||||
Сначала закрыть возможность исполнения и идентификации: нативный режим B2
|
||||
либо доступная до интернета локальная диагностика. Затем реализовать редактор
|
||||
и версии справочника, после — автомат состояния и интеграцию с журналом команд.
|
||||
Не выдавать расширение списка ручных пресетов за завершённый автоподбор.
|
||||
|
||||
Аппаратная приёмка: одна известная SIM в обоих слотах, замена на другого
|
||||
оператора, неизвестный/неполный идентификатор, отказ регистрации, неверный APN,
|
||||
разрыв после записи, перезапуск во время попытки, обновление каталога при
|
||||
ожидающей команде и восстановление без связи с VPS. Проверять сохранность
|
||||
другой SIM, адресов серверов, устройства/ровера и существующих намерений.
|
||||
Других SIM и массового парка сейчас нет; их физическую приёмку не заявлять.
|
||||
@@ -0,0 +1,937 @@
|
||||
# B2 autonomy and command delivery
|
||||
|
||||
[Подтверждения B2 и граница рантайма, Host 0.1.31](TRACKER_CONFIRMATIONS_20260927.md)
|
||||
|
||||
Owner scope, 2026-09-26: telemetry, complete configuration, device admission and
|
||||
commands must operate through the owner's VPS, without an ARNavi/Gelios account.
|
||||
USB is a bootstrap/recovery transport. This includes independently assigned
|
||||
trackers, several per apparatus, reusable non-identifying profiles and a
|
||||
reproducible VPS installer. Relay latency is additional scope, not a substitute
|
||||
for full configuration.
|
||||
|
||||
Current qualification, 2026-09-27: telemetry and selected commands work through
|
||||
the owned VPS, but repeated remote configuration is **not yet reliable**. The
|
||||
two-SIM regression below verified one write, then failed the network restoration;
|
||||
USB restored and independently verified the exact baseline. Earlier successful
|
||||
roundtrips remain bounded evidence, not general reliability acceptance.
|
||||
|
||||
The [2026-09-27 coverage and recovery audit](CONFIGURATION_COVERAGE_20260927.md)
|
||||
adds an offline, value-redacted coverage checker and fixes bootstrap admission
|
||||
for the shipped VPS 0.1.26. It confirms 78 editable scalars in the 207-record
|
||||
physical image. Its new write succeeded; power cycling did not resolve the
|
||||
failed network restoration. USB subsequently restored the exact baseline,
|
||||
including field 25 = 15, with independent readback. The
|
||||
[Host 0.1.27 readiness qualification](OUTBOUND_READINESS_20260927.md) adds guarded
|
||||
session admission, but does not establish full configuration reliability.
|
||||
|
||||
The [Host 0.1.29 clock/freshness follow-up](CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md)
|
||||
qualifies our own opcode-7 time response and fresh-stream configuration admission.
|
||||
A subsequent physical write applied, but post-write network verification failed;
|
||||
USB restored the exact baseline again. Full remote reliability remains open.
|
||||
|
||||
The [Host 0.1.30 recovery qualification](RUNTIME_RECOVERY_20260927.md) preserves
|
||||
verification of an already committed full-image write through VPS process
|
||||
restart and a new B2 connection. Only readback resumes; effects do not replay.
|
||||
Linux SIGKILL/loopback qualification passed. Physical modem recovery and
|
||||
continuous USB-only power remain separate, unaccepted gates.
|
||||
|
||||
## Two independent device channels
|
||||
|
||||
The qualified B2 231 / 0.01 has four monitoring slots and a separate configuration
|
||||
service. Moving monitoring slots alone does not remove the manufacturer's
|
||||
configuration dependency.
|
||||
|
||||
- Monitoring: INTERNAL over TCP. The owner's receiver can send an asynchronous
|
||||
command while the TCP session is open; it need not wait for the next GNSS point.
|
||||
- Configuration service: ordered binary settings fields 70 (host) and 71 (port),
|
||||
interval 62 and startup bit in 72. A real redirected request used HTTP
|
||||
`POST /c/index.php`, a binary body, and a keep-alive connection. It is not the
|
||||
TLS management API used between Core and VPS.
|
||||
- Device envelope: `5b 01 LEN:u16be IMEI:u64le 00 01 e7 02 00 00 OP PAYLOAD 5d`.
|
||||
LEN is the body length minus five. Metadata is admitted only for model 231,
|
||||
firmware 0.01. OP 6 identifies the exchange, OP 5 uploads the full image,
|
||||
OP 2 requests a new image.
|
||||
- Server envelope: `5b LEN:u16be 00 OP PAYLOAD 5d`, LEN = body length minus four.
|
||||
Captured OP 6 answer is `5b00030006025d`; captured upload acknowledgment is
|
||||
`5b00030005015d`. The earlier inferred six-byte upload ACK was rejected by
|
||||
the bench and is not used. OP 2 carries the complete CRC-checked configuration.
|
||||
|
||||
Reference framing was captured in three explicitly owner-authorized diagnostic
|
||||
requests. The last returned the manufacturer's own previously downloaded copy
|
||||
byte-for-byte; current owner-VPS settings were not uploaded to the manufacturer.
|
||||
Those reference requests are engineering evidence, not a runtime dependency.
|
||||
The release has no vendor client, proxy, login or vendor API call.
|
||||
|
||||
Initial USB provisioning sets the selected owner VPS in primary monitoring slot
|
||||
1, recovery slot 2 and configuration fields 70/71 in one backed-up whole-image
|
||||
transaction. Core admits the device to that paired, assigned VPS first. Firmware,
|
||||
instance credentials, SIM identity, periodic interval and unknown fields remain intact.
|
||||
The accepted 0.1.23 bootstrap clears only the startup-check bit, as qualified below.
|
||||
Existing optional monitoring slots 3/4 are preserved and must be reviewed when
|
||||
migrating a device that already uses them; the qualified bench has both disabled.
|
||||
The component operations are physically qualified; the newly composed bootstrap
|
||||
is covered by synthetic transaction tests, not a factory-fresh physical-device run.
|
||||
|
||||
A separate authenticated engineering observation lease remains bounded to 180 s,
|
||||
four 16-KiB captures and 64 retained leases. It is disabled during normal product
|
||||
operations and does not expose raw traffic to the browser. No transparent proxy
|
||||
or guessed response is needed by the production settings path.
|
||||
|
||||
## Command contract
|
||||
|
||||
The manufacturer INTERNAL specification documents an asynchronous binary frame,
|
||||
`FF token:u32le command`, with response packet type 09 (code + token). The B2
|
||||
manual §10 identifies physical outputs as PIN4..PIN6. Older generic INTERNAL
|
||||
examples use other output indexes and must not override the B2 mapping.
|
||||
|
||||
VPS 0.1.8 adds a narrow, authenticated API allowlist:
|
||||
|
||||
| Operation | Documented wire definition | Behavior |
|
||||
| --- | --- | --- |
|
||||
| Request position | `01 01` | Ask for an immediate telemetry packet |
|
||||
| Pulse output | `18 PIN 00 seconds` | PIN4..6, 1..5 seconds; no persistent latch |
|
||||
| Read settings | Password + `*GETP` in FC | Existing read-only evidence path |
|
||||
| Change server 1 | Documented SETP #1, GETP before/after | Existing endpoint-only transaction |
|
||||
|
||||
Binary actions require a currently connected admitted device, expire for dispatch
|
||||
after three seconds, and can be sent only on a session that existed when queued.
|
||||
They never wait indefinitely for an offline tracker. Dispatch is committed before
|
||||
writing the socket. A dispatched action is never replayed; a queued action expires
|
||||
on service restart. A lost reply is not evidence that the physical action failed.
|
||||
The response deadline is thirty seconds. Only a matching token on the selected
|
||||
session is accepted. Code 6 means accepted for later execution, not completion;
|
||||
code 0 is device confirmation, not independent proof of relay contact state.
|
||||
|
||||
The API immediately wakes the sender after durable submission; a one-second
|
||||
maintenance timer remains for settings stages. Packet acknowledgement, command
|
||||
confirmation and observed output state are separate evidence. GNSS fix is not a
|
||||
prerequisite for communicating with an online modem.
|
||||
|
||||
## Physical interfaces and limits of inference
|
||||
|
||||
Primary source: [B2 manufacturer manual](https://8888.arusnavi.ru/Arnavi%20B2/).
|
||||
The 16-pin connector exposes power, configurable inputs/outputs, RS232, RS485,
|
||||
1-WIRE and CAN. CAN2 shares pins with RS485; these are not independent simultaneous
|
||||
resources. The manual describes three low-side outputs, with mode 1 for command
|
||||
control, mode 22 for speed/belt/light control and mode 23 for speed-bounded blocking.
|
||||
A CAN connection and a program number do not establish permission or capability to
|
||||
command arbitrary vehicle brakes. Device telemetry about an output is not proof
|
||||
that an external relay/contact/controller actually changed state.
|
||||
|
||||
The owner explicitly confirmed that the two relay boards are disconnected from
|
||||
the former engine/speed-sensor/limiter circuits and can be checked with LEDs.
|
||||
Bench qualification must record each physical PIN, wire command, receipt, device
|
||||
state and observed LED/contact response; no live vehicle actuation is implied.
|
||||
|
||||
### Bench observation, 2026-09-26
|
||||
|
||||
The owner observed no LED transition for a two-second PIN4 binary pulse and a
|
||||
five-second PIN5 binary pulse. One board LED stayed on and the other stayed off.
|
||||
Both commands produced code-0 token replies (1.818 s and 5.933 s roundtrip), which
|
||||
therefore do not prove physical switching. Telemetry before/after reported an
|
||||
external supply near 12.48 V and discrete mask 0x0041; roughly 15-second sampling
|
||||
did not cover the pulse interval. The photographs do not establish the boards'
|
||||
identity, wire-to-PIN mapping, or meaning of each LED.
|
||||
|
||||
VPS 0.1.9 permits an explicit FC text encoding of the same bounded pulse, following
|
||||
manual §10 (`password*SERV*24.PIN.0.seconds`). PIN and duration limits, current
|
||||
session requirement, dispatch expiry and no-replay rules remain unchanged. Only
|
||||
this generated text is accepted; credentials never appear in public receipts.
|
||||
There is no token-confirmation mechanism for FC: unrelated replies cannot turn
|
||||
it into success. Text delivery remains unconfirmed pending independent evidence.
|
||||
The text comparison on the same PIN5 subsequently produced an operator-observed
|
||||
transition: the previously unlit board LED turned on and then off. The requested
|
||||
duration was five seconds; physical latency/duration were not measured. This
|
||||
qualifies that one visible board response on model 231 / firmware 0.01, not both
|
||||
boards, electrical contacts, generic binary control, or arbitrary firmware.
|
||||
Telemetry still did not sample the pulse interval. A seven-byte text response
|
||||
arrived, but its interpretation/correlation is not yet qualified, so the API
|
||||
correctly retained `unconfirmed`. The confirmed physical observation is separate
|
||||
operator evidence; do not silently promote uncorrelated protocol receipts.
|
||||
|
||||
## Camera qualification of the disconnected bench, 2026-09-26
|
||||
|
||||
The owner authorized repeated camera-observed tests. MacBook FaceTime video
|
||||
established the spatial mapping: the upper board LED is controlled by PIN5;
|
||||
the lower board LED remained lit. No vehicle mechanisms were connected.
|
||||
|
||||
- The FC text PIN5 five-second pulse lit the upper LED for 5.0 seconds at
|
||||
10-frame/s analysis resolution (video positions 19.7–24.7 seconds).
|
||||
- VPS 0.1.10 adds allowlisted `set-output`, manual section 10
|
||||
`password*SERV*8.PIN.STATE`, PIN4..6 and strict boolean `enabled`. This is an
|
||||
explicit persistent state, not a pulse. It keeps active-session binding,
|
||||
three-second dispatch expiry, no replay and private password handling.
|
||||
- Explicit PIN5 on and off both changed the upper LED, confirmed on video.
|
||||
PIN4 and PIN6 on/off changed their corresponding TAG6 bits but produced no
|
||||
visible transition on either board. In the recorded sequence, masks changed
|
||||
0x0001 → 0x0041 (PIN6) → 0x0051 (PIN4) → 0x0071 (PIN5). The reverse commands
|
||||
restored 0x0001. The upper LED was off and the lower LED still on at handoff.
|
||||
- A `SERV OK` text reply and output-bit change are useful separate evidence;
|
||||
the generic command receipt still does not invent token correlation or
|
||||
physical confirmation. The lower board may have a power indicator or a
|
||||
different wiring path; neither interpretation is established. Close inspection
|
||||
of its wiring/labels or an electrical measurement is needed before more tests.
|
||||
- Video timestamps are relative; file creation UTC is rounded and was not
|
||||
independently synchronized with server dispatch. No precise millisecond
|
||||
latency or relay contact behavior is claimed.
|
||||
|
||||
Both private videos, sampled LED counts, command manifests and redacted
|
||||
telemetry have recorded SHA-256 evidence outside Git. Firmware and configuration
|
||||
fields were unchanged during this bench run. The new VPS artifact passed 50
|
||||
focused VPS tests, was reproduced twice, installed through the shipped installer,
|
||||
and published in the Core installer catalog. At that release full configuration
|
||||
was still pending; the later acceptance is recorded below.
|
||||
|
||||
## Remaining autonomy acceptance
|
||||
|
||||
### Mission Core command surface accepted, 2026-09-26
|
||||
|
||||
The existing B2 settings window now contains a Commands section: request position,
|
||||
explicit output on/off and a five-second pulse. This is domain content in the
|
||||
existing FeatureSettingsWindow composition (novelty A), using canonical Select,
|
||||
SettingsCard, StatusBadge, Button and WindowFooterActions. A separate workspace
|
||||
was rejected: these occasional actions belong to one already enrolled device,
|
||||
with its identity, assignment and operation lock. No new product root is added.
|
||||
|
||||
Only the qualified firmware/host combinations are admitted. Existing enrollment
|
||||
snapshots provide output modes without reconnecting USB, without altering the
|
||||
snapshot date or implying a fresh configuration read. Commands are separate from
|
||||
desired policy and profile application. Pending, disconnected, incompatible and
|
||||
unsaved-change states explain why actions are unavailable. Lost requests keep the
|
||||
durable operation ID; output commands never repeat automatically.
|
||||
|
||||
TAG6 mode 1 provides PIN4..6 logical states independently of GNSS. The Core decoder
|
||||
handles repeated TAG6 instances (analog/frequency tags cannot hide discrete
|
||||
states), stores observations transactionally with the pull cursor, rejects older
|
||||
state overwrite and hides state outside the currently assigned host contour.
|
||||
The UI labels stale observations, keeps output feedback separate from command
|
||||
receipts and never animates a successful output change optimistically.
|
||||
|
||||
Acceptance on the real enrolled B2 used the UI's Request position button through
|
||||
VPS 0.1.10, with USB physically unplugged as confirmed by the owner. The VPS queue
|
||||
was 0.004319 seconds; matching device code 0 arrived 1.838826 seconds after socket
|
||||
dispatch. These are VPS-local measurements, not physical actuation latency or a
|
||||
cross-machine end-to-end benchmark. No output command was sent in this UI run.
|
||||
All outputs remained logically inactive. The accepted endpoint remains visible
|
||||
after subsequent commands, even when the last command replaces the operation card.
|
||||
|
||||
Validation: architecture checks, full TypeScript checking, 990 frontend tests and
|
||||
production build; focused backend checks cover strict inputs, output mode gates,
|
||||
version/offline rejection, no replay, secret projection, late/out-of-order packets,
|
||||
transaction rollback, assignment scope and legacy enrollment projection. Browser
|
||||
QA checked real feedback, disabled actions while pending/dirty, dropdown, Escape
|
||||
and right-aligned footer actions. Private evidence is retained outside Git.
|
||||
|
||||
### Whole-configuration path, 2026-09-26
|
||||
|
||||
VPS 0.1.15/0.1.16 adds `read-configuration` and `configure-all` through the paired
|
||||
TLS API. The tracker receives documented `password*SERV*1.9` (upload) and
|
||||
`password*SERV*1.8` (download) through INTERNAL. The HTTP channel checks admitted
|
||||
IMEI, model/firmware framing, CRC, size limits and the active modem peer. This is
|
||||
legacy device identity plus network correlation, not cryptographic device
|
||||
attestation; a modem using different CGNAT egress for the two sockets is not yet
|
||||
qualified. Core-to-VPS authentication and certificate pinning remain separate.
|
||||
|
||||
Before a write, the VPS obtains the complete current image and compares its hash
|
||||
with Core's predecessor. Critical password/recovery/configuration-service fields
|
||||
cannot change in this operation. Core overlays only reviewed portable settings;
|
||||
record order, missing fields, unknown settings and unique values are preserved.
|
||||
Only one image reply is sent. A new upload independently verifies the exact image;
|
||||
SERV OK, TCP acknowledgment and a successful API request are never write success.
|
||||
Restart or timeout after dispatch produces an explicit uncertain/unconfirmed
|
||||
outcome and never silently resends the write. Core privately retains the image
|
||||
and identity-source provenance, and does not pretend SIM identity was refreshed
|
||||
by a settings upload. The browser receives summaries, not configuration bytes.
|
||||
|
||||
Physical bench evidence with USB unplugged:
|
||||
- Full read returned 207 records / 983 bytes, byte-identical to the USB baseline.
|
||||
- A change to field 25, stationary interval 15 -> 16 seconds, was verified by a
|
||||
separate full read. The other 206 records remained byte-identical.
|
||||
- Return to 15 seconds restored the exact original full image. The same behavior
|
||||
was exercised through the canonical Core API, not only an engineering helper.
|
||||
- On 0.1.15 one preflight timed out without an image write; a later write succeeded
|
||||
in about 29 s. A subsequent download request was TCP-acknowledged but produced
|
||||
no download, so restoration was not falsely marked successful.
|
||||
- 0.1.16 adds 15 s between settings stages/adjacent settings operations. The
|
||||
original image was restored through Core in about 51 s. This pacing applies
|
||||
only to full settings, not position/output actions. These are individual bench
|
||||
timings, not a latency guarantee or evidence of thousand-device capacity.
|
||||
- The final 0.1.16 UI Save settings action repeated 15 -> 16 -> 15 with
|
||||
independent verification in both directions and an exact restored image. The
|
||||
downloadable installer bytes match the qualified installed artifact.
|
||||
- Final 0.1.16 UI Request position regression: queue 0.003744 s, matching
|
||||
device confirmation 1.662265 s after socket dispatch. This is protocol
|
||||
confirmation, not physical relay latency.
|
||||
- Browser acceptance also showed the current B2 GNSS marker in the expanded
|
||||
Rover observation map with the onboard Node offline; 12 satellites reported.
|
||||
- Live position, logical output feedback and both own monitoring endpoints stayed
|
||||
available. Firmware was not updated and no output actuation was needed.
|
||||
|
||||
The same deterministic single-file installer is used for qualification and
|
||||
operator download. The profile editor applies over the network and retains
|
||||
separate saved/confirmed states; no USB is required for this enrolled device.
|
||||
The portable catalog intentionally covers reviewed settings, not every raw field
|
||||
or every accessory shown in the manufacturer's configurator.
|
||||
|
||||
### Remaining scope and limits
|
||||
|
||||
1. Factory-fresh physical bootstrap and power-cycle persistence, including SIM
|
||||
provisioning and devices with existing optional monitoring destinations.
|
||||
2. Controlled migration of the recovery/configuration endpoint to another VPS;
|
||||
changing server 1 alone deliberately retains the old recovery channel.
|
||||
3. Mapping and device qualification of remaining configuration fields and
|
||||
peripheral protocols (CAN/RS485/RS232/1-WIRE/BLE), remote firmware lifecycle
|
||||
and protected credential rotation. Full-image transport is not proof of all
|
||||
these device capabilities.
|
||||
4. Batch enrollment, restart/offline recovery and capacity qualification on a
|
||||
suitable worker before claiming a thousand-device deployment.
|
||||
5. Physical relay/contact latency and local speed-limiter behavior remain
|
||||
separate work; the owner stopped the miswired LED investigation.
|
||||
|
||||
A geofence control policy must also define position freshness, out-of-order packet
|
||||
handling, boundary hysteresis, loss of connectivity, command expiry, priority,
|
||||
operator cancellation and the actual limiter interface. A cellular roundtrip has
|
||||
no hard deadline. Do not implement immediate braking by blindly replaying a stale
|
||||
"inside zone" command after reconnect. Local enforcement is an independent device
|
||||
capability to qualify, not an assumption from a server polygon.
|
||||
|
||||
### Remote restart and return observation, 2026-09-26
|
||||
|
||||
VPS 0.1.17 adds a bounded `restart` command for model 231 / firmware 0.01,
|
||||
using the B2 manual §10 binary `01 07` under the existing token envelope.
|
||||
The request has the same three-second dispatch deadline and durable no-replay
|
||||
rule as other actions. Its return-observation window is 180 seconds. A token
|
||||
code 0 or 6 is recorded as acceptance and does not complete the operation.
|
||||
|
||||
Return is observed only after a new TCP session starts after dispatch and sends
|
||||
valid type-1 telemetry measured after dispatch (at most five seconds ahead of
|
||||
server time). Both pre-existing monitoring sessions, new headers alone, old
|
||||
archive points, text replies and unrelated token responses are insufficient.
|
||||
The final state is `reconnected`, deliberately not a claim of CPU restart or
|
||||
hardware power-cycle proof. Timeout reports unconfirmed return; VPS restart
|
||||
reports an uncertain result; neither resends the command.
|
||||
|
||||
The existing Commands page uses canonical SettingsCard/Button components and
|
||||
separates request acknowledgment timing from time to fresh data on reconnection.
|
||||
Core requires the matching VPS release and preserves the saved profile state.
|
||||
Synthetic checks cover old/secondary sessions, stale and future timestamps,
|
||||
unregistered sessions, text-only replies, expiry, service restart, idempotency,
|
||||
private wire projection and Core/HTTP/frontend state semantics.
|
||||
|
||||
|
||||
Initial restart qualification (before the startup-check correction below):
|
||||
- A UI-issued restart on 0.1.17 returned fresh telemetry on a new connection
|
||||
after 53.225900 seconds. No USB, firmware update or output actuation was used.
|
||||
- The pre-restart configuration was 207 records / 983 bytes. Two subsequent
|
||||
full reads timed out while telemetry continued. No settings image was sent,
|
||||
and persistence must not be claimed from the retained Core cache.
|
||||
- Bounded captures showed settings-upload commands acknowledged with SERV OK,
|
||||
but the HTTP channel issued empty command-2 requests instead of an upload.
|
||||
The documented binary 0109 produced the same behavior as SERV 1.9.
|
||||
- A one-shot empty command-2 response (0.1.19 engineering lease) advanced the
|
||||
device to an empty command-1 request. A one-shot empty command-1 response
|
||||
(0.1.20 engineering lease) did not complete the exchange: command 1 repeated.
|
||||
The empty reply did not establish its meaning. Neither response contains a settings or
|
||||
firmware image. These hypotheses are not admitted in the product handler.
|
||||
- Each experiment retains timestamps, private capture bytes and SHA-256 hashes;
|
||||
the observation leases were explicitly closed. Position reception remained
|
||||
available. Completion requires a fresh device upload after restart, not a
|
||||
restore/write of the old image followed by reading it back.
|
||||
|
||||
- While this configuration exchange was unresolved, a product-UI position
|
||||
request on 0.1.20 was token-confirmed after 1.314065 seconds (queue 0.005 s).
|
||||
The separate monitoring command channel stayed functional. Core compatibility
|
||||
and the production UI build were updated and the canonical 8000 service was
|
||||
health-checked. The 0.1.20 artifact remains an engineering qualification
|
||||
release; the operator download at that point remained 0.1.16.
|
||||
- Automatic approval review initially rejected a reference command-1 request.
|
||||
After the owner's separate scoped authorization, exactly one 20-byte
|
||||
identity/version request ran. It contained no configuration or passwords.
|
||||
The saved response was not automatically forwarded to the device.
|
||||
|
||||
### Startup-check correction and accepted Host 0.1.23
|
||||
|
||||
The ten-byte reference reply contains the existing four-byte numeric device ID,
|
||||
independently observed during USB enrollment. Host admission now carries that
|
||||
known ID. The host never derives it from the IMEI, generates a replacement ID,
|
||||
or asks the manufacturer for it. Numeric ID association is immutable per IMEI;
|
||||
a conflicting admission fails atomically. Old Core callers that omit the ID do
|
||||
not erase an established mapping. Removal from admission also removes reply
|
||||
authority, while retaining identity history for later re-enrollment.
|
||||
|
||||
A one-shot numeric-ID reply advanced the device from command 1 to command 2.
|
||||
However, empty command-2 responses produced a repeated 1/2 exchange rather than
|
||||
completion. The 0.1.22 combined experiment was rejected. Host 0.1.23 retains only
|
||||
the independently known numeric-ID reply. It serves a settings image only for
|
||||
an explicit bounded write; it does not rewrite a cached image on startup.
|
||||
No runtime manufacturer calls exist.
|
||||
|
||||
A bounded capture of the first request after another restart showed an empty
|
||||
settings-download request (command 2). Fresh telemetry returned after 123.9333 s.
|
||||
The next experiment explicitly wrote the backed-up full configuration with
|
||||
**only field 72 bit 0 cleared**, the manufacturer's “check at every start” flag.
|
||||
All other bits and all other 206 records were retained, including field 62's
|
||||
value 150 (the public schema labels this interval in hours; physical units have
|
||||
not been calibrated). Its zero-value semantics were not qualified and were not
|
||||
changed. This recovery write is separate from reading; it does not prove that
|
||||
the pre-recovery original image survived the preceding restart unchanged.
|
||||
|
||||
Physical acceptance, USB unplugged, model 231 / firmware 0.01:
|
||||
|
||||
- A separate product read after the flag change returned all 207 records /
|
||||
983 bytes, exactly matching the target image.
|
||||
- One new restart returned fresh telemetry on a new connection after
|
||||
**71.176131 s**. An independent full read after that restart again matched
|
||||
the target byte for byte. No configuration was written during this restart
|
||||
qualification and no output was actuated.
|
||||
- The canonical Mission Core UI then read the same 207 records through VPS;
|
||||
its newly persisted evidence also matched the target byte for byte.
|
||||
- A UI-issued coordinate request was token-confirmed **1.456098 s** after
|
||||
socket dispatch. This measures protocol confirmation, not relay switching
|
||||
or a guaranteed cellular deadline.
|
||||
- A final UI Save settings roundtrip changed field 25 from 15 to 16 seconds,
|
||||
then back to 15. Both operations were independently verified from all 207
|
||||
records, in 41.410 s and 41.379 s including the deliberate
|
||||
settings-channel pacing. All other 206 records stayed unchanged, and the
|
||||
final image exactly matched the accepted post-restart target. Startup checks
|
||||
stayed disabled throughout; settings writes did not re-enable them.
|
||||
- Initial USB bootstrap now sets both monitoring destinations and the
|
||||
configuration endpoint to the selected owned VPS, and clears only the
|
||||
startup-check bit. Missing/malformed flags reject before any USB write.
|
||||
Portable profile saves and ordinary remote writes preserve these flags.
|
||||
Physical factory-fresh USB bootstrap remains a separate acceptance case.
|
||||
|
||||
The accepted installer is immutable Host **0.1.23**, SHA-256
|
||||
`97abb7a869f86debe885e5130dd14791ac7ed0dfea99f9ee75c64bfb229559d0`.
|
||||
It was reproduced from the source with the same tar, installer and manifest
|
||||
hashes as the installed release, then published in Mission Core. Node was not
|
||||
updated. Release README entries are the historical qualification state at build;
|
||||
this section records subsequent bench acceptance without replacing the artifact.
|
||||
|
||||
Private evidence sessions (outside source control):
|
||||
`startup-pull-disable-ef4f81c06bb549a59d3bf61fe1738884` and
|
||||
`startup-disabled-restart-d4508839ef4f487ba22301f7f90ce456` retain before/target,
|
||||
readbacks, operation receipts, UTC/monotonic times and hashes. The original
|
||||
restart and failed startup exchanges remain retained, not overwritten.
|
||||
|
||||
Remaining startup scope: periodic background checks and a safe no-update reply
|
||||
have not been qualified. The full original image was deliberately changed by
|
||||
one flag, so this result must not be presented as unchanged-original persistence
|
||||
or complete device lifecycle autonomy. Factory reset, physical power cycling,
|
||||
remote firmware, credentials and peripheral protocols remain separate gates.
|
||||
|
||||
### Background-check parameter: negative qualification, 2026-09-27 operator time
|
||||
|
||||
Exactly one newly owner-approved command-6 reference request returned the same
|
||||
seven-byte body as the original reference. No configuration or password was
|
||||
included, no response was automatically forwarded, and this consumed the scoped
|
||||
authorization. It does not establish a neutral/no-update response. The owned
|
||||
runtime remained Host 0.1.23 throughout the following tests.
|
||||
|
||||
The public type-231 schema exposes field 62 as a two-byte integer with range
|
||||
0..65535. Three individually backed-up network experiments tried values **1,
|
||||
151 and 0**, from the same freshly read value 150. The complete CRC-valid target
|
||||
image was observed leaving the VPS in each case. Each independent command-5
|
||||
readback returned the exact original 207-record image, including field 62 = 150.
|
||||
The product reported `not_applied`, not success. No accelerated periodic-check
|
||||
window started because no candidate interval was actually retained.
|
||||
|
||||
A positive control changed field 25 from 15 to 16 and back to 15 using the same
|
||||
full-image API, peer admission, write/readback sequence and live firmware. Both
|
||||
directions were verified. This narrows the failure to the tested period changes;
|
||||
it is not evidence that all field-62 values are unsupported, that zero disables
|
||||
anything, or that the actual timer uses the units in the current public schema.
|
||||
The exact firmware restriction and whether USB behaves differently remain open.
|
||||
Do not add field 62 to portable profiles or clear it in bootstrap on this evidence.
|
||||
|
||||
Final canonical Core read returned all 207 records, byte-identical to the accepted
|
||||
startup-disabled baseline. A Core-issued position request was token-confirmed in
|
||||
**2.104986 s**, with **0.004595 s** VPS queue time. No output, firmware, Node or
|
||||
VPS-runtime change occurred. The five explicit configuration-image transmissions
|
||||
were the three period candidates and the positive control with restoration;
|
||||
none was an unsolicited background response.
|
||||
|
||||
Private evidence session `periodic-check-eb630dc8b6b04b1daf4ece0f597bed71` retains
|
||||
the baseline/candidates, separate preflight and verification receipts, UTC and
|
||||
monotonic timestamps, a bounded packet capture and redacted CRC-checked HTTP
|
||||
event table. Core read evidence is in `core-flow-c3dd8d4cad164ce594aae15e13ab032d`.
|
||||
The capture completed with no kernel drops and was stopped explicitly. New
|
||||
synthetic regressions ensure unchanged and partial readbacks cannot become
|
||||
successful writes or be replayed after a duplicate request or service restart.
|
||||
|
||||
Next discriminating experiment requires the owned B2 on USB: compare one fresh
|
||||
USB field-62 write/readback with the network behavior, preserve all other records,
|
||||
and restore the exact baseline. Until that or protocol evidence resolves the
|
||||
background path, complete lifecycle autonomy remains unqualified.
|
||||
|
||||
### USB comparison and repeated telemetry, 2026-09-27
|
||||
|
||||
After the operator reconnected the cable, macOS enumerated the qualified Artery
|
||||
CDC interface. The identity-bracketed USB read returned model 231 / firmware
|
||||
0.01 and the exact accepted 207-record, 983-byte baseline, SHA-256
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
|
||||
One backed-up USB transaction changed only field 62 from 150 to 1 in the
|
||||
transmitted image. The device returned `SR=1`, but the transaction's configuration
|
||||
readback and final identity check established `not_applied`: all original bytes
|
||||
remained. The immediate separate snapshot timed out during its final identity
|
||||
read and was retained as failed evidence. A subsequent complete independent
|
||||
snapshot succeeded and again matched the original image byte for byte. No
|
||||
restoration write was necessary. Thus this tested rejection also occurs through
|
||||
USB; it is not confined to the owned VPS transport. It does not establish the
|
||||
firmware's reason, the accepted range, timer units or zero-value semantics.
|
||||
|
||||
A separate 16-second passive capture on the owned receiver port established
|
||||
that the tracker still completed INTERNAL identification and sent two valid
|
||||
eight-packet packages, both numbered 39. Each payload exactly matched an earlier
|
||||
Core receipt. The VPS sent the corresponding package acknowledgments; the trace
|
||||
also contains acknowledgment retransmissions and reconnects. The Core's old
|
||||
telemetry timestamp therefore did not mean the tracker made no connections:
|
||||
these were duplicate stored payloads, not fresh measurements. One canonical
|
||||
Core position request was dispatched with 0.004706 s queue time and ended
|
||||
`unconfirmed` after approximately 35 s. No fresh position or successful command
|
||||
delivery is claimed. This capture alone does not locate the underlying fault
|
||||
among the cellular path, modem handling and device acknowledgment processing.
|
||||
|
||||
Later, additional packages advanced the Core receipt timestamp and temporarily
|
||||
made the device online. The latest inspected payloads still contained historical
|
||||
measurements. This new arrival justified one further position request, retained
|
||||
separately: it also ended `unconfirmed` after approximately 35 s (queue
|
||||
0.006464 s). Packet arrival is therefore not acceptance of fresh navigation or
|
||||
reliable bidirectional commands.
|
||||
|
||||
Private session `usb-period-compare-0a184b850292413c961163d4b141398d` retains
|
||||
the before/readback images, the one USB write receipt, the failed and successful
|
||||
independent reads, the position receipt and the bounded packet capture.
|
||||
Capture SHA-256:
|
||||
`9112cc11e8fb51bfcd22fc6fad66623b2b0944a4b5f3297a492a7aa57b0adc3f`.
|
||||
The capture stopped at its deadline with no kernel drops; no remote file was
|
||||
created. Settings ended unchanged, including the disabled startup check.
|
||||
No firmware, outputs, manufacturer requests, Node update or VPS runtime change
|
||||
occurred. USB communication is available; stable network exchange and the
|
||||
background-check lifecycle remain unresolved acceptance gates.
|
||||
|
||||
### Correlated modem capture and USB recovery restart, 2026-09-27
|
||||
|
||||
Simultaneous passive USB diagnostics and a 40-second receiver-port capture
|
||||
narrowed the stalled exchange. Three distinct nine-byte HEADER2 replies from
|
||||
the owned VPS appeared byte-for-byte in the modem's `RXGET` diagnostic stream.
|
||||
The corresponding four-byte acknowledgments for package 45 matched the public
|
||||
SERVER_COM format, but none appeared in that same diagnostic capture. The VPS
|
||||
retransmitted those four-byte TCP segments; a read-only `ss -tin` inspection
|
||||
also showed four unacknowledged bytes on established connections, nonzero
|
||||
receive windows and repeated retransmissions. This is stronger evidence than
|
||||
an application command timeout, but does not identify which network component
|
||||
or modem behavior caused the missing transport acknowledgment. In particular,
|
||||
absence from a diagnostic stream alone is not proof of modem non-reception.
|
||||
The server/Mac clock sample had approximately one second of roundtrip
|
||||
uncertainty; do not use these two capture clocks as a precise latency benchmark.
|
||||
|
||||
For a bounded recovery comparison, the official configurator was inspected
|
||||
statically again, without executing it. The `act_Reboot` registration at
|
||||
0x77af33..0x77af4f uses literal `>D 1\r\n` at 0x77b558 for the same model range
|
||||
5..249 as the already qualified SettingsGet action. The existing executable
|
||||
SHA-256 was verified against the USB bootstrap reference. Exactly one six-byte
|
||||
USB restart request was issued after a new identity-bracketed backup, exact
|
||||
baseline comparison and a check that startup configuration pulling remained off.
|
||||
No configuration, firmware or output command was sent.
|
||||
|
||||
The device returned with a new USB session and reset diagnostic uptime.
|
||||
Independent identity and full configuration reads matched the pre-restart
|
||||
snapshot exactly. This qualifies the observed USB software restart on model
|
||||
231 / firmware 0.01; it is not a power-cycle or factory-reset test. Network
|
||||
observation through approximately 193 seconds after dispatch did not produce
|
||||
a fresh position. A subsequent simultaneous capture retained modem connection
|
||||
attempts, while the 25-second VPS capture contained only four outgoing FIN/ACK
|
||||
segments from older connections: no new incoming handshake or application
|
||||
payload was observed in that window. No automatic restart retry ran.
|
||||
|
||||
Evidence sessions, outside source control:
|
||||
|
||||
- `link-correlation-73311b9599a24aa8aca14f592c01c85b`: passive before-restart
|
||||
USB/network captures and exact reply-byte correlation.
|
||||
- `usb-restart-recovery-94928ea71d7b4e6b8adb09614a37ec3b`: source qualification,
|
||||
backup, one-shot transmission receipt, new-session/configuration verification
|
||||
and bounded network-return observations.
|
||||
- `post-restart-link-correlation-1d895d107a5c4e508f4bc04c0aaa1f10`: passive
|
||||
post-restart modem and TCP observations.
|
||||
|
||||
Both packet captures stopped at their deadlines with zero kernel drops. Host
|
||||
0.1.23, Mission Core and the device configuration were retained; no vendor query,
|
||||
Node update or VPS runtime change occurred. The next independent control is the
|
||||
current SIM's mobile-data operation or a known-working alternative SIM. Carrier
|
||||
failure, device firmware failure and complete lifecycle autonomy are not yet
|
||||
established by this evidence.
|
||||
|
||||
### Two installed SIMs and recovered exchange, 2026-09-27
|
||||
|
||||
The owner retained the personal MTS SIM, inserted a different MegaFon SIM and
|
||||
reported disconnecting/reconnecting external power. A fresh identity-bracketed
|
||||
USB read recognized both reported SIM identifiers; slot 1 changed and slot 2
|
||||
matched the prior observation. Full configuration remained exactly the accepted
|
||||
207-record, 983-byte baseline. APNs were `internet` and `internet.mts.ru`; neither
|
||||
SIM's GPRS-disable flag was set. No settings were written. Reported identifiers
|
||||
remain device observations, not full independently verified ICCIDs.
|
||||
|
||||
Diagnostic uptime advanced through 722–807 seconds, consistent with the earlier
|
||||
qualified software restart. Therefore this external-power interruption is not
|
||||
accepted as a full restart or power-cycle persistence test; USB remained attached.
|
||||
The B2 manual documents two SIM holders and two-operator support, but does not
|
||||
specify simultaneous independent data sessions or an automatic watchdog policy.
|
||||
This test does not qualify either behavior.
|
||||
|
||||
A new 40-second VPS capture and simultaneous 45-second passive USB capture
|
||||
recorded 67 valid incoming packages. All 68 captured four-byte outgoing package
|
||||
acknowledgments had exact byte matches in the USB diagnostic stream, as did the
|
||||
one captured HEADER2 acknowledgment. Historical package numbers advanced instead
|
||||
of remaining on the earlier repeated payload. The capture observed one incoming
|
||||
public peer address; it does not independently identify the active carrier or
|
||||
establish failover behavior. Three payload retransmissions were still present.
|
||||
The passive capture stopped at its deadline, with no kernel drops.
|
||||
|
||||
The first canonical Core position request, while archive drainage was underway,
|
||||
was dispatched but remained `unconfirmed` after 36.82 seconds. Subsequently Core
|
||||
reported online with a fresh position measured approximately nine seconds before
|
||||
the check. This changed state justified one separately recorded new request.
|
||||
The second request completed `device_confirmed`, code 0: VPS queue 0.005224 s,
|
||||
measured device roundtrip 1.135291 s, and locally observed end-to-end operation
|
||||
completion 8.606640 s. These are different clocks/intervals; UI completion is not
|
||||
the radio roundtrip. No automatic replay of the first request occurred.
|
||||
|
||||
Private evidence sessions:
|
||||
|
||||
- `dual-sim-observation-c5c822f9f2c344d2ad21cb2d06de394d`: fresh USB read,
|
||||
configuration comparison, both separate position receipts and fresh telemetry.
|
||||
- `link-correlation-5298fe9e87004db3881db8c0c3ab6553`: correlated passive capture;
|
||||
network SHA-256 `20e5bc63a4d153c2dac4a444e49c928a4486714b74e2c0f1d8fb8f872bb50e8b`,
|
||||
USB SHA-256 `ff419027c925db29ad34b007bf94b035429a9195d25ce9b1fab9ea4ef2ca5ab2`.
|
||||
|
||||
Network telemetry and one confirmed command recovered without configuration,
|
||||
firmware, manufacturer requests, Node updates or VPS runtime changes. This is a
|
||||
successful bounded recovery observation, not proof of the earlier fault's cause,
|
||||
MTS SIM failure, automatic restart or complete autonomous lifecycle acceptance.
|
||||
|
||||
### Two-SIM configuration regression and exact USB recovery, 2026-09-27
|
||||
|
||||
The canonical Core API performed a new network-only read/write/readback case
|
||||
through Host 0.1.23. USB remained connected but was not used during these network
|
||||
operations. The initial read returned the accepted 207-record baseline in
|
||||
12.57 seconds. Changing only field 25 from 15 to 16 seconds reached `verified`
|
||||
in 54.795 seconds, including Core polling and settings-channel pacing.
|
||||
|
||||
The requested return to 15 passed its preflight but remained `unconfirmed` at
|
||||
the write stage after 187.41 seconds. An independent new network read completed
|
||||
in 9.57 seconds and established that the actual value was still 16. A separately
|
||||
recorded restoration attempt using this newly observed predecessor timed out
|
||||
in preflight after 181.328 seconds; that attempt did not reach a settings write.
|
||||
No blind resend or automatic replay ran. Neither timeout proves carrier failure
|
||||
or establishes which part of the settings exchange stalled.
|
||||
|
||||
After both network operations were terminal, identity-bracketed USB inspection
|
||||
again read 16. A single USB recovery changed only field 25 to 15 after asserting
|
||||
that the complete prepared image matched the accepted baseline. An independent
|
||||
read then matched every byte: 207 records, 983 bytes, SHA-256
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
The product's read-only USB refresh subsequently obtained that same image and
|
||||
updated its observed snapshot. The failed network receipt remains `unconfirmed`;
|
||||
USB recovery must not be presented as successful remote restoration.
|
||||
|
||||
Private evidence sessions outside source control:
|
||||
|
||||
- `core-flow-3bada51cd97f4bff83428f82dc4c847a`: initial read, verified write,
|
||||
failed return, explicit restoration and USB recovery subdirectories.
|
||||
- `core-flow-95027e95805e4b2b9d44a58b780a6eac`: independent network read proving
|
||||
the temporary value remained in the device.
|
||||
- `core-cellular-702f37f2155f4fd58b5b240647366b0f`: subsequent product USB refresh,
|
||||
exact-baseline comparison and healthy Core restart.
|
||||
|
||||
### Cellular observations in Mission Core, 2026-09-27
|
||||
|
||||
Operator job: determine which SIM the tracker reports as active, its registration
|
||||
and signal state, and the age of that evidence while diagnosing field connectivity.
|
||||
The admitted placement is the existing B2 **Server and connection** section.
|
||||
A separate diagnostics workspace was rejected because this is supporting state
|
||||
for the same device and connection lifecycle. This is domain content in an
|
||||
existing composition, not new navigation or a new shared visual pattern.
|
||||
|
||||
Core now projects TAG8, TAG201 and TAG99/DS2 table 6 from the existing durable
|
||||
INTERNAL journal after the established framing and CRC validator accepts a
|
||||
packet. Reference: the manufacturer's public
|
||||
[INTERNAL TAG table](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU).
|
||||
The parser is Core-only; the receiver codec and immutable VPS 0.1.23 artifact
|
||||
remain unchanged. The observed B2 emits these tags; this does not qualify every
|
||||
ARNavi hardware/firmware family listed in the generic specification.
|
||||
|
||||
Status and each SIM's serving-network observation retain independent measurement
|
||||
and receive timestamps. Old archive packets do not replace newer observations;
|
||||
missing tags do not refresh an old component. Conflicting repeated scalar tags
|
||||
are omitted. Invalid/unknown MCC and signal values remain unknown. Observations
|
||||
require device admission and the current paired, assigned host; host changes do
|
||||
not mix previous-host data into the new snapshot. Cellular projection and journal
|
||||
cursor commit atomically, independently of whether the packet contains GNSS.
|
||||
|
||||
The UI reuses `SettingsCard`, `StatusBadge`, `FeatureSettingsWindow` and the
|
||||
existing facts layout. Its state grammar distinguishes absent information,
|
||||
current observations and last received observations. Each SIM's network reading
|
||||
shows its own time. Serving-network codes do not set an APN, reconstruct ICCIDs,
|
||||
identify a phone number or establish simultaneous data sessions on both SIMs.
|
||||
Known names are shown only for exact documented MCC/MNC pairs; `250-00` remains
|
||||
an explicit network code rather than being guessed as the owner's MTS SIM.
|
||||
|
||||
Live acceptance through the canonical service on port 8000 showed active SIM 1,
|
||||
GPRS connected and MegaFon `250-02`, with both SIM registration observations and
|
||||
signal readings. The second reported network was `250-00`. Values and timestamps
|
||||
updated in the browser. Normal/expanded fleet compositions, settings scrolling,
|
||||
Escape, keyboard focus return and right-aligned footer controls were checked;
|
||||
the real B2 connection view was left open. No new settings-window expansion
|
||||
control was added; its existing canonical composition was retained.
|
||||
|
||||
Validation: architecture/focused UI checks, full typecheck, 995 frontend tests,
|
||||
production build, Ruff and 130 relevant backend tests passed sequentially. The
|
||||
initial sandboxed backend pass could not bind a test localhost socket; the same
|
||||
bounded suite passed with the required host permission. Coverage includes CRC,
|
||||
partial frames, conflicting tags, legitimate zero values, partial observations,
|
||||
stale/future timestamps, host reassignment, admission and transaction rollback.
|
||||
The existing frontend large-chunk build warning remains. Core was restarted
|
||||
through its managed LaunchAgent after a SQLite backup and passed health
|
||||
acceptance. No firmware, output actuation, Node update, vendor request or VPS
|
||||
runtime change occurred in this increment. Remote-write reliability and the
|
||||
previously listed autonomy gates remain open.
|
||||
|
||||
### SIM state versus APN selection: operator clarification, 2026-09-27
|
||||
|
||||
The B2 manual's two holders/two operators statement does not document the full
|
||||
switching algorithm, its deadlines or simultaneous independent data sessions.
|
||||
The public DS2 contract reports one selected SIM and GPRS OK on that selected
|
||||
SIM. Two registration statuses must not be rendered as two Internet links or
|
||||
as physically tested automatic failover. Do not borrow a switching algorithm
|
||||
from an ARNavi 5 manual and assert it for this B2 firmware.
|
||||
|
||||
The owner reported the second installed card is MTS, but the live TAG201 value
|
||||
contained MCC 250/MNC 0. The configured APN `internet.mts.ru` is configuration
|
||||
evidence, not detected SIM ownership or proof of the current serving network.
|
||||
TAG8 also sometimes omitted a valid MCC. Unknown live codes remain unknown;
|
||||
there is no substitution from a phone number, user declaration, chosen preset,
|
||||
APN or historical carrier reading. Known exact codes currently map MTS, MegaFon
|
||||
and Beeline; other codes remain visible without an invented brand name.
|
||||
|
||||
The same admitted connection section now places observed mobile state before
|
||||
editable endpoint/APN settings, with a distinct canonical card for each SIM.
|
||||
Each card separates the modem's selected Internet SIM, registration, detected
|
||||
network, signal time and the APN from the last configuration read. A freshly
|
||||
reported missing SIM suppresses that slot's previous network observation and
|
||||
cannot receive an Internet badge. Stale/offline data receive last-state wording.
|
||||
This remains novelty A in the existing settings window. Keeping the previous
|
||||
single dense facts block was rejected because it obscured the authority of the
|
||||
operator selector and the difference between registration and Internet use.
|
||||
|
||||
The editing group is explicitly named Internet setup (APN). It selects a target
|
||||
slot first, then a carrier access preset, and previews the APN that will be
|
||||
written. Selection alone edits a local draft. Save settings persists the policy
|
||||
and starts the existing remote apply; the preset replaces APN/login/password for
|
||||
the selected slot and preserves the other slot's access fields. Save profile
|
||||
stores a portable template without sending it. This UI change does not add
|
||||
automatic APN provisioning or a command to switch the active SIM. Incorrect
|
||||
carrier access settings may prevent that slot from establishing Internet access.
|
||||
|
||||
Validation: architecture/focused state checks, typecheck, all 997 frontend tests
|
||||
and production build passed. Cases include two registered SIMs with one selected,
|
||||
selection of SIM 2, stale/offline state, removal with an old network reading,
|
||||
unknown network codes and the existing Beeline mapping. Live browser QA changed
|
||||
the SIM-2 preset from MTS to MegaFon only in a draft: its preview changed to
|
||||
`internet`, while the observed APN remained `internet.mts.ru` and selected SIM
|
||||
remained 1. Escape discarded that draft without saving or transmitting. Ordinary
|
||||
and expanded parent layouts and the canonical footer were checked; the live case
|
||||
was retained. No device command, USB transaction, backend/VPS change or automatic
|
||||
carrier write was performed for this clarification. Core serves content-hashed
|
||||
assets with fresh HTML, so this frontend-only build requires no service restart.
|
||||
|
||||
## APN placement and bounded operation feedback — 2026-09-27
|
||||
|
||||
Owner feedback: keep the SIM evidence and APN editor together; a saved operator
|
||||
preset appeared to wait indefinitely while every action was disabled. Existing
|
||||
connection section retained (novelty A): VPS transaction → SIM 1 → SIM 2 → APN editor → monitoring server.
|
||||
Follow-up owner feedback removed the redundant mobile-state summary card; the
|
||||
active Internet badge remains on the SIM card itself. Putting the monitoring server between
|
||||
SIM evidence and its editor was rejected because it splits one operator task.
|
||||
No new product root, navigation, shared primitive or styling was introduced.
|
||||
|
||||
Read-only inspection of the owner's failed transaction proved a terminal
|
||||
`configure-all / preflight / unconfirmed` receipt: 180-second VPS deadline, no
|
||||
configuration upload and no `write_reply_sent_at`. Therefore that transaction
|
||||
never wrote the selected MegaFon preset to SIM 2. Its desired policy remains
|
||||
saved in Core; no automatic write retry or policy reversal was performed.
|
||||
|
||||
Core now retains the shorter authenticated VPS expiry rather than displaying
|
||||
only its 240-second fallback. Terminal preflight timeout is distinguished from
|
||||
an unknown write result. A still-pending reply past Core's bound terminates as
|
||||
unknown, without resubmission. Frontend shows time remaining, stops the spinner
|
||||
at expiry while retaining the write interlock until reconciliation, and exposes
|
||||
the terminal result. Closing the window and saving a local profile remain
|
||||
possible during a background transaction. This does not fix the underlying
|
||||
intermittent B2 configuration upload and does not establish autonomous network
|
||||
configuration acceptance.
|
||||
|
||||
Validation: 26 equipment-network backend tests, 19 focused frontend/architecture
|
||||
checks, full 999 frontend tests, typecheck and production build passed. Synthetic
|
||||
coverage includes preflight versus write/verify timeout, a reachable VPS stuck
|
||||
pending, deadline non-extension, and spinner expiry without inventing success
|
||||
or releasing the write interlock. Real UI verification uses the enrolled B2,
|
||||
including a single read-only VPS transaction; see private session manifest for
|
||||
its outcome. No configuration write, USB operation, relay command, firmware
|
||||
upload or vendor-service request belongs to this increment.
|
||||
|
||||
## Explicit Internet SIM selection — 2026-09-27
|
||||
|
||||
Owner clarification supersedes the APN-only selector: choosing SIM 2 and saving
|
||||
must actually request Internet on SIM 2, keep the settings window open, and
|
||||
report device evidence rather than a local save or command receipt.
|
||||
|
||||
Model 231 field 72 bits 10 and 20 prohibit GPRS on SIM 1 and SIM 2 respectively
|
||||
(manufacturer model schema aliases `231_72_10`, `231_72_20`). A bounded physical
|
||||
USB experiment established that writing these flags alone did not switch the
|
||||
selected SIM within 93 seconds. The same flags followed by the documented
|
||||
0107 restart returned fresh DS2 telemetry with SIM 2/GPRS OK after about 79
|
||||
seconds. Both experiments independently restored the exact predecessor image.
|
||||
These are exclusive data-selection flags, not a priority/failover algorithm.
|
||||
|
||||
Host 0.1.24 owns one durable `select-sim` operation: fresh image preflight;
|
||||
exact predecessor check; one image dispatch; independent exact readback;
|
||||
one restart; then fresh type-1 TAG99 with the requested active SIM and GPRS OK
|
||||
on a connection opened after restart dispatch. A 360-second deadline bounds
|
||||
all phases. A matching image alone cannot mark selection successful. Host
|
||||
restart, missed response or expiry never replays a write or restart. Core also
|
||||
requires fresh presence evidence from the owning VPS before dispatch.
|
||||
|
||||
The existing connection section is retained (novelty A), using canonical
|
||||
Select, TextField, SettingsCard and window controls. Explicit SIM selection
|
||||
replaces any legacy carrier-preset intent; APNs and credentials stay unchanged
|
||||
unless the operator edits the selected card's APN. The form starts with an
|
||||
explicit selection prompt instead of presenting a passive APN browser as a
|
||||
command. Save keeps the window open and brings the operation result into view.
|
||||
Historical installed-card evidence remains labelled as historical during an
|
||||
outage; stale evidence cannot authorize a new write. A fresh removal excludes
|
||||
the slot. Unknown network codes remain unnamed. Saving without an edit or an
|
||||
explicit SIM-selection intent explains that no command was sent.
|
||||
|
||||
Synthetic acceptance covers preserved access credentials/other flags, strict
|
||||
slot/flag agreement, one-time restart including service-crash recovery, wrong
|
||||
SIM, no GPRS, missing DS2, archived/future measurements, old/unregistered TCP
|
||||
sessions, expiry, and Core refusing to equate readback with SIM selection.
|
||||
Frontend architecture, typecheck, 1003 unit tests and production build passed.
|
||||
Physical end-to-end outcome and limitations follow in the qualification entry.
|
||||
|
||||
### Host 0.1.24 physical acceptance
|
||||
|
||||
Private session `sim-switch-284dab5fa2d74cdbb0186e9fe421d207/network-check`:
|
||||
The bench stopped reporting after the USB experiment's exact-image restoration.
|
||||
A separate, previously qualified USB restart restored SIM 1/GPRS and a new
|
||||
network session. This recovery is not counted as a remote SIM-selection result.
|
||||
|
||||
The operator-facing form then selected detected SIM 2 and clicked Save settings.
|
||||
The entire subsequent transaction used Core → owned VPS → cellular B2, without
|
||||
USB writes or vendor services. Exact preflight/readback proved that only field
|
||||
72 changed, 2072 → 3096; all 206 other fields and both APNs/access credentials
|
||||
were preserved. A single documented restart was dispatched after verification.
|
||||
The requested SIM 2/GPRS was independently observed through a new TCP session;
|
||||
the durable result became `sim_selected` and Core's policy state `applied`.
|
||||
|
||||
Total transaction time: **255.097 seconds** from Core creation; restart-to-
|
||||
confirming-new-session evidence: **210.044 seconds**. The earlier bench result
|
||||
of about 79 seconds is not a guarantee. Fast or bounded cellular registration,
|
||||
fallback to the other SIM and repeated bidirectional switching under field
|
||||
conditions have not been established. The real SIM 2 now reports MCC250/MNC1,
|
||||
so its MTS label is from fresh network evidence, not the configured APN.
|
||||
The selected-only data mode remains enabled for SIM 2 on this test B2.
|
||||
|
||||
The settings window stayed open throughout and displayed pending and confirmed
|
||||
results. A further value-comparison fix treats JSON property order and explicit
|
||||
server defaults as equivalent; completed operations no longer leave read/apply
|
||||
buttons disabled as though the form were dirty. Saving an unchanged applied
|
||||
policy does not dispatch another restart. Progress is brought into view on save.
|
||||
|
||||
The installer was reproduced byte-for-byte and published for download in Core:
|
||||
Host **0.1.24**, SHA-256
|
||||
`c1090551788cda35f7757ee654419f83bb3a3e12d08c8c8e82ce0012e1b2f33a`.
|
||||
Existing host identity, TLS, bindings and state were preserved by the same
|
||||
installer used for operator deployment. Node was not modified.
|
||||
|
||||
Final acceptance: all **1004** frontend tests, typecheck and production build
|
||||
passed. Browser QA confirmed normal/expanded parent layouts, Escape, enabled
|
||||
read controls after completion, and unchanged-save feedback with the operation
|
||||
ID and device revision unchanged. Canonical Core remains on port 8000; no
|
||||
Mission Core listener remains on 8765. Fresh SIM 2/GPRS data remained online.
|
||||
|
||||
### Communication limits and transport outage, 2026-09-27
|
||||
|
||||
See [the communication limits investigation](COMMUNICATION_LIMITS.md) for
|
||||
manufacturer references, measured phases, capacity limits and remaining gates.
|
||||
Session `communication-limits-69cdaddac9c74079b059d8115a2d62aa` retained
|
||||
simultaneous USB/PCAP evidence and all unsuccessful command results.
|
||||
|
||||
Before the new experiment, SIM2 stopped advancing telemetry despite repeated
|
||||
connections. Three identical old packages were each followed by a VPS ACK and
|
||||
an incoming RST+ACK 9–10 ms later, with a different TTL from regular tracker
|
||||
traffic. This suggests a transport-path intermediary but does not identify its
|
||||
owner or establish a firmware defect. A request-position remained unconfirmed.
|
||||
|
||||
One explicit USB recovery changed only the exclusive SIM selection to SIM1,
|
||||
preserved both APNs/all other records, and issued one qualified restart.
|
||||
Hardware identity, new USB session and exact post-write configuration were
|
||||
verified. The broader identity comparison failed because the device-reported
|
||||
SIM1 identifier changed length; that failed check is retained separately.
|
||||
Core first observed resumed delivery after 80.416 s, and SIM1 telemetry less
|
||||
than 30 seconds old after 234.371 s; backlog delivery accounts for part of this
|
||||
gap. This does not qualify reverse switching over the network.
|
||||
|
||||
Three SIM1 request-position samples also remained unconfirmed. VPS dispatch
|
||||
queues were 5.560–6.525 ms. The correlated sample showed kernel retransmissions
|
||||
without a normal TCP ACK or matching USB receipt. Retransmissions persisted
|
||||
after the 30-second application result deadline: current timeout does not
|
||||
guarantee cancellation of bytes already queued in TCP. This is a priority
|
||||
limitation before claiming bounded remote-output latency.
|
||||
|
||||
Final Core policy/USB image were reconciled to SIM1 through a guarded no-op
|
||||
application (`unchanged`), with fresh SIM1/GPRS observed. No firmware, relay,
|
||||
onboard Node, vendor-service request or product-runtime update occurred.
|
||||
Temporary packet captures exited; the canonical Core and VPS services remain.
|
||||
|
||||
### Positive command control with USB disconnected, 2026-09-27
|
||||
|
||||
Session `network-only-278ac319e262481d971a22cd1b4480ef` observed no B2 USB
|
||||
enumeration and used only Core/VPS. Fresh SIM1/GPRS continued. One position
|
||||
request reached `device_confirmed`, code 0: VPS queue 0.004374 s, device
|
||||
confirmation 1.320071 s after dispatch. PCAP independently matched the command
|
||||
token in a type-9 response after 1.314112 s; no incoming RST appeared in the
|
||||
45-second capture. No configuration, outputs, restart or runtime changes.
|
||||
This proves one working network-only exchange, not that USB caused earlier
|
||||
failures, not bounded future latency, and not physical-output actuation.
|
||||
|
||||
### TCP delivery deadlines, VPS Host 0.1.25, 2026-09-27
|
||||
|
||||
Release session `delivery-a8d26be666ec4dd182f46a4db8d0c566` qualifies monotonic
|
||||
command-byte deadlines across asyncio and Linux kernel queues. Commands are
|
||||
bounded by the operation deadline and 30 seconds after dispatch; configuration
|
||||
HTTP replies by the operation deadline and 12 seconds. Abortive close prevents
|
||||
queued bytes from lingering after disconnect. TCP ACK only releases transport
|
||||
tracking; durable protocol confirmation remains separate. Idempotent submission
|
||||
now reports an expired record's current outcome consistently with GET.
|
||||
|
||||
The shipped loopback qualifier passed on the supported VPS: healthy TCP stays
|
||||
open without application confirmation; a blocked 64-KiB stream resets at
|
||||
0.751091 seconds for a 0.750-second deadline. This is a bounded functional check,
|
||||
not capacity qualification. No firewall, packages or onboard environment changed.
|
||||
|
||||
Physical network-only session `network-only-b5c513eb06da42d599fb515e66b8a83d`
|
||||
produced an unconfirmed position command: queue 4.791 ms, five on-wire sends,
|
||||
no TCP ACK, reset at 29.994 seconds after first transmission, no command bytes
|
||||
after expiry in the 45-second capture and no replay on another connection.
|
||||
Core's dialog remained open and its actions became available after timeout.
|
||||
This qualifies failure containment, not reliable mobile delivery. A preceding
|
||||
unaccepted/uncertain post-update attempt is retained separately, not retried.
|
||||
|
||||
154 backend cases and 1004 frontend cases passed; production build and typecheck
|
||||
passed. The byte-reproducible installer was applied and published as 0.1.25.
|
||||
Four persistent identity/key files retained their digests. Tracker configuration,
|
||||
SIM selection, firmware, outputs and onboard Node were untouched. Already
|
||||
received commands cannot be cancelled by closing a server socket.
|
||||
@@ -0,0 +1,111 @@
|
||||
# B2: permission for both SIMs, 2026-09-27
|
||||
|
||||
## Decision and evidence boundary
|
||||
|
||||
The model-231 configuration schema defines field 72 bit 10 as prohibiting GPRS
|
||||
on SIM 1, and bit 20 as prohibiting GPRS on SIM 2. Neither flag specifies a
|
||||
priority or failover interval. The public SIM sections contain APN, credentials,
|
||||
roaming permission, preferred roaming operator, PIN and balance-query settings.
|
||||
No documented temporary SIM selection or timed rollback was found there or in
|
||||
the B2 manual's command table. That is a limit of the reviewed documentation,
|
||||
not proof that no additional manufacturer command exists.
|
||||
|
||||
Sources: [manufacturer model-231 schema](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations)
|
||||
and [B2 user manual, sections 9–10](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf).
|
||||
|
||||
## Product behavior
|
||||
|
||||
The existing Internet selector adds **Обе SIM разрешены**. Selecting one card
|
||||
retains explicit exclusive selection and its warning about losing the other
|
||||
card as a recovery channel. Selecting both clears only the two GPRS prohibition
|
||||
bits; it preserves both APNs, credentials, other flags, unknown records and
|
||||
server endpoints. This is not simultaneous Internet on two cards or a promise
|
||||
of an immediate automatic switchover. No new surface, control or product root.
|
||||
|
||||
The portable policy uses `connectivity.strategy=both`. A deliberate save submits
|
||||
one durable `select-sim` job with `sim_policy=both` and no exclusive `sim_slot`.
|
||||
VPS 0.1.37 validates that neither prohibition remains. Core rejects the new
|
||||
request on older VPS versions. Existing exclusive requests remain compatible.
|
||||
|
||||
Execution is fresh full read → guarded image write → independent full read →
|
||||
restart → fresh GPRS data on a new connection. Either real slot may satisfy
|
||||
the last step. Configuration readback alone, an old connection, or registration
|
||||
without GPRS cannot. Recovery reads the actual image and fresh modem state
|
||||
before deciding on a further attempt. Saving unrelated settings with an
|
||||
already-applied both-SIM policy does not request another restart.
|
||||
|
||||
## Physical acceptance on the owner's B2
|
||||
|
||||
Private session `dual-sim-policy-e26d3337c21a4a3bbc321fcf67eb0756`; model 231,
|
||||
firmware 0.01, indoor conditions. USB and firmware were not used.
|
||||
|
||||
- Baseline full read succeeded on its first attempt: 207 records, 983 bytes.
|
||||
- The actual product selector and **Сохранить настройки** submitted the job.
|
||||
- Exactly field 72 changed; its only difference was clearing SIM 2's GPRS
|
||||
prohibition. Both APNs and every other record remained byte-identical.
|
||||
- One attempt completed. Fresh GPRS on SIM 1 was received 62.631 seconds after
|
||||
restart dispatch; the whole workflow took about 110 seconds.
|
||||
- Closing the settings window with Escape and opening it again retained the
|
||||
same running job. The window did not own or cancel the transaction.
|
||||
- An additional full read after the restart matched the complete target image,
|
||||
confirming persistence beyond the pre-restart readback.
|
||||
- A subsequent position request received B2 token confirmation code 0 in
|
||||
2.435 seconds, one attempt. Core and VPS agreed on the result.
|
||||
|
||||
SHA-256 of the baseline: `7e7798a5e2c1909454dfab500dac4cc2d0917555a02f2afac711b167c9ae1ee8`.
|
||||
SHA-256 after the change: `a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
|
||||
The owner then powered down, removed SIM 1 and started B2 with only SIM 2
|
||||
(MTS), on external power without USB. No new connection was observed for at
|
||||
least 386 seconds after the owner reported completion. The receiver was active
|
||||
and had zero established tracker sockets. Stored SIM 2 APN/login/password
|
||||
matched the public MTS preset, and both GPRS permissions were enabled. The owner
|
||||
reported one long and three short blue flashes: according to the manual, mobile
|
||||
network search/registration and more than eight GNSS satellites. This does not
|
||||
identify the cause (coverage, SIM service or modem); it does not establish a
|
||||
VPS/APN failure. Later buffered observations qualify this LED-only account:
|
||||
B2 recorded SIM 2 as registered with network 250-01 and GPRS state 4 while
|
||||
SIM 1 was absent. Those records arrived only upon recovery, 94–468 seconds
|
||||
after measurement. They establish what the modem reported during the outage,
|
||||
not a working application connection to this VPS through MTS. The cause remains
|
||||
unresolved. Boot through SIM 2 alone is **not accepted**. No claim of seamless
|
||||
radio failover follows from a powered-off card-removal test.
|
||||
|
||||
One position request was queued while the last packet was already 120 seconds
|
||||
old. Core and VPS kept it in `waiting-link` with zero attempts. The owner then
|
||||
restored SIM 1 with power off, retained SIM 2, and supplied 12 V without USB.
|
||||
The same durable job was dispatched once, 442.342 seconds after creation,
|
||||
and received B2 confirmation code 0 in 0.906 seconds. Total creation-to-reply
|
||||
time was 443.247 seconds. Core and VPS agreed on `device_confirmed`; no
|
||||
replacement command or settings write was involved. This proves preservation
|
||||
and automatic dispatch of this queued command across the observed outage,
|
||||
not exactly-once execution of every possible command after an ambiguous reply.
|
||||
|
||||
Fresh telemetry after recovery reports SIM 1 active, GPRS state 4, and both
|
||||
SIMs present. The first fresh modem record was measured at 20:47:25 UTC and
|
||||
received at 20:47:30.513 UTC. Earlier SIM 2 records, measured at
|
||||
20:39:34–20:45:52 UTC, were received at 20:47:21.715–20:47:26.873 UTC.
|
||||
Raw packages and decoded timestamps are retained privately. The runtime's
|
||||
30-second freshness condition prevents those buffered records from confirming
|
||||
a current SIM-selection operation.
|
||||
|
||||
## Release and validation
|
||||
|
||||
VPS 0.1.37 was installed using the versioned installer on the existing host.
|
||||
Its four identity files were preserved, its service is active, and all 28
|
||||
installed payload files match the release manifest. Installer published in
|
||||
Mission Core: SHA-256 `140a54c608a6e9c71663cc9435c7ffab12bba6c5277fc78c6d9daa59da19e002`.
|
||||
No clean-Ubuntu or migration qualification is inferred from this update.
|
||||
|
||||
Focused backend coverage includes contradictory policy rejection, APN/flag
|
||||
preservation, either-slot fresh evidence, recovery without a second restart,
|
||||
Core version admission and rejection of readback-only success. The pre-existing
|
||||
TCP test needed a local-socket sandbox exception and then passed, along with
|
||||
the seven packet-commit tests. Frontend architecture, typecheck, 1,012 tests and
|
||||
production build passed; a subsequent progress-text change has focused coverage
|
||||
and a fresh production build. Normal settings, dropdown, save, pending close /
|
||||
reopen, and persisted selection were checked in the canonical UI on port 8000.
|
||||
|
||||
Remaining: automatic switchover timing/conditions and recovery from exclusive
|
||||
selection of an unusable SIM are not qualified. A disconnected VPS cannot
|
||||
deliver a recovery command over that same disconnected mobile link.
|
||||
@@ -0,0 +1,101 @@
|
||||
# Применение интернета для распознанной SIM
|
||||
|
||||
Дата: 2026-09-28. VPS Host ARNavi 0.1.38. B2 model 231, firmware 0.01.
|
||||
Сессия: `automatic-connectivity-66e3010ea75244c6b5b97c28fad18193`.
|
||||
|
||||
## Реализованная граница
|
||||
|
||||
В существующем блоке «Интернет» пользователь выбирает SIM и сохраняет настройки.
|
||||
Для выбранной SIM по умолчанию включается подбор параметров карты. Сначала Core
|
||||
ищет ранее проверенную тройку APN/логин/пароль этой карты, затем кандидат из
|
||||
каталога по её подтверждённой домашней сети. Сейчас кандидаты есть для обычных
|
||||
тарифов МТС и МегаФона. Обслуживающая сеть, номер телефона и APN слота не
|
||||
используются как доказательство оператора или идентичности карты.
|
||||
|
||||
Карты распознаются по полному сетевому SID и ранее квалифицированному соответствию
|
||||
SID ↔ модемные CCID/IMSI. Новый неизвестный SID не получает имя оператора по
|
||||
догадке. Применение по сети требует доступного канала к собственному VPS.
|
||||
|
||||
Политика хранит только выбор режима. Секреты доступа, идентификаторы SIM и
|
||||
доказательства успешного подключения не входят в переносимый профиль. Кэш
|
||||
проверенных настроек находится в частном SQLite-хранилище наблюдений SIM и
|
||||
переживает перезапуск Core. Он привязан к карте внутри данного трекера, не слоту.
|
||||
|
||||
## Цепочка подтверждения
|
||||
|
||||
1. Core проверяет актуальную регистрацию и неаннулированное наблюдение карты.
|
||||
Стартовый SID не объявляется свежим измерением на каждом пакете: сохраняется
|
||||
привязка при свежем состоянии регистрации. Отсутствие, поиск, конфликт или
|
||||
неоднозначность делают её непригодной для автоматической записи.
|
||||
2. В долговечном задании фиксируются карта, слот и точный целевой образ.
|
||||
VPS проверяет идентичность перед отправкой записи и ещё раз в транзакции
|
||||
перед выдачей конфигурации по HTTP. При замене карты образ не выдаётся;
|
||||
недостаток сведений сохраняет задание в ожидании.
|
||||
3. VPS читает фактический образ, сверяет предшественника, пишет изменения и
|
||||
независимо читает результат. Для выбора SIM проверяется её эксклюзивное
|
||||
разрешение GPRS; служебный перезапуск принадлежит тому же заданию.
|
||||
4. Успех требует свежего GPRS на выбранном слоте по новому соединению и нового
|
||||
подтверждения ожидаемого SID после перезапуска. Обычный ACK или только
|
||||
совпадение настроек не закрывает операцию.
|
||||
5. Core запоминает доступ только после совпадения целевого образа и результата
|
||||
`sim_selected` с подтверждённой картой. Повторное чтение после потерянного
|
||||
ответа использует ту же проверку карты. Другие SIM сохраняют свои параметры.
|
||||
|
||||
Схема соединений прежняя: Core инициирует API-запросы к VPS; B2 инициирует
|
||||
соединение с VPS. VPS не подключается к Core. Внешний ARNavi в этом цикле не
|
||||
участвует. Достоверность ограничена данными прошивки B2; криптографической
|
||||
аттестации физической SIM это не добавляет.
|
||||
|
||||
## Физическая проверка
|
||||
|
||||
МегаФон находился в первом слоте, МТС во втором. Питание 12 В, USB отключён.
|
||||
Оба выбора сделаны кнопками обычного интерфейса Mission Core.
|
||||
|
||||
| Выбор | Результат | Попытки | От принятия задания до подтверждения |
|
||||
| --- | --- | --- | --- |
|
||||
| SIM 2, МТС | Образ проверен, свежая связь через SIM 2, карта подтверждена | 1 | 114.236 с |
|
||||
| SIM 1, МегаФон | Образ проверен, свежая связь через SIM 1, карта подтверждена | 1 | 132.964 с |
|
||||
|
||||
Это длительность полного цикла настройки и перезапуска, не задержка доставки
|
||||
одного пакета. APN и реквизиты обеих карт уже совпадали с кандидатами;
|
||||
в образе менялись разрешения SIM. Исправление заведомо неверных реквизитов
|
||||
новой карты данным аппаратным опытом не проверялось.
|
||||
|
||||
Интерфейс после каждого результата показал «Проверенные настройки этой карты».
|
||||
Перезапуск Core сохранил оба результата кэша, тот же идентификатор завершённого
|
||||
задания и одну попытку; повторной отправки не возникло. Итог: SIM 1 активна,
|
||||
трекер передаёт свежие пакеты на собственный VPS.
|
||||
|
||||
Синтетические проверки охватывают перенос настроек вместе с картой между
|
||||
слотами, замену карты после отправки команды до HTTP-выдачи образа, отсутствие
|
||||
нового SID при наличии GPRS, восстановление очереди VPS, приватность ответа,
|
||||
защиту от архивных пакетов и избирательную запись всех трёх полей доступа.
|
||||
Связанные backend-тесты, архитектура UI, typecheck, 1015 frontend-тестов и
|
||||
production build прошли. Проверены ручной режим APN без отправки, повторное
|
||||
открытие, Escape, обычный и развёрнутый контейнер оборудования.
|
||||
|
||||
## Поставка
|
||||
|
||||
Установлен штатным версионным `.pyz` поверх 0.1.37. Четыре файла идентичности
|
||||
сохранены, журнал скопирован штатным SQLite backup до обновления; сервис активен.
|
||||
Проверены все файлы установленного manifest и байты скачивания из Core.
|
||||
Две независимые сборки дали одинаковый артефакт.
|
||||
|
||||
- Installer SHA-256: `952198b0495520536023fc2f675847adb80f37ca1e5a2e61db00a99da1aac767`.
|
||||
- Manifest SHA-256: `89e8342901dc46b02efe349941cdc96369a4b4352b89c717651267cdd6aa7ab4`.
|
||||
- База исходников: `fb33a6d45c73e6d458faed586959ba1a12775355` плюс рабочие изменения;
|
||||
точные хеши исходников и закрытые измерения находятся в каталоге сессии.
|
||||
|
||||
## Что ещё не закрыто
|
||||
|
||||
- Автоматический запуск настройки сразу после физической перестановки без
|
||||
«Сохранить настройки» не реализован. Выбор и применение остаются явным действием.
|
||||
- Сетевой подбор для произвольной ранее неизвестной карты без её квалификации
|
||||
не заявляется. Универсальная база операторов, редактирование корпоративных
|
||||
реквизитов и перебор нескольких кандидатов требуют отдельного этапа.
|
||||
- Если B2 вообще не может выйти в интернет, VPS не сможет по этому отсутствующему
|
||||
каналу исправить APN. Нужен локальный канал начальной настройки/восстановления.
|
||||
- Новая физическая перестановка после обучения кэша и реальная коррекция APN
|
||||
в другом слоте ещё не проверены; программная перестановка проверена тестами.
|
||||
- Чистая Ubuntu, перенос на другой VPS и масштабная нагрузка остаются отдельной
|
||||
приёмкой согласно решению владельца.
|
||||
@@ -0,0 +1,137 @@
|
||||
# Команды B2: очередь, журнал и операторское окно
|
||||
|
||||
## Принятое размещение
|
||||
|
||||
По запросу владельца 27.09.2026 из строки ARNavi B2 в оборудовании открывается
|
||||
отдельное окно «Команды». В настройках остаётся переход в то же окно. Пользователь
|
||||
выбирает понятное действие, видит тело для прочитанной прошивки и отправляет его;
|
||||
здесь же просматривает незавершённые и завершённые операции.
|
||||
|
||||
Альтернатива — оставить команды внутри настроек — не выбрана: журнал живёт
|
||||
дольше редактирования конфигурации и не должен зависеть от сохранения формы.
|
||||
Нового раздела основного меню или product root нет. Это доменная композиция
|
||||
канонического `Window size="lg"`, `SettingsCard`, `ResourceList/ResourceRow`,
|
||||
`Select`, `StatusBadge`, `Button`, `IconButton`, `ToastStack` и `LoadingRegion`.
|
||||
В реестре нет иконки терминала; используется существующая `activity` с явным
|
||||
accessible name «Команды». Новая общая визуальная сущность не добавлена.
|
||||
|
||||
## Владение и порядок
|
||||
|
||||
- **Core** — долговечные намерения, FIFO по устройству, локальная отмена до
|
||||
передачи, журнал и повтор HTTP с тем же ID при неизвестном результате.
|
||||
- **VPS** — одна активная операция на B2, соединение с устройством, исходящий
|
||||
пакет, ожидание ответа и собственный долговечный результат.
|
||||
- **B2** — выполнение согласно его прошивке, подтверждение по доступной
|
||||
семантике протокола. GNSS и наличие мобильного соединения — разные условия.
|
||||
|
||||
Очередь относится к серверному процессу Core, не к открытой вкладке. Закрытие
|
||||
окна не останавливает её. Если сам Core выключен, ещё не переданные операции
|
||||
не передаются до его возвращения и истекают по исходному сроку. Уже принятые
|
||||
VPS операции продолжаются независимо от Core. Перезапуск не продлевает сроки.
|
||||
Текущий владелец соединений и исполнения — VPS 0.1.26; этот этап меняет Core,
|
||||
не firmware трекера или бортовой Node.
|
||||
|
||||
На устройство допускается до 32 незавершённых операций. Локальная очередь
|
||||
передаёт одну операцию после завершения предыдущей; конфигурационные операции
|
||||
из настроек используют тот же interlock. Переход waiting → submitting и
|
||||
приватный outbox фиксируются одной SQLite FULL-транзакцией. Отмена конкурирует
|
||||
с отправкой через эту же транзакционную границу: после начала передачи она
|
||||
отклоняется, а не выдаётся за отмену физического действия.
|
||||
|
||||
Запрос позиции ждёт начала передачи до 30 секунд. Выходы/импульс/restart ждут
|
||||
начала передачи из Core до 3 секунд. Уже переданная обычная команда имеет
|
||||
исходный срок до 30 секунд, restart — до 180 секунд для подтверждения возврата.
|
||||
VPS дополнительно применяет свои ограничения отправки и TCP из 0.1.26.
|
||||
Эти часы не дают жёсткого real-time: таймер ОС может задержаться, а доставка
|
||||
на сотовом пути не гарантируется. Просроченное воздействие не накапливается.
|
||||
|
||||
После неясного ответа на POST браузер сохраняет ID запроса локально и предлагает
|
||||
уточнить ту же отправку. Идентичный ID возвращает имеющуюся операцию; другой
|
||||
preset с тем же ID отклоняется. Новые произвольные команды не принимаются.
|
||||
Каталог ограничен прошивкой 0.01, режимом выхода и поддержанными действиями:
|
||||
позиция, restart, PIN4–6 вкл./выкл./импульс 5 секунд. Тело показывается без пароля;
|
||||
служебные токены и обрамление формирует существующий адаптер VPS.
|
||||
|
||||
## Журнал
|
||||
|
||||
Отдельная таблица операций с индексами по устройству и состоянию сохраняет
|
||||
каждую принятую операцию, её параметры без секретов, состояние, события и
|
||||
доступные времена отправки/ответа. Существующие операции настройки также
|
||||
попадают сюда. История загружается страницами по стабильному sequence cursor;
|
||||
повторные обновления объединяются по ID, а не создают новые строки.
|
||||
Активные записи возвращаются независимо от страницы истории; последнее
|
||||
состояние известных активных ID запрашивается до завершения. Поздний ответ
|
||||
опроса не заменяет более свежее состояние в браузере.
|
||||
|
||||
Если Core не получил результат команды до своего срока, неизвестный исход
|
||||
не блокирует очередь. Отдельный долговечный GET-опрос исходного VPS уточняет
|
||||
эту строку без повторной отправки B2 и без перезаписи более новой операции.
|
||||
Браузер продолжает следить за такими строками вне первой страницы.
|
||||
Границы и проверка описаны в [протоколе восстановления](FAULT_RECOVERY_20260927.md).
|
||||
|
||||
Состояния различают очередь Core, передачу на VPS, очередь VPS, отправку B2,
|
||||
подтверждение, неизвестный результат, отсутствие подтверждения, истечение срока
|
||||
и локальную отмену. «Подтверждено B2» не означает, что измерены контакты реле.
|
||||
Для restart результат — свежие данные по новому соединению. Текстовые FC
|
||||
команды без токена не получают выдуманного подтверждения исполнения.
|
||||
|
||||
Времена, сообщённые VPS, показаны отдельно от времени, когда Core увидел статус.
|
||||
Если опрос пропустил промежуточное состояние, известное время отправки/ответа
|
||||
сохраняется как отдельное свидетельство; неизвестное время не восстанавливается
|
||||
по предположению. При первом запуске прежние network_operation из истории
|
||||
Core импортируются. Старые незавершённые записи без действующей операции
|
||||
получают неизвестный исход; точные времена их переходов не придуманы.
|
||||
|
||||
## Обновление и ограничения
|
||||
|
||||
Новая команда будит рабочий цикл Core. При активных операциях результаты
|
||||
проверяются примерно раз в секунду; обычная синхронизация телеметрии сохраняет
|
||||
интервал около пяти секунд. Выполнение не зависит от открытого окна; окно
|
||||
читает журнал раз в две секунды и сохраняет последний результат при ошибке.
|
||||
Время на экране включает задержку наблюдения; отдельное время VPS → B2
|
||||
показывается по измерению, а не по анимации.
|
||||
|
||||
Один имеющийся worker Core последовательно обслуживает подключённые хосты;
|
||||
длительный сетевой вызов может задержать обработку следующего. Исходные сроки
|
||||
действия не продлеваются, но малая задержка и тысяча устройств этим этапом
|
||||
не квалифицированы. VPS сохраняет предел 256 соединений. Масштабирование,
|
||||
ретенция журнала и автоматический резерв SIM требуют отдельной квалификации.
|
||||
Условия помещения/улицы не входят в модель устройства, настройки или UI.
|
||||
|
||||
## Приёмка 27.09.2026
|
||||
|
||||
До обновления сохранены приватные SQLite-копии обеих баз. Миграция проверена
|
||||
на отдельной копии: целостность БД сохранена, восстановлены 56 прежних операций.
|
||||
После установки Core журнал доступен из строки B2 и через настройки; Escape
|
||||
возвращает фокус к кнопке команд. Проверены каталог, маскировка пароля, все три
|
||||
фильтра, раскрытие этапов рядом со строкой и подгрузка старой истории.
|
||||
|
||||
В интерфейсе последовательно отправлены три запроса координат. Результат
|
||||
третьего сохранён при закрытом окне и показан после повторного открытия.
|
||||
|
||||
| Запрос | Ответ B2 по VPS | Ожидание в VPS | Сопоставленный ответ в PCAP |
|
||||
|---|---:|---:|---:|
|
||||
| 1 | 1,188 с | 0,0038 с | 1,182 с |
|
||||
| 2 | 1,995 с | 0,0035 с | 1,989 с |
|
||||
| 3 | 2,758 с | 0,0044 с | 2,753 с |
|
||||
|
||||
PCAP подтверждает три отдельных прикладных кадра, по одному на операцию,
|
||||
ответы с совпадающими токенами/CRC и кодом 0. Повторов и TCP reset в этой
|
||||
100-секундной записи нет. Измерения относятся к запросам позиции; исполнение
|
||||
выходов, аварийный reboot, максимальная пропускная способность и длительный
|
||||
радиообрыв этой серией не проверялись. USB serial не открывался; настройки,
|
||||
SIM, прошивка B2, Node и версия VPS не менялись.
|
||||
|
||||
Пройдены 215 backend-проверок до заключительных исправлений; после них —
|
||||
87 целевых проверок очереди, API, журнала, сетевых операций и оборудования,
|
||||
включая временную ошибку SQLite, потерянный POST, перезапуск, неизменность ID,
|
||||
отмену при конкурирующей отправке, исходный deadline, перепривязку и полный
|
||||
размер очереди. Также прошли Ruff, архитектурные проверки, TypeScript,
|
||||
1007 frontend-тестов и production build. Существующие предупреждения
|
||||
Starlette/httpx и большого JS chunk сохраняются.
|
||||
|
||||
Приватная сессия доказательств:
|
||||
`command-runtime-0a8b7a08711746f08b55f0e32a4313f6`.
|
||||
В неё входят исходные пакеты, снимки журнала, резервные копии, UTC/monotonic
|
||||
отметки, программа анализа и SHA-256 manifest. Это ограниченная приёмка на одном
|
||||
B2; ровно одно физическое исполнение и масштаб в тысячу устройств не заявляются.
|
||||
@@ -0,0 +1,287 @@
|
||||
# B2: границы связи и план квалификации
|
||||
|
||||
Состояние исследования: 2026-09-27. Область принятия: один тестовый B2,
|
||||
модель 231, прошивка 0.01; текущий VPS Host 0.1.26. Исторические результаты
|
||||
0.1.24/0.1.25 ниже сохраняют собственную область принятия. Это не гарантия для всех B2,
|
||||
операторов, прошивок или парка из тысячи устройств.
|
||||
|
||||
## Источники и граница достоверности
|
||||
|
||||
- [Руководство B2 производителя](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf):
|
||||
разделы 1–3, 9–10. Имя файла содержит 241219, заголовок PDF — 241220.
|
||||
- [INTERNAL производителя](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit):
|
||||
SERVER_COM и TAG99/DS2, определения SIM и состояния GPRS.
|
||||
- Публичная схема конфигуратора модели 231: поле 72, биты 10 и 20 —
|
||||
запреты GPRS по слотам. Сохранённый первичный материал использовался
|
||||
при квалификации; неизвестные поля полной конфигурации сохраняются.
|
||||
- [Каталог прошивок B2](https://8888.arusnavi.ru/Arnavi%20B2/%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B8/)
|
||||
содержит 0.05. Наличие файла не доказывает исправление обнаруженной проблемы.
|
||||
Списка изменений и принятия этой версии в нашем тракте пока нет.
|
||||
- Поиск B2 в форумах Wialon/Gurtam и общедоступных обсуждениях не дал
|
||||
проверяемого описания точного алгоритма SIM и его таймеров. Описания других
|
||||
ARNavi и новости об их прошивках нельзя переносить на B2 0.01.
|
||||
|
||||
Руководство подтверждает 2G (GSM/GPRS/EDGE), два SIM-держателя, четыре сервера,
|
||||
внешний Wi-Fi-модуль и SMS/TCP-команды. Устройство имеет совмещённые интерфейсы:
|
||||
вторая CAN-линия использует ресурс RS485. Подключение всех возможностей сразу
|
||||
из перечня не следует из наличия разъёма. Детального расписания двух SIM,
|
||||
гарантированных задержек команд и API выбора приоритетной SIM руководство
|
||||
не устанавливает.
|
||||
|
||||
## Что означает выбор SIM
|
||||
|
||||
На принятой прошивке DS2 сообщает одну выбранную SIM для GPRS. Две регистрации
|
||||
в сети не являются доказательством двух независимых подключений к интернету.
|
||||
Наш способ выбора включает GPRS целевого слота и запрещает его другому слоту.
|
||||
Это **исключительный выбор**, а не предпочтение с автоматическим резервом.
|
||||
|
||||
Само изменение этих флагов не переключило соединение за 93 секунды предыдущего
|
||||
USB-опыта. Положительный результат получен после перезапуска. Текущая операция
|
||||
`select-sim`: свежий снимок → запись → независимое чтение → один restart →
|
||||
свежая DS2 целевой SIM через новое соединение. Успех записи не равен успеху
|
||||
подключения. Отсутствие ответа после записи оставляет неопределённый результат;
|
||||
повтор записи или restart автоматически не запускается.
|
||||
|
||||
Оператор определяется по полученным кодам сети. APN и номер телефона не служат
|
||||
доказательством оператора. Неизвестный код остаётся неизвестным. Замена SIM не
|
||||
означает, что устройство или Core умеют определить корпоративный APN, пароль
|
||||
доступа и ограничения тарифа. Пока связи нет, VPS не может доставить по этому же
|
||||
каналу параметры для её восстановления. Локальный USB или независимо
|
||||
работающий SMS-канал — отдельные способы восстановления; SMS-инфраструктура
|
||||
в продукте не квалифицирована.
|
||||
|
||||
## Задержка состоит из разных этапов
|
||||
|
||||
Для принятого ранее перехода SIM1 → SIM2 исключительно через Core/VPS:
|
||||
|
||||
| Этап | Время |
|
||||
| --- | ---: |
|
||||
| Создание операции Core → создание на VPS | 0,733 с |
|
||||
| Создание Core → передача образа настроек | 26,486 с |
|
||||
| Создание Core → проверка образа и отправка restart | 45,053 с |
|
||||
| Restart → свежая целевая DS2 на новом соединении | 210,044 с |
|
||||
| Полная операция | 255,097 с |
|
||||
|
||||
Последние 210 секунд нельзя называть временем регистрации модема: туда могут
|
||||
входить повторные соединения, доставка накопленных сообщений и ожидание свежего
|
||||
подтверждения. Предыдущий USB-опыт с restart дал около 79 секунд, но это другая
|
||||
процедура, а не доказательство постоянного ускорения. Набора для p95/p99 нет.
|
||||
|
||||
В настройках введены две паузы по 15 секунд между обменами полным образом:
|
||||
ранние испытания без них теряли последующий запрос. Они не относятся к
|
||||
обычным командам позиции/выходов. Уменьшение пауз требует отдельного сравнения
|
||||
долей успешных операций; просто убрать ожидание — не установленная оптимизация.
|
||||
|
||||
## Исследование сбоя 27 сентября
|
||||
|
||||
Приватная сессия `communication-limits-69cdaddac9c74079b059d8115a2d62aa`.
|
||||
Исходный обрыв существовал до эксперимента. USB подтвердил ровно принятый
|
||||
образ SIM2: 207 записей, 983 байта; параметры не потерялись.
|
||||
|
||||
Одновременная пассивная запись USB и VPS установила:
|
||||
|
||||
- B2 повторно открывал TCP и отправлял одинаковый пакет №13 с семью старыми
|
||||
измерениями; это не свежая телеметрия, несмотря на новые подключения.
|
||||
- VPS формировал четырёхбайтовый ответ за 3,123–3,866 мс после получения пакета.
|
||||
- В трёх случаях после ответа приходил RST+ACK через 9,013–10,370 мс.
|
||||
TTL обычных входящих пакетов был 117, а RST — 40–42; различался также IP ID.
|
||||
- Девятибайтовые ответы на заголовок точно найдены в USB-потоке модема.
|
||||
Подтверждения пакета №13 в этом потоке не найдены. RST+ACK нельзя засчитывать
|
||||
как нормальное подтверждение доставки данных.
|
||||
|
||||
**Вывод ограничен:** видны сбросы на транспортном пути и застрявшая очередь.
|
||||
Признаки совместимы с вмешательством промежуточного оборудования. Они не
|
||||
идентифицируют виновника, не доказывают фильтрацию конкретным оператором и
|
||||
не доказывают ошибку прошивки. Проверка с другим путём/оператором/портом должна
|
||||
сохранять те же байты протокола и сопоставимые условия.
|
||||
|
||||
Один запрос позиции на исходном соединении был отправлен, но не подтверждён.
|
||||
Затем выполнено отдельное USB-восстановление: изменено только поле 72 на SIM1,
|
||||
сохранены APN и остальные 206 записей, выполнен один квалифицированный restart.
|
||||
Это не приёмка обратного переключения через VPS.
|
||||
|
||||
После восстановления поток продолжился, сначала выгружая старые измерения SIM2,
|
||||
затем появились свежие SIM1/GPRS. Поэтому нужно различать время поступления,
|
||||
время измерения и текущую активную SIM. От USB-restart до первого наблюдаемого
|
||||
`online` прошло 80,416 с, но возраст последнего измерения тогда составлял
|
||||
1526,508 с. SIM1 впервые появилась через 213,259 с; свежая SIM1 с возрастом
|
||||
меньше 30 с — через 234,371 с. Это времена опросного наблюдения Core, а не
|
||||
точные моменты регистрации в сотовой сети. USB-проверка точного образа прошла;
|
||||
аппаратные идентификаторы сохранились. Проверка полного объекта identity дала
|
||||
отказ: сообщаемая строка SIM1 изменилась с 12 на 20 символов. Это наблюдение
|
||||
модема, а не основание объявлять замену оборудования; исходный отказ сохранён.
|
||||
|
||||
На SIM1 выполнены три отдельных запроса позиции: при выгрузке очереди, после
|
||||
появления свежей DS2 и с одновременной записью USB/PCAP. Все три остались
|
||||
`unconfirmed`. Очередь VPS составила 6,327; 6,525 и 5,560 мс соответственно.
|
||||
В последнем опыте двенадцатибайтовый кадр команды виден на выходе VPS и его
|
||||
TCP-повторы продолжались, однако нормального TCP ACK и точного кадра в
|
||||
USB-потоке за окно наблюдения не было. Это не измерение времени исполнения
|
||||
команды: её доставка не подтверждена. Предыдущий успешный ответ за 1,66 с
|
||||
не превращается в гарантию на основании одной удачной попытки.
|
||||
|
||||
В двух пассивных окнах SIM1 после восстановления входящих RST не наблюдалось,
|
||||
пакеты телеметрии продвигались. Условия и время различались; этого недостаточно
|
||||
для вывода «МегаФон всегда работает, МТС всегда неисправен».
|
||||
|
||||
Обнаружено дополнительное ограничение тайм-аута: 30 с сейчас ограничивают
|
||||
**ожидание результата в приложении**, а не срок жизни уже переданных ядру TCP
|
||||
байтов. В PCAP повторная передача была видна и после этого срока. Поэтому
|
||||
текущая версия не обеспечивает жёсткую отмену запоздавшей команды. Даже
|
||||
закрытие сокета не отменяет действие, уже принятое устройством. Для дальнейшей
|
||||
квалификации требуются ограничение неподтверждённых TCP-данных, явная семантика
|
||||
неопределённого исхода и, где это поддерживает устройство, срок действия самой
|
||||
команды. Автоматически повторять воздействия после тайм-аута нельзя.
|
||||
|
||||
В конце опыта Core прочитал USB-снимок и сохранил соответствующий выбор SIM1.
|
||||
Перед проверкой применения вычисленный полный образ сравнен с фактическим;
|
||||
он уже совпадал. Штатная проверка вернула `unchanged`: дополнительной записи
|
||||
или перезапуска не произошло. Свежая DS2 подтвердила SIM1/GPRS. Настройки
|
||||
обеих APN остались исходными. Продуктовый код и VPS 0.1.24 не изменялись.
|
||||
|
||||
## Контроль без USB
|
||||
|
||||
Следующая сессия `network-only-278ac319e262481d971a22cd1b4480ef` выполнялась
|
||||
после исчезновения USB-интерфейса B2 из системного перечисления Mac. USB-порт
|
||||
не открывался. На SIM1 продолжали поступать свежие данные. Отправлен один
|
||||
`request-position`; конфигурация, выходы и перезапуск не затрагивались.
|
||||
|
||||
Команда получила `device_confirmed`, код 0. Очередь VPS — 4,374 мс,
|
||||
от отправки до подтверждения устройства — 1,320 с. Независимая запись TCP
|
||||
содержит ответ с совпадающим токеном через 1,314 с после кадра команды;
|
||||
в этом окне входящих RST не было. Это положительный контроль работоспособности
|
||||
команд без USB. Одна удачная попытка не доказывает, что USB был причиной
|
||||
предыдущих отказов, и не устанавливает верхнюю границу задержки.
|
||||
|
||||
Исправление тайм-аута должно охватывать сокет, а не только статус операции.
|
||||
[Linux TCP_USER_TIMEOUT](https://man7.org/linux/man-pages/man7/tcp.7.html)
|
||||
ограничивает время неподтверждённых данных конкретного TCP-соединения.
|
||||
Обычное [asyncio close](https://docs.python.org/3/library/asyncio-protocol.html#asyncio.BaseTransport.close)
|
||||
предусматривает отправку буфера при закрытии; его нельзя считать отменой.
|
||||
Критерии исправления: прекращение передачи на принятой ОС, отсутствие повтора
|
||||
команды на новом соединении и сохранение честного неопределённого результата.
|
||||
Проверка выпуска 0.1.25 описана ниже.
|
||||
Принятое B2 действие закрытием сокета отменить нельзя. В этой сессии настройки
|
||||
сокетов и продуктовый код не менялись.
|
||||
|
||||
## Ограничения нашего сервера
|
||||
|
||||
Установлены чтением кода 0.1.25, а не нагрузочным испытанием:
|
||||
|
||||
| Механизм | Текущее ограничение | Следствие |
|
||||
| --- | --- | --- |
|
||||
| TCP receiver | 256 одновременных соединений | Это не 256 устройств: один B2 может открыть несколько соединений, включая конфигурацию. Тысяча устройств не квалифицирована. |
|
||||
| Приём пакетов | 180 с без чтения закрывают соединение | Длинная стоянка/сон и интервалы требуют проверки. |
|
||||
| Диск | Журнал 512 MiB, резерв свободного места 256 MiB | При заполнении применяется обратное давление; нельзя обещать неограниченное хранение. |
|
||||
| Команды | Одна незавершённая операция на устройство | Массовые изменения должны иметь очередь по устройствам. |
|
||||
| Обычные действия | 3 с на начало отправки, 30 с на ожидание подтверждения | С 0.1.25 очередь сокета обрывается по сроку. Уже принятые трекером или находящиеся в сети данные отменить нельзя. |
|
||||
| Полная конфигурация / SIM | 180 / 360 с на VPS | Истечение срока не означает откат уже переданного образа. |
|
||||
| Проверка образов | Корреляция IMEI, peer IP, модели, CRC | Это не криптографическое удостоверение B2; разные CGNAT-адреса двух сокетов пока не квалифицированы. |
|
||||
| Core ↔ VPS | Аутентификация и закреплённый TLS-сертификат | Не распространяется автоматически на legacy INTERNAL B2 ↔ VPS. |
|
||||
|
||||
## Очерёдность дальнейшей работы
|
||||
|
||||
1. Довести наблюдаемость доставки: очередь → запись в сокет → TCP-подтверждение
|
||||
без RST → подтверждение устройства → наблюдаемый результат. Для выхода
|
||||
отдельно различать логическое состояние и физический контакт реле.
|
||||
Граница TCP исправлена в 0.1.25 ниже; физический результат выходов и
|
||||
гарантированная задержка остаются отдельными вопросами.
|
||||
2. Сравнить пути связи одинаковыми командами и одновременными USB/PCAP-данными.
|
||||
Сначала устранить устойчивый сбой обмена; затем измерять серию задержек.
|
||||
3. Квалифицировать оба направления SIM через сеть и отдельно отсутствие
|
||||
интернета у выбранной SIM. Возврат с USB не выдавать за автоматический резерв.
|
||||
До доказанного локального fallback не обещать удалённое восстановление из
|
||||
полного отсутствия связи.
|
||||
4. Исследовать ускорение свежего статуса при выгрузке архива и допустимость
|
||||
более коротких пауз конфигурации, не меняя критерий успешной записи.
|
||||
5. Проверить точную спецификацию и совместимость следующей прошивки до
|
||||
отдельного испытания. Обновление не является гарантированным откатом:
|
||||
сохранённый файл прошивки сам по себе ещё не доказывает рабочий downgrade.
|
||||
6. Масштабирование выполнять на серверном стенде: лимиты сокетов, несколько
|
||||
соединений на устройство, очереди, диск, восстановление процесса и массовые
|
||||
переподключения. На операторском Mac нагрузочные тесты не запускать.
|
||||
|
||||
Автономия от кабинета ARNavi для уже принятого тракта связи возможна и частично
|
||||
проверена. Полная автономия жизненного цикла, надёжный резерв SIM и гарантия
|
||||
быстрых команд пока не приняты. Если задача требует жёсткого времени реакции
|
||||
на геозону, проектировать локальную логику на борту; наличие такой произвольной
|
||||
логики в B2 данным исследованием не подтверждено.
|
||||
|
||||
## Проверенная граница доставки в VPS Host 0.1.25
|
||||
|
||||
Сессия выпуска `delivery-a8d26be666ec4dd182f46a4db8d0c566`, 27.09.2026.
|
||||
Командный кадр имеет монотонный срок: не позже завершения операции и не
|
||||
дольше 30 секунд после отправки. Для HTTP-ответа с настройками предел —
|
||||
12 секунд, также ограниченный сроком операции. Watchdog учитывает обе очереди:
|
||||
пользовательский буфер asyncio и неподтверждённые байты Linux `TIOCOUTQ`.
|
||||
Временная граница снимается с конкретного кадра после TCP-подтверждения;
|
||||
это **не** меняет результат команды на «выполнено».
|
||||
|
||||
При истечении срока соединение закрывается с `SO_LINGER={1,0}` и
|
||||
`transport.abort()`. Тот же режим действует при разрыве соединения и остановке
|
||||
обработчика. Поэтому уже закрытый сокет не продолжает отправлять его старую
|
||||
очередь. Дополнительно включён per-socket `TCP_USER_TIMEOUT=30000`, без
|
||||
изменения системных настроек Linux. Семантика аварийного закрытия и очистки
|
||||
очередей проверена по [исходнику Linux TCP](https://github.com/torvalds/linux/blob/v6.8/net/ipv4/tcp.c).
|
||||
|
||||
Встроенная в артефакт `qualify_delivery.py` проверка на Linux 6.8.0-137-generic
|
||||
использовала два локальных соединения, без B2, firewall и изменения служб:
|
||||
|
||||
- Подтверждённые TCP 12 байт без ответа приложения: соединение остаётся открытым.
|
||||
- Заблокированный получатель: перед сроком 2304 байта оставались в ядре,
|
||||
62080 — в asyncio. При тестовом сроке 0,750 с аварийное закрытие произошло
|
||||
за 0,751091 с; клиент получил reset, дескриптор сервера закрыт.
|
||||
|
||||
На настоящем B2 без USB выполнен отдельный запрос координат — сессия
|
||||
`network-only-b5c513eb06da42d599fb515e66b8a83d`. Очередь VPS заняла 4,791 мс.
|
||||
TCP-подтверждения команды не было; запись содержит отправку и повторения на
|
||||
1,360 / 4,750 / 11,854 / 25,678 секунды. Исходящий reset произошёл на
|
||||
29,994 секунды после первого кадра, около границы 30 секунд от создания
|
||||
операции. В 45-секундной записи нет кадров этой команды после срока и нет
|
||||
её переноса на другое соединение. Результат — `unconfirmed`; интерфейс
|
||||
снял ожидание и снова разрешил действия. Телеметрия B2 продолжила поступать.
|
||||
|
||||
Первый контрольный запрос сразу после обновления не появился в журнале
|
||||
команд VPS, а Core завершил его как `uncertain`. Он не повторялся. Неудачная
|
||||
попытка и её частичная запись сохранены в
|
||||
`network-only-0e6ee734cd8c436eae6e4984e154ba63`; это не измерение успешной доставки.
|
||||
|
||||
154 целевых backend-теста (153 общим проходом и один добавленный тест срока
|
||||
HTTP отдельно), 1004 frontend-теста, архитектурные проверки, typecheck и
|
||||
production build прошли. Две сборки установщика совпали побайтно. Версия
|
||||
0.1.25 установлена штатным установщиком, четыре файла идентичности/ключей
|
||||
сохранили SHA-256, загрузка этой же сборки опубликована в Mission Core.
|
||||
Настройки B2, SIM и бортовой Node в этом изменении не записывались.
|
||||
|
||||
Ограничение: это прекращение **дальнейшей передачи сервером**, а не отмена
|
||||
команды, уже принятой трекером или находящейся в сети. Это не система жёсткого
|
||||
реального времени: задержка event loop/ОС остаётся возможной. Работа обратного
|
||||
мобильного канала и задержка физического исполнения по-прежнему не гарантированы.
|
||||
|
||||
## Сравнение помещения и улицы
|
||||
|
||||
[Полный отчёт от 27.09.2026](INDOOR_OUTDOOR_COMPARISON_20260927.md): после переноса
|
||||
и подключения USB спутников стало 14–16 вместо 8, показатель активной SIM1 —
|
||||
20–22 вместо 16. Пять отдельных запросов позиции на VPS 0.1.25 подтверждены
|
||||
B2 за 0,519–1,105 с; медиана 0,604 с. Во всех пяти сетевых записях команд
|
||||
проверены контрольная сумма, токен ответа и код 0; повторных передач не было.
|
||||
USB serial не использовался, настройки и выходы не менялись. Это совместное
|
||||
изменение места/USB/возможного питания, а не изолированное доказательство
|
||||
влияния улицы. Пропускная способность, долговременная надёжность и непрерывность
|
||||
питания этим опытом не установлены.
|
||||
|
||||
## Возврат в помещение и runtime 0.1.26
|
||||
|
||||
На той же 0.1.25 после возврата подтверждены 5/5 запросов: 1,191–2,264 с,
|
||||
медиана 1,677 с; спутники 14–17, SIM1 15–22. Один TCP-повтор команды завершился
|
||||
подтверждением. После обновления 0.1.26 ещё 3/3 запроса подтверждены за
|
||||
0,887–2,224 с; повтор каждого запроса к Core сохранил исходный ID и не создал
|
||||
вторую команду. Уличная медиана 0,604 с меньше комнатной, но роль питания,
|
||||
времени и радиоканала по этим сериям не разделена.
|
||||
|
||||
[Контракт runtime](WEAK_LINK_RUNTIME.md) описывает долговечную исходящую очередь
|
||||
Core, дедупликацию, исходный срок действия, ожидание соединения для чтения и
|
||||
отсутствие повтора неопределённых воздействий. Индекс активных операций и
|
||||
пробуждение по событиям уменьшают работу сервера без команд. Это не расширение
|
||||
физических возможностей 2G, не автоматический резерв SIM и не приёмка тысячи
|
||||
трекеров. Все следующие аппаратные испытания — в помещении.
|
||||
@@ -0,0 +1,132 @@
|
||||
# B2 configuration clock and session freshness — 2026-09-27
|
||||
|
||||
## Current result
|
||||
|
||||
VPS Host **0.1.29** is installed and published in Mission Core. The same qualified
|
||||
installer can reproduce the deployed code. The host now answers the observed
|
||||
configuration clock request itself and defers configuration dispatch on silent
|
||||
monitoring streams. This closes two concrete protocol/transport gaps. It does
|
||||
**not** establish reliable remote configuration or complete vendor independence.
|
||||
|
||||
A physical write reached the B2 and changed only field 25 from 15 to 16 seconds.
|
||||
The device then stopped communicating with the VPS; verification could not be
|
||||
sent before the operation expired. A fresh USB read established that the change
|
||||
had actually applied. One qualified USB restoration and an independent full read
|
||||
restored the exact 207-record / 983-byte baseline at **14:48:32 UTC**. Core's cache
|
||||
was reconciled without rewriting the failed network history. Network recovery
|
||||
after this write remains a separate acceptance gate.
|
||||
|
||||
## Reference-qualified clock response
|
||||
|
||||
Two owner-authorized bounded diagnostic exchanges sent the same captured
|
||||
20-byte opcode-7 request to the manufacturer's configuration endpoint. They
|
||||
contained identity/model/firmware/request code, not configuration, passwords,
|
||||
SIM data or coordinates. The replies were ten bytes:
|
||||
|
||||
`5b 0006 00 07 <Unix UTC seconds:u32be> 5d`
|
||||
|
||||
The four-byte value fell between each request's wall-clock start/end and advanced
|
||||
by 36 seconds between exchanges. Host 0.1.28 introduced a dynamic response from
|
||||
its own synchronized clock. It never replays the reference timestamp. An admitted
|
||||
model-231/0.01 identity and active matching modem peer are required. This response
|
||||
cannot advance or confirm a configuration transaction or extend its deadline.
|
||||
|
||||
The owned runtime makes no manufacturer calls. Reference queries are engineering
|
||||
qualification, not a dependency of the product. Two repeated clock exchanges on
|
||||
one real Linux loopback HTTP connection passed in isolated state. Physical
|
||||
traffic subsequently showed the B2's opcode-7 request and our matching response.
|
||||
That observation is not proof that every firmware clock/startup path is covered.
|
||||
|
||||
## Physical sequence and remaining limits
|
||||
|
||||
| Phase | Observation | What it establishes |
|
||||
| --- | --- | --- |
|
||||
| First read on 0.1.28 | Expired after 180.757 s; B2 requested opcode 2 instead of uploading | No settings image was sent by this read |
|
||||
| Bounded recovery exchange | Fresh USB image matched baseline; one unchanged image served after an explicit download request | One intentional engineering write, not a normal automatic retry |
|
||||
| Following exchange | Opcode 6, full opcode-5 upload and opcode-7 time exchange | The owned clock response worked on the physical dialogue |
|
||||
| Independent network read | Exact baseline in 6.022 s | A fresh full read succeeded |
|
||||
| Repeated 0.1.28 read | No TCP ACK for the command; six TCP transmissions, abort at 29.999 s; operation ended at 180.718 s | A drained old socket was still unusable; retransmission here was TCP, not application replay |
|
||||
| First 0.1.29 read | Waited for fresh input; exact baseline received in 24.119 s total | Freshness admission worked on one physical read |
|
||||
| 0.1.29 write | Fresh preflight, one download request, one image response | Three commands individually TCP-acknowledged in 0.657, 0.550 and 1.231 s |
|
||||
| Image delivery | Complete 989-byte response body TCP-acknowledged after 1.011 s | Transport delivery; not sufficient alone to confirm application |
|
||||
| Write verification | No fresh monitoring input after download; operation ended uncertain in verify at 180.927 s | No automatic replay and no false successful application |
|
||||
| Independent USB inspection | Field 25 = 16; other 206 records unchanged | This network write actually applied |
|
||||
| USB restoration | Field 25 = 15, exact independent readback | Baseline restored; remote restoration did not pass |
|
||||
|
||||
Only one physical tracker, model 231 / firmware 0.01, was used indoors with 12 V
|
||||
and USB connected. No USB serial operation ran during the timed network phases.
|
||||
These observations do not isolate RF quality, two-SIM behavior, USB electrical
|
||||
stability, firmware configuration reload or carrier transport. They are not a
|
||||
latency guarantee or a fleet-scale reliability result. The recovery lease is
|
||||
explicit engineering tooling and is not an automatic production recovery path.
|
||||
|
||||
## Freshness admission in 0.1.29
|
||||
|
||||
The previous Linux guard required no queued asyncio/kernel bytes. A silent
|
||||
connection can satisfy that check while its cellular path has already failed.
|
||||
Configuration commands now additionally require input from the B2 within five
|
||||
monotonic seconds. Otherwise they remain queued until new device input arrives
|
||||
or their original operation deadline expires. Among eligible drained streams,
|
||||
the most recently active one still wins. The five-second bound is a conservative
|
||||
admission policy, not a documented modem guarantee. Position/output policy is
|
||||
unchanged. Dispatched stages and images are never automatically replayed.
|
||||
|
||||
The physical three-command sample dispatched about 1.01 seconds after incoming
|
||||
telemetry and got TCP acknowledgements without retransmission. This is a narrow
|
||||
positive observation; it did not solve post-write reconnection.
|
||||
|
||||
Core also now retains VPS creation and stage-dispatch timestamps for full
|
||||
configuration operations. Each distinct dispatch timestamp enters the journal
|
||||
once; repeated status polling does not duplicate it. Confirmed verification time
|
||||
has its own evidence event. Invalid/non-finite timestamps and private payloads
|
||||
are excluded. Historical entries without these facts are not fabricated.
|
||||
|
||||
## Release validation and evidence
|
||||
|
||||
- Installer SHA-256: `c6637e2578c48771b65aae28e2754b5386fa125e2ae416df1c59824f3e62acd7`.
|
||||
- Two builds produced identical installer/tar/manifest hashes. All 23 installed
|
||||
manifest files match the artifact. All four identity files were preserved;
|
||||
state backups precede installation. VPS time synchronization was checked.
|
||||
- Focused VPS/Core/protocol tests and Ruff passed; frontend typecheck/build
|
||||
passed. Configuration-timeline regression tests passed separately.
|
||||
- Artifact-owned isolated Linux delivery, durable runtime, six fault scenarios,
|
||||
HTTP clock and fresh-packet wakeup checks passed. The new wakeup scenario uses
|
||||
a real loopback telemetry frame and verifies one command dispatch with an
|
||||
unchanged expiry. No physical tracker or production journal is used by it.
|
||||
- An initial 0.1.29 qualifier candidate used the wrong expected package ACK in
|
||||
its test harness. It failed and was not installed. The corrected final artifact
|
||||
passed. The same principle applies to the earlier rejected 0.1.28 harness.
|
||||
- Browser QA on canonical port 8000 showed the real command history and current
|
||||
pending/terminal operations. No onboard Node update or relay action occurred.
|
||||
|
||||
Private sessions: `clock-8a29efb2006e4744a86a5d046839fe81`, its
|
||||
`reconcile-351ce7ef505b4547a53d3c805415253c` child,
|
||||
`clock-roundtrip-*`, and `fresh-31bf7b0ede4f4fe1808508c51b56a873`.
|
||||
Raw traffic, device identity, SIM values, complete images and state backups remain
|
||||
in ignored owner storage. Hash manifests preserve UTC/monotonic times and scope.
|
||||
The 0.1.29 capture ended after the failed operation when Core was deliberately
|
||||
reloaded for the journal fix; it must not be described as a complete 360-second
|
||||
capture. A separate bounded recording covers the requested hardware recovery.
|
||||
|
||||
## Next acceptance gates
|
||||
|
||||
1. Explain and qualify post-image-write reconnection, including startup HTTP
|
||||
exchanges and modem return. Confirm recovery without USB, not merely a write.
|
||||
2. Repeat complete read → one-field write → readback → restoration → independent
|
||||
read cycles, including controlled outages and host restart, with honest
|
||||
uncertain outcomes and no replay of dispatched effects.
|
||||
3. Separate persisted one-shot SIM activation from reusable desired settings;
|
||||
verify unchanged APN/identity handling on unrelated edits.
|
||||
4. Complete the factory-fresh bootstrap and remaining configuration categories
|
||||
listed in [the coverage audit](CONFIGURATION_COVERAGE_20260927.md).
|
||||
|
||||
## Handoff state
|
||||
|
||||
The final download checksum matched the installed 0.1.29 artifact. Core remains
|
||||
on port 8000 with no listener on 8765 and no pending outbox command. The browser
|
||||
shows VPS 0.1.29 online and the B2 last packet at 14:43:23 UTC. A six-minute bounded
|
||||
recovery observation ended while awaiting the operator power-cycle confirmation;
|
||||
no completed physical cycle or network recovery is claimed. The original image
|
||||
is independently restored and both USB descriptors and temporary captures are
|
||||
closed. Continue with the operator-confirmed power cycle, then inspect actual
|
||||
network return and configuration before any further write.
|
||||
@@ -0,0 +1,137 @@
|
||||
# B2 configuration coverage and recovery audit — 2026-09-27
|
||||
|
||||
The owner's target is independent admission, telemetry, settings and commands
|
||||
through the owner's VPS. A complete image transport is necessary, but does not
|
||||
by itself qualify every setting, accessory or firmware operation.
|
||||
|
||||
## Evidence and scope
|
||||
|
||||
One physical B2, model 231 / firmware 0.01, VPS Host 0.1.26, canonical Mission
|
||||
Core, indoor operation on 12 V. No USB serial access, manufacturer device
|
||||
requests, firmware changes or output actuation in this audit.
|
||||
|
||||
The initial fresh network read returned **207 records / 983 bytes in 6.018 s**,
|
||||
identical to the retained baseline. The scalar profile overlay, without edits,
|
||||
reproduces all bytes exactly. Monitoring slots 1 and 2 and configuration fields
|
||||
70/71 point to the owner receiver; monitoring slots 3 and 4 are disabled.
|
||||
These are configuration facts, not a claim about all possible firmware traffic.
|
||||
|
||||
The public model-231 configurator schema contains 12 sections. Its newer default
|
||||
values are not a source of missing device settings. Eight catalogued GNSS filter
|
||||
parameters (241–248) are absent on this physical firmware. Five present records
|
||||
(70, 71, 135, 136, 138) are absent from that public UI schema; the configuration
|
||||
endpoint semantics for 70/71 were qualified separately.
|
||||
|
||||
## What is editable today
|
||||
|
||||
The portable catalog has 86 scalar definitions; **78 occur with supported widths
|
||||
in this device image**. There are no incompatible-width catalogued records in
|
||||
this sample. This count is parser/editor coverage, not 78 physical write tests.
|
||||
|
||||
| Manufacturer section | Present records | Portable scalars | Separate handling | Preserved, not fully edited |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| Monitoring servers | 20 | 0 | 12 | 8 |
|
||||
| Packet composition | 1 | 0 | 0 | 1 |
|
||||
| Track generation | 13 | 12 | 1 | 0 |
|
||||
| Inputs and outputs | 12 | 0 | 0 | 12 |
|
||||
| Digital ports | 22 | 0 | 1 | 21 |
|
||||
| Modbus | 16 | 0 | 0 | 16 |
|
||||
| BLE sensors | 22 | 0 | 0 | 22 |
|
||||
| Driving quality | 68 | 66 | 0 | 2 |
|
||||
| Phone numbers | 10 | 0 | 0 | 10 |
|
||||
| SIM settings | 15 | 0 | 7 | 8 |
|
||||
| Navigation | 1 | 0 | 0 | 1 |
|
||||
| System modes | 6 | 0 | 1 | 5 |
|
||||
|
||||
Rows can overlap a shared bitfield; do not add the columns as unique-record
|
||||
totals. “Separate handling” means endpoint/APN handling or only selected bits of
|
||||
record 72. It is not full-section support. Unique identifiers, phone numbers,
|
||||
device passwords, sensor addresses and SIM credentials must not become generic
|
||||
portable profile defaults.
|
||||
|
||||
The offline checker is
|
||||
`k1link.device_plugins.arnavi_b2.configuration_audit`. It reports record IDs,
|
||||
counts, hashes, overlay compatibility and destination classifications. It never
|
||||
prints configuration values, contacts a service or synthesizes missing fields.
|
||||
Its reference input is the cached [public model schema](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations).
|
||||
The hardware command reference remains the manufacturer's
|
||||
[B2 documentation directory](https://8888.arusnavi.ru/Arnavi%20B2/), especially
|
||||
manual sections 9–10. Neither source authorizes unqualified binary writes.
|
||||
|
||||
## Physical transaction results
|
||||
|
||||
- Field 25, stationary interval: **15 → 16 seconds verified in 48.276 s**.
|
||||
The other 206 records remained byte-identical.
|
||||
- First return to 15: expired unconfirmed at the write-request stage after
|
||||
361.928 s. The VPS never served the target image and never dispatched the
|
||||
subsequent SIM restart. A separate 6.026 s network read found **16**, not 15.
|
||||
- An explicit second restoration, with SIM activation removed from that
|
||||
transaction, expired in preflight after 180.735 s. No image was served.
|
||||
- A bounded receiver capture shows the preflight command retransmitted by TCP
|
||||
while other telemetry sessions remained active. Application success cannot
|
||||
be inferred from online status or from writing bytes into a socket.
|
||||
|
||||
- One separate restart request was followed by fresh telemetry on a new TCP
|
||||
connection after 12.299 s (`reconnected`). This is connection evidence, not
|
||||
proof of a CPU restart. The subsequent full read expired in preflight after
|
||||
180.750 s without a new image.
|
||||
|
||||
**Recovery completed through USB at 14:03:28 UTC.** The owner confirmed all
|
||||
indicators off, ten seconds without power, then 12 V only. The first subsequent
|
||||
network read returned field 25 = 16 in 15.039 s. Two explicit restoration attempts
|
||||
still expired: 180.824 s in preflight, then 180.889 s at the write-request stage.
|
||||
Neither served an image. Power cycling did not resolve remote configuration.
|
||||
|
||||
The subsequently installed Host 0.1.27 adds outbound transport readiness checks.
|
||||
Its restoration attempt obtained a fresh predecessor image, but expired after
|
||||
180.864 s at the write-request stage without serving an image. TCP acknowledged
|
||||
the download command after 0.723 s; no corresponding image request arrived.
|
||||
See [the bounded readiness qualification](OUTBOUND_READINESS_20260927.md).
|
||||
|
||||
After the owner connected USB, a new identity-bracketed read found exactly the
|
||||
test image: only field 25 differed from the baseline. One qualified USB write
|
||||
restored 15. Its readback and a separate full read matched all 207 original
|
||||
records byte for byte. Core subsequently reread the hardware through its USB
|
||||
inspection API and retained the failed network receipt. Desired settings remain
|
||||
original; no operation is pending. This is **USB recovery**, not acceptance of
|
||||
the remote write/read/restart roundtrip.
|
||||
|
||||
## Product findings and next acceptance gates
|
||||
|
||||
1. Fixed the USB bootstrap's stale version allowlist: shipped VPS 0.1.26 was
|
||||
rejected even though its qualified provisioning protocol is unchanged. A
|
||||
regression checks the shipped artifact version; unknown versions still
|
||||
fail closed. This is synthetic bootstrap admission acceptance, not a new
|
||||
factory-fresh hardware run.
|
||||
2. Saved `connectivity.activate` is persistent intent. Editing an unrelated
|
||||
profile field can therefore start a `select-sim` transaction and an extra
|
||||
restart. Separate the one-time activation action from desired configuration,
|
||||
including live-SIM confirmation and recovery of previously applied flags.
|
||||
Do not fix this by assuming matching stored flags prove the selected modem
|
||||
SIM already changed.
|
||||
3. Settings recovery still needs physical qualification. Distinguish read
|
||||
request, image served, independent readback and reconnection. Preserve the
|
||||
original deadline and history. Never turn an uncertain image write into an
|
||||
automatic repeated write or silently replay actuation on another session.
|
||||
4. Only after the recovery gate, extend the editor with validated per-field
|
||||
schemas and readback acceptance for system/packet settings, I/O and digital
|
||||
ports, then Modbus and BLE. Accessory function needs a known wiring fixture;
|
||||
image readback cannot prove relay, CAN or sensor behavior.
|
||||
|
||||
Evidence session: `configuration-audit-874d3d549dbd41e9a258412c676af6ac` under
|
||||
ignored private outputs. Raw images, identifiers, traffic and credentials remain
|
||||
private. Redacted manifests include UTC/monotonic times and artifact SHA-256.
|
||||
|
||||
Initial audit validation: 115 focused backend tests passed; Ruff passed for the bootstrap and
|
||||
audit modules/tests. The canonical Core service was reloaded through its managed
|
||||
LaunchAgent after consistent SQLite backups; its health was accepted. No VPS
|
||||
code/installer or frontend change belonged to that initial audit. The subsequent
|
||||
0.1.27 release and recovery checks are recorded in the linked qualification.
|
||||
|
||||
## Subsequent 0.1.29 qualification
|
||||
|
||||
The [clock/freshness follow-up](CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md)
|
||||
records two reference clock requests, owned time handling, fresh-stream admission
|
||||
and a further applied physical write with failed post-write network return.
|
||||
USB independently restored the exact 207-record baseline at 14:48:32 UTC.
|
||||
This adds protocol coverage, not general remote-configuration acceptance.
|
||||
@@ -0,0 +1,105 @@
|
||||
# Две SIM: идентичность, перестановка и связь, 2026-09-28
|
||||
|
||||
Сессия: `dual-sim-identity-e81e0384e86d442dbda64636d8dbd563`.
|
||||
Тот же B2, модель 231, прошивка 0.01; ранее испытанная МТС и предоставленная
|
||||
владельцем МегаФон. Все перестановки выполнены владельцем при отключённых
|
||||
12 В и USB, затем подключались 12 В и USB для пассивной записи запуска.
|
||||
|
||||
## Результат двух расстановок
|
||||
|
||||
| Расстановка | Идентификация в потоке запуска | Свежая связь с VPS |
|
||||
| --- | --- | --- |
|
||||
| МегаФон — SIM 1, МТС — SIM 2 | Два различных CCID/IMSI; домашние коды 25002 / 25001 привязаны к соответствующим слотам | SIM 1, МегаФон; в модем передан сохранённый APN `internet` |
|
||||
| МТС — SIM 1, МегаФон — SIM 2 | Сырые CCID, IMSI и SID из потока запуска совпали с прежними картами и переместились в новые слоты; домашние коды 25001 / 25002 | SIM 2, МегаФон; в модем передан сохранённый APN `internet.mts.ru` |
|
||||
|
||||
В обеих расстановках VPS получил свежие коды сетей обеих карт. После обмена
|
||||
один запрос координат через Core → VPS → B2 подтверждён устройством с первой
|
||||
попытки: код 0, `device_confirmed`, **0,999 секунды** от отправки VPS до ответа.
|
||||
Создано 08:14:03.157 UTC, отправлено 08:14:03.198, подтверждено 08:14:04.197.
|
||||
Это одиночный контрольный запрос, не оценка гарантированной задержки.
|
||||
|
||||
Конфигурация оставалась прежней во всех трёх штатных чтениях: 207 записей,
|
||||
983 байта, SHA-256
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
Мы не записывали APN, прошивку или выходы и не выбирали активную SIM командой.
|
||||
После обмена карточек B2 не перенёс сохранённые APN вслед за ними.
|
||||
|
||||
Успешный выход через эту МегаФон с APN `internet.mts.ru` не означает, что такой
|
||||
APN подходит всем картам оператора, и не доказывает автоматический подбор APN
|
||||
прошивкой. Причина допуска этого подключения оператором не установлена.
|
||||
В этой сессии не проверялся выход МТС через первый слот с её правильным APN.
|
||||
|
||||
## Важное ограничение штатного запроса идентичности
|
||||
|
||||
В потоке запуска обе карты выдавали SID длиной 20 цифр, а ответы внутреннего
|
||||
модема на `AT+CIMI` содержали разные 15-значные IMSI. После обмена картами
|
||||
совпадение подтверждено по хешам исходных ответов и соответствию слотам.
|
||||
Наш USB-наблюдатель не отправлял эти AT-команды: их посылала прошивка B2.
|
||||
|
||||
Однако штатное чтение `I 7`, обрамляющее чтение конфигурации, дало другой результат:
|
||||
|
||||
| Карты в слотах | SID0 при `I 7` | SID1 при `I 7` |
|
||||
| --- | --- | --- |
|
||||
| МегаФон / МТС | 12 цифр, не совпадает с исходным SID МегаФона | 20 цифр, совпадает с МТС |
|
||||
| МТС / МегаФон | 12 цифр, не совпадает с исходным SID МТС | 20 цифр, совпадает с SID МегаФона из запуска |
|
||||
| Повторное чтение без перестановки | Те же 12 цифр для МТС | Те же 20 цифр для МегаФона |
|
||||
|
||||
Оба запроса идентичности внутри каждого чтения согласовались друг с другом;
|
||||
проверены сами байты ответа, не только JSON-проекция. Короткие значения для
|
||||
разных карт различаются и не являются префиксом/суффиксом полных исходных SID.
|
||||
Нельзя объявить их полными ICCID или восстанавливать догадкой. Причина
|
||||
расхождения внутри B2 не установлена; повторное чтение не устранило её.
|
||||
|
||||
Ранее [одна МТС без второй карты](SIM_SLOT_IDENTITY_20260928.md) возвращала
|
||||
полный ICCID через тот же `I 7` в обоих слотах. Это существенная граница приёмки:
|
||||
успех с одной картой нельзя переносить на две одновременно установленные SIM.
|
||||
|
||||
## Разные формы номера МегаФона
|
||||
|
||||
Сырой ответ модема `AT+CCID` для этой МегаФон содержит 18 десятичных цифр и
|
||||
два символа `ff`. Следующий SID, сформированный B2, содержит 20 десятичных цифр:
|
||||
первые 18 совпадают, окончание отличается. Обе формы повторились после обмена
|
||||
слотами. У МТС сырой CCID и исходный SID совпадают полностью.
|
||||
|
||||
В доказательствах сохранены обе формы отдельно. Никакой нормализации `ff`,
|
||||
дополнения цифрами или вывода оператора по длине номера не выполнялось.
|
||||
Совпадение 20-значного SID само по себе не делает его каноническим ICCID.
|
||||
Данные операторов в этой проверке подтверждались IMSI/домашними кодами и
|
||||
свежими кодами обслуживающих сетей, независимо от настроенных APN.
|
||||
|
||||
## Метод, доказательства и завершение
|
||||
|
||||
Пассивная USB-запись: около 130,5 с / 20 205 байт в первой расстановке и
|
||||
170,1 с / 27 487 байт во второй. Настройки tty и явные линии управления модемом
|
||||
не менялись, наш наблюдатель в USB не писал. Затем выполнялись штатные
|
||||
ограниченные чтения продукта; третье чтение повторяло второе для проверки
|
||||
нового расхождения идентификатора.
|
||||
|
||||
Захват VPS ограничен 600 секундами, портом TCP 9922, снимком 96 байт:
|
||||
262 пакета захвачено, 262 получено фильтром, 0 потерь ядра. Контрольная команда
|
||||
после перестановки пришлась уже после окончания этого захвата; её доказательство —
|
||||
журнал операции/попыток VPS и свежая телеметрия, а не этот PCAP.
|
||||
|
||||
Сырые CCID, IMSI, SID, координаты, конфигурация, USB-потоки и пакеты сохраняются
|
||||
только в приватном каталоге сессии под `outputs/arnavi-b2/`, вне Git. Манифест
|
||||
содержит UTC/монотонные метки, заметки владельца и SHA-256 артефактов.
|
||||
Оба USB-наблюдателя завершены. Удалённый захват остановлен, хеш локальной копии
|
||||
сверен, временный каталог VPS удалён. Core на порту 8000 и сервис VPS работают.
|
||||
|
||||
Итоговая физическая расстановка: **МТС в первом слоте, МегаФон во втором,
|
||||
подключены 12 В и USB**. При завершении B2 передаёт свежие данные через SIM 2,
|
||||
МегаФон; возраст последнего пакета около 15 секунд, измерения — 20 секунд.
|
||||
|
||||
## Решение для дальнейшей реализации
|
||||
|
||||
Для этих двух карт подтверждены различение и привязка к слоту в потоке запуска,
|
||||
включая обмен слотами. Повторный штатный опрос не даёт столь же надёжного полного
|
||||
идентификатора первой SIM при двух картах. Для автоматического применения APN
|
||||
нельзя использовать правило «SID состоит из цифр — значит идентичность доказана».
|
||||
|
||||
Следующий этап должен сохранять источник, исходное представление, полноту,
|
||||
сеанс запуска и свежесть наблюдения; не позволять неполному отчёту подменять
|
||||
подтверждённую карту или переносить ожидающую запись на другую SIM. Получение
|
||||
достоверной идентичности вне потока запуска и канонизация форматов требуют
|
||||
отдельной квалификации. Автоматический подбор и запись APN этим опытом не
|
||||
реализованы; MVNO, корпоративные тарифы и другие SIM не испытывались.
|
||||
@@ -0,0 +1,74 @@
|
||||
# Durable B2 maintenance runtime — VPS Host 0.1.32
|
||||
|
||||
Scope: owner-authorized service operations ending at B2. No physical actuator,
|
||||
relay, pin-load or downstream sensor acceptance is claimed. The existing bounded
|
||||
pin-command transport was preserved; it is not automatically retried.
|
||||
|
||||
## Job and attempt ownership
|
||||
|
||||
Core accepts one immutable request ID into SQLite before HTTP and retains its
|
||||
outbox across restarts. On uncertain HTTP delivery it reads the VPS result first;
|
||||
only an absent/unavailable result permits resubmission of the same ID and body.
|
||||
The VPS owns a persistent job and distinct bounded transport attempts. Restart of
|
||||
Core or VPS and expiry of one attempt do not discard the job. Per-device FIFO
|
||||
capacity is 32. No new attempt is admitted without recent B2 input. Another
|
||||
tracker's job progresses independently. Retry delays grow from 5 to 300 seconds;
|
||||
idle channels sleep on events. Old completed/uncertain historical jobs are not
|
||||
silently replayed on upgrade.
|
||||
|
||||
Supported durable kinds: position request, restart, full configuration read,
|
||||
profile configuration write and SIM selection. The capability is negotiated;
|
||||
older hosts retain their bounded behavior. Device identity/firmware/assignment
|
||||
changes before dispatch are rejected explicitly. Permanent B2 argument/execution
|
||||
errors finish with a visible failure; code 7 (full B2 command queue) waits/retries.
|
||||
Code 6 remains intermediate; matching token/code 0 finishes a position command.
|
||||
|
||||
A configuration retry first reads the actual image. Target image = completed;
|
||||
unchanged predecessor = eligible for a fresh preflight and another write; any
|
||||
other image = explicit conflict, not overwrite. SIM recovery additionally needs
|
||||
fresh selected-slot/GPRS telemetry. A confirmed target SIM is not rebooted again.
|
||||
A restart with known code-0 acceptance and no return evidence finishes as
|
||||
`accepted`, distinct from `reconnected`; it is not repeated. If no receipt is
|
||||
available, the owner-authorized maintenance job can retry after recovery.
|
||||
|
||||
This is durable delivery with state reconciliation, not a claim of exactly-once
|
||||
physical execution. B2 has no demonstrated durable client-id deduplication. If
|
||||
both an effect and its response happened before a disconnect, a lost receipt may
|
||||
still make an unobservable effect ambiguous. Tracker acknowledgments establish
|
||||
only the tracker boundary. No network runtime can deliver while hardware has no
|
||||
power or the mobile network remains unreachable.
|
||||
|
||||
Stopping retries is persisted in Core and VPS. A pre-admission stop is a tombstone,
|
||||
so a delayed POST cannot revive the job. An already handed-off attempt can finish;
|
||||
the UI does not promise to undo it. Attempt rows are redacted and paged, with
|
||||
individual tokens retained only privately. UI shows counts, current attempt,
|
||||
responses, waiting/reconciliation and stop controls.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Session `durable-operations-a6b9b43aa22342e28d2d91a4afca9e41`.
|
||||
Installer SHA-256 `29ad94442210b9f6f399e2b2d0a0b9a3b3411a6ccb3cf5f43e922e7863e98eba`.
|
||||
|
||||
- 85 focused backend tests: durable and legacy paths, Core outage beyond one day,
|
||||
lost POST and restart, stale ACK removal, per-tracker isolation, crash before
|
||||
and after attempt admission, cancellation races, configuration target/old/
|
||||
divergent images, verified second write and SIM recovery without second reboot.
|
||||
- 135 VPS/installer checks passed, including loopback tests.
|
||||
- Shipped Ubuntu `qualify_operations.py` used actual isolated TCP/HTTP and SQLite:
|
||||
one job, two attempts across SIGKILL; old reply could not finish the new attempt;
|
||||
terminal result and stop-before-delayed-POST survived further SIGKILLs. All
|
||||
previous receipt/runtime/fault qualification also passed. No physical tracker
|
||||
or production database was used in those destructive process tests.
|
||||
- Versioned installer preserved four identity files, made a SQLite backup, and
|
||||
all 27 installed manifest files matched the accepted artifact. Core download
|
||||
carries that same artifact; onboard software was not updated.
|
||||
- Actual owner B2: two Core-issued position jobs confirmed in 1.136 s and 0.523 s,
|
||||
each with one persisted attempt. Core/VPS outcomes agreed. No physical settings,
|
||||
reboot, pin or USB serial commands were issued for this release.
|
||||
- Frontend architecture/typecheck, 1010 tests and production build passed. Real
|
||||
command history, per-attempt result and Escape checked on canonical port 8000.
|
||||
Existing bundle-size warning remains.
|
||||
|
||||
These tests do not qualify thousands-device throughput or resolve the separate
|
||||
USB/power/radio stall observed earlier. Full vendor-feature parity and factory
|
||||
bootstrap remain separate acceptance scopes; this release does not assert them.
|
||||
@@ -0,0 +1,107 @@
|
||||
# B2: обрывы и восстановление 27.09.2026
|
||||
|
||||
Сессия `fault-recovery-775a9eb9cb8d4707a225842eae8f0d5c`: один принадлежащий
|
||||
владельцу B2, модель 231, ПО 0.01, помещение. VPS 0.1.26 не обновлялся.
|
||||
Физические команды — только запросы позиции; реле, настройки, прошивка
|
||||
и бортовой Node не менялись.
|
||||
|
||||
## Физическое отключение
|
||||
|
||||
Владелец подтвердил снятие 12 В и USB и погасшие индикаторы. После прекращения
|
||||
пакетов Core показал отсутствие связи, сохранив экземпляр и привязку.
|
||||
Последняя позиция имела `position_fresh=false`.
|
||||
|
||||
Для исключения оставшегося TCP-сеанса запрос отправлен после более 190 секунд
|
||||
без пакетов (тайм-аут сеанса VPS — 180 секунд). Два HTTP POST с одним ID
|
||||
возвратили одну операцию. По журналу VPS запрос находился в очереди, истёк
|
||||
по исходному 30-секундному сроку и не имел `dispatched_at`.
|
||||
|
||||
После сигнала владелец включил 12 В без USB. B2 вернулся под прежним
|
||||
экземпляром, появились свежие данные. Новый запрос получил `device_confirmed`
|
||||
за **0,664 с** по измерению VPS. Старый остался истёкшим без отправки.
|
||||
Отдельный PCAP в этой серии не снимался; вывод опирается на журнал и
|
||||
протокольный результат. Исполнение выходов не проверялось.
|
||||
|
||||
Первый сборщик достиг 660-секундного предела в ожидании включения. Отметка
|
||||
тайм-аута сохранена. Сбор продолжен отдельным запуском с прежним ID и
|
||||
накопленными образцами; во время разрыва опроса новые команды не создавались.
|
||||
|
||||
## Изолированные сбои VPS
|
||||
|
||||
`apps/vps-host/qualify_faults.py` использует установленный `ndc_vps` без
|
||||
изменений, временную SQLite, локальные HTTP/TCP-порты и один синтетический B2
|
||||
последовательно. SHA-256 установленных модулей сверены с исходниками.
|
||||
Главный процесс боевого VPS, его база, TLS и firewall не менялись.
|
||||
Дочерний тестовый процесс аварийно завершается SIGKILL. Временные процессы
|
||||
и каталог убираются при завершении.
|
||||
|
||||
Пройдены шесть сценариев:
|
||||
|
||||
1. Потеря запроса до полного HTTP-тела: повтор с тем же ID.
|
||||
2. Потеря HTTP-ответа после принятия: авария, восстановление очереди,
|
||||
повтор исходного ID, один прикладной кадр позиции.
|
||||
3. Истечение срока без подключения: перезапуск не продлевает срок,
|
||||
поздний синтетический B2 не получает команду.
|
||||
4. TCP принимает байты, протокольного ответа нет: `unconfirmed`,
|
||||
после перезапуска и подключения команда не воспроизводится.
|
||||
5. Синтетическая команда выхода отправлена, затем авария: `uncertain`,
|
||||
без автоматического повтора.
|
||||
6. Новая команда после восстановления проходит; идентичность, история
|
||||
и целостность SQLite сохранены.
|
||||
|
||||
Серия заняла 3,972 с; приёмник зарегистрировал пять командных кадров.
|
||||
Это функциональная проверка с укороченными сроками, не нагрузка и не
|
||||
измерение радиоканала, TLS или реле. Для повторения на квалифицированном
|
||||
Ubuntu VPS скопировать инженерный скрипт во временный каталог и выполнить
|
||||
`PYTHONPATH=/opt/nodedc-mission-vps/current python3 qualify_faults.py`.
|
||||
Скрипт сам создаёт временную базу; боевую базу ему не передают.
|
||||
|
||||
## Найденный дефект Core
|
||||
|
||||
VPS мог сохранить подтверждение, но Core не получал его до срока, ставил
|
||||
`uncertain` и больше не читал этот ID. Перезапуск и новая команда не
|
||||
исправляли старую строку. Два регрессионных теста сначала падали.
|
||||
|
||||
Теперь локальный тайм-аут команды создаёт долговечное намерение прочитать
|
||||
результат у исходного VPS. Только GET с прежним ID, без POST и физического
|
||||
повтора. За проход — до двух запросов на хост; интервалы 5, 10, 20… до
|
||||
300 секунд сохраняются до сетевого вызова. Исходный срок не продлевается.
|
||||
|
||||
Неверные ID/тип или незавершённый ответ не заменяют неизвестный исход.
|
||||
Конечный результат обновляет журнал и завершает опрос. Новая текущая операция
|
||||
не затирается старой. Ожидающие результата строки продолжают обновляться
|
||||
в открытом журнале за пределами первой страницы и не блокируют очередь.
|
||||
Конечный `uncertain` от самого VPS не запускает бесконечный опрос.
|
||||
|
||||
Область исправления — `scope=command`. Поздняя конфигурация не применяется
|
||||
к текущему состоянию через историю. Для настроек и SIM нужен отдельный
|
||||
контроль версий снимков. Неизвестные результаты, сохранённые до этой версии,
|
||||
автоматически не переинтерпретируются.
|
||||
|
||||
## Приёмка Core
|
||||
|
||||
Сохранены SQLite-копии оборудования и VPS. Миграция на отдельной копии
|
||||
сохранила 61 операцию без изменения состояний; integrity — ok.
|
||||
Core обновлён штатным LaunchAgent на 8000. Перед обновлением принят запрос
|
||||
со статусом `waiting`; после обновления тот же ID получил `device_confirmed`,
|
||||
ответ VPS → B2 **0,505 с**. История выросла ровно с 61 до 62 строк.
|
||||
Это сохранность принятого намерения/результата через управляемый перезапуск;
|
||||
точный момент отправки относительно остановки процесса не квалифицирован.
|
||||
|
||||
Пройдены Ruff, 95 backend-тестов, архитектурные проверки, TypeScript,
|
||||
1008 frontend-тестов и production build. Существующие предупреждения
|
||||
Starlette/httpx и большого JS chunk сохраняются. В заново загруженном
|
||||
интерфейсе проверены журнал и этапы истёкшей команды.
|
||||
|
||||
Приватные результаты, операторские UTC/monotonic отметки, программы сбора,
|
||||
логи, резервные копии и SHA-256 manifest сохранены под игнорируемым
|
||||
`outputs/vps-host-20260926/autonomy/` в каталоге сессии.
|
||||
|
||||
## Границы результата
|
||||
|
||||
При отсутствии связи гарантировать доставку нельзя. Если команда отправлена,
|
||||
а подтверждение потеряно, неизвестный исход сохраняется без повторного
|
||||
воздействия. Это не гарантия ровно одного физического исполнения и не
|
||||
проверка тысячи устройств. Ограничения worker Core, 256 соединений VPS,
|
||||
длительного радиообрыва и масштабирования остаются. Полный аудит автономной
|
||||
конфигурации — следующий отдельный этап.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Резервный образ перед изменением прошивки B2
|
||||
|
||||
Владелец потребовал сохранить текущую прошивку до любых изменений.
|
||||
Установленная версия стендового B2 модели 231 — **0.01**. Архив конфигурации,
|
||||
файл обновления другой версии и дамп обмена USB не являются её резервной копией.
|
||||
|
||||
## Проверка источников 28.09.2026
|
||||
|
||||
- В [публичном каталоге B2](https://8888.arusnavi.ru/Arnavi%20B2/%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B8/)
|
||||
доступна только 0.05; файл уже сохранён в Mission Core.
|
||||
- В [каталоге WEB-конфигуратора](https://ws.arusnavi.ru/#/firmwares) после входа
|
||||
доступны две версии именно B2: 0.05 и 0.06. Остальные строки относятся к L3;
|
||||
их изменения нельзя переносить на B2.
|
||||
- Карточка стендового устройства показывает текущую 0.01, установленную
|
||||
14.04.2025, и отсутствие задания на обновление. В списке доступных версий
|
||||
только 0.06 и 0.05. Выбор версии и сохранение задания не выполнялись.
|
||||
- В просмотренном руководстве B2 описана загрузка обновления локально и через
|
||||
WEB-конфигуратор. Команда выгрузки исполняемого образа из устройства в файл
|
||||
не найдена. Это не доказывает невозможность чтения через сервисные средства,
|
||||
но поддержанного способа резервирования имеющимися интерфейсами пока нет.
|
||||
- Файл 0.01 среди найденных локальных образов отсутствует. Получение и проверка
|
||||
резервного образа **не завершены**. USB для неподтверждённой операции не запрашивался.
|
||||
|
||||
## Найденные файлы
|
||||
|
||||
| Версия B2 | Размер | SHA-256 | Источник |
|
||||
| --- | ---: | --- | --- |
|
||||
| 0.05 | 155824 | `bf71fc531b02917eac076d7b718b51698f3d787562ca37c959bb1c9954fe9927` | Публичный каталог производителя |
|
||||
| 0.06 | 157760 | `36135a214f62bfeac7f049fdedb1cb7c717b676cfe6027f7c72a026c39988625` | Кнопка скачивания строки B2 0.06 в WEB-конфигураторе |
|
||||
|
||||
Происхождение 0.06 установлено по конкретной строке каталога и загруженному
|
||||
файлу `231-0.06.dfw`, а не по одному имени файла. Известный digest добавлен
|
||||
в каталог модели. Хранение и скачивание не разрешают установку; `installable`
|
||||
и `update_available` остаются false. Ни один из этих файлов не является
|
||||
резервной копией установленной 0.01. Бинарные файлы хранятся в локальном архиве,
|
||||
не в исходниках Git.
|
||||
|
||||
## Что известно об изменениях
|
||||
|
||||
По описаниям строк производителя, пересказ:
|
||||
|
||||
- **0.05**, запись от 22.10.2025: обновлённое позиционирование, включая геометки,
|
||||
локатор и фильтры; EGTS без авторизации и триггер интеграции датчиков.
|
||||
- **0.06**, запись от 25.03.2026: выход может учитывать обороты двигателя,
|
||||
полученные по CAN; улучшена стабильность навигационного модуля.
|
||||
|
||||
В этих описаниях не заявлены улучшения горячей замены SIM, автоматический APN,
|
||||
свежий опрос резервной карты или предпочтение слота с разрешённым резервом.
|
||||
Поэтому обновление нельзя представлять как доказанное решение этих задач.
|
||||
Доступ к исходникам или SDK для изменения алгоритмов самой B2 не установлен.
|
||||
|
||||
## Следующее необходимое подтверждение
|
||||
|
||||
Нужен исходный образ **B2, тип 231, ПО 0.01** и сведения производителя:
|
||||
|
||||
1. Соответствует ли он исполняемой версии стенда и допускается ли возврат
|
||||
с 0.05/0.06 на 0.01; сохраняются ли загрузчик, калибровки и конфигурация.
|
||||
2. Есть ли поддержанная команда чтения установленного образа. Если нет,
|
||||
является ли предоставленный `.dfw` достаточным средством восстановления.
|
||||
3. Как восстановить устройство после прерванной загрузки и какие требования
|
||||
к питанию/USB предъявляет загрузчик.
|
||||
4. Какие изменения 0.01 → 0.06 относятся к SIM/APN и какие команды обеспечивают
|
||||
перечитывание слотов и выбор предпочтительной SIM без отключения резерва.
|
||||
|
||||
Это подготовленный список вопросов, а не отправленное обращение. Первоначально
|
||||
образ 0.01 был условием перед изменением прошивки. Последующим сообщением
|
||||
владелец отменил ожидание производителя и разрешил продолжать эксперименты
|
||||
на своём стенде, включая риск повреждения. Ему повторно сообщено, что образа
|
||||
0.01 нет и возврат к нему не гарантирован. Это разрешение не превращает файлы
|
||||
0.05/0.06 или конфигурацию в резервную копию установленной прошивки.
|
||||
|
||||
Исследование продолжается с проверки нативных механизмов SIM и анализа
|
||||
имеющихся файлов; наличие файла обновления не считается доступом к исходному
|
||||
коду. Поведенческая квалификация новой версии и её установка — отдельные
|
||||
операции с явной фиксацией версии, а не незаметная часть SIM-теста.
|
||||
|
||||
## Проверка архива
|
||||
|
||||
0.06 сохранена через штатный сервис архива. После перезапуска канонического
|
||||
Core API вернул обе версии с происхождением производителя; скачанные байты
|
||||
0.05 и 0.06 совпали с исходными по размеру и SHA-256. Три существующие проверки
|
||||
архива/API и Ruff прошли. В открытом разделе «Прошивка» видны 0.06, размер
|
||||
157760 байт и сообщение об отсутствии образа считанной 0.01. Обновление
|
||||
устройства не запускалось; B2 продолжает передавать данные на VPS.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Граница прошивки и серверного рантайма
|
||||
|
||||
Уточнение владельца 28.09.2026: перед дальнейшей автоматизацией проверить,
|
||||
не пытаемся ли мы серверной конструкцией переопределить алгоритм самой B2.
|
||||
|
||||
## Установленные факты
|
||||
|
||||
- На стенде модель 231 / ПО 0.01. Переключение на оставшуюся рабочую SIM без
|
||||
отключения питания наблюдалось без наших команд: B2 уже имеет собственный
|
||||
алгоритм восстановления модема. Новый резервный слот при живом основном
|
||||
соединении не всегда обнаруживался в наблюдаемом окне.
|
||||
- Текущая ручная операция `select-sim` задаёт запрет GPRS для другого слота
|
||||
через поле 72, биты 10/20. Это исключительный выбор, а не предпочтение
|
||||
с разрешённым резервом. Сейчас на стенде включены обе SIM (`both`).
|
||||
- В просмотренной официальной схеме модели 231 есть отдельные APN, разрешение
|
||||
роуминга и запреты GPRS. Параметр «приоритетный оператор в роуминге» не
|
||||
является приоритетом слота. Настройка автоматического перечитывания
|
||||
неактивной SIM, универсального подбора APN или мягкого приоритета слота
|
||||
в этой схеме не найдена. Отсутствие в схеме не доказывает отсутствия
|
||||
внутреннего механизма в прошивке.
|
||||
- В [официальном каталоге B2](https://8888.arusnavi.ru/Arnavi%20B2/%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B8/)
|
||||
опубликован `231 (B2) -0.05.dfw`, дата файла 28.11.2025. В этом каталоге
|
||||
нет списка изменений. По проверенным источникам нельзя утверждать, что
|
||||
0.05 исправляет обнаружение SIM, приоритет слота или автоматический APN.
|
||||
- Локальный справочный файл 0.05: 155824 байта, SHA-256
|
||||
`bf71fc531b02917eac076d7b718b51698f3d787562ca37c959bb1c9954fe9927`.
|
||||
Это готовый образ, не исходный код. Он не устанавливался на B2.
|
||||
- Копия конфигурации не является резервной копией исполняемой прошивки.
|
||||
Наличие пригодного образа прежней 0.01 и процедуры её возврата не доказано.
|
||||
|
||||
## Разделение ответственности
|
||||
|
||||
Прошивка B2 владеет SIM/модемом, регистрацией в сети, обнаружением карты,
|
||||
переходом между слотами, чтением GNSS и локальным накоплением телеметрии.
|
||||
Сервер использует предоставленные команды/настройки; он не меняет внутренний
|
||||
алгоритм платы, если прошивка не предоставляет такого интерфейса.
|
||||
|
||||
VPS/Core владеют принятыми намерениями пользователя, сохранением очереди,
|
||||
сроками, сопоставлением ответов, повторным чтением и понятным статусом.
|
||||
Эта часть нужна при любой прошивке. Она не может удалённо исправить APN
|
||||
единственной неработающей SIM, когда отсутствует другой канал к устройству.
|
||||
|
||||
## Порядок дальнейшей работы
|
||||
|
||||
1. Уточнить для B2 модель 231 различия 0.01 → 0.05: горячая замена, опрос
|
||||
резервной карты, ручной приоритет с разрешённым резервом, APN и команда
|
||||
свежего чтения идентичности. Не переносить команды иных моделей на B2.
|
||||
2. Установить воспроизводимую процедуру обновления/возврата и реальный набор
|
||||
сохранённых образов. Проверить совместимость настроек и протокола;
|
||||
текущие записи Core/VPS квалифицированы только для 0.01.
|
||||
3. Только после этого проводить отдельную квалификацию другой прошивки на
|
||||
том же наборе физических сценариев. Обновление само по себе не считается
|
||||
исправлением. Текущий опыт горячей замены не смешивать с перезапуском.
|
||||
4. Использовать подтверждённый нативный механизм в продукте. Не достраивать
|
||||
периодические перезапуски, блокировки слотов или подбор APN поверх
|
||||
неизвестного алгоритма. Если аппарат не предоставляет нужной функции,
|
||||
зафиксировать ограничение и выбрать локальный канал управления либо
|
||||
другое поддерживаемое оборудование, а не обещать сервером невозможное.
|
||||
|
||||
Самостоятельная модификация бинарной прошивки — отдельная разработка;
|
||||
доступ к исходникам/SDK и поддержанный путь загрузки собственной сборки
|
||||
в проверенных материалах не установлены. Возможность обновления готовым
|
||||
образом не означает возможность безопасно изменить произвольную логику.
|
||||
|
||||
Последующая проверка авторизованного каталога обнаружила B2 0.06 и описания
|
||||
0.05/0.06. Исходный образ 0.01 там отсутствует. См.
|
||||
[результат поиска резервного образа](FIRMWARE_BASELINE_20260928.md): версия 0.06
|
||||
не квалифицирована как исправление SIM и не устанавливалась.
|
||||
|
||||
По следующему запросу владельца добавлены раздел «Прошивка» и локальный архив
|
||||
файлов: [контракт и проверка](FIRMWARE_SETTINGS_20260928.md). Это хранение,
|
||||
выбор и скачивание образов; прошивка B2 через Mission Core ещё недоступна.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Прошивка в настройках B2
|
||||
|
||||
Владелец 28.09.2026 запросил раздел для работы с прошивкой и консольную
|
||||
иконку входа в команды. Выбран существующий FeatureSettingsWindow:
|
||||
«Устройство и аппарат», «Сервер и связь», «Команды», «Прошивка», параметры.
|
||||
Отдельное окно или корень навигации отклонены: файл и считанная версия
|
||||
относятся к текущему оборудованию, а не к новому рабочему пространству.
|
||||
|
||||
## Контракт
|
||||
|
||||
- Последняя считанная версия и дата берутся из наблюдения устройства. Наличие
|
||||
связи само по себе не превращает сохранённое наблюдение в новое чтение ПО.
|
||||
- Архив общий для модели и хранится в `fleet/firmware/archive.sqlite3`.
|
||||
Добавление, выбор и скачивание не меняют настройки и не отправляют команды.
|
||||
- Файлы `.dfw` до 4 МиБ сохраняются транзакционно, дедупликация по SHA-256;
|
||||
архив ограничен 128 МиБ. Происхождение и версия известного файла определяются
|
||||
по проверенному digest. Имя файла пользователя не доказывает совместимость.
|
||||
- Скачивание повторно проверяет SHA-256 на сервере и в клиенте. Пустой архив,
|
||||
загрузка, отказ доступа, недоступность и повтор чтения имеют явные состояния.
|
||||
- Официальный образ 0.05 опубликован в локальном архиве. Это не копия установленной
|
||||
0.01 и не квалификация обновления. В UI нет фиктивной кнопки установки.
|
||||
- При последующем поиске исходной прошивки также сохранён официальный образ
|
||||
0.06 из WEB-конфигуратора. [Проверка источников](FIRMWARE_BASELINE_20260928.md)
|
||||
не обнаружила 0.01; резервирование текущей прошивки остаётся незавершённым.
|
||||
- Обновление по USB/через VPS не реализовано этим изменением. `update_available`
|
||||
и `installable` остаются false. Никакого обращения к производителю из UI нет.
|
||||
- Footer сохранения профиля/настроек скрыт в разделе прошивки: это другая
|
||||
операция. Черновики параметров сохраняются при переключении разделов.
|
||||
|
||||
## Дизайн
|
||||
|
||||
Класс A: доменная секция существующего окна. SettingsCard, Select, Button,
|
||||
LoadingRegion, StatusBadge, ToastStack — общие компоненты; отдельного CSS нет.
|
||||
Одобренная владельцем новая иконка `terminal` (`>_`) добавлена сначала в
|
||||
Design Guideline: export, registry, документация и живой каталог.
|
||||
Командный IconButton сохраняет доступную подпись и прежний обработчик.
|
||||
|
||||
## Публикация файла
|
||||
|
||||
`scripts/publish_equipment_firmware.py --fleet-root … --file …` сохраняет
|
||||
локальный файл тем же сервисом архива. В Git остаётся известный digest и
|
||||
публичный источник; бинарный файл не включается в исходники.
|
||||
|
||||
Приёмка: сохранение и скачивание реального 0.05 через канонический API,
|
||||
восстановление каталога после повторного открытия, проверка нового раздела и
|
||||
командного окна в обычном/развёрнутом интерфейсе и Escape. Физическая прошивка
|
||||
устройства в эту приёмку не входит.
|
||||
|
||||
## Выполненная проверка
|
||||
|
||||
- 3 проверки архива/API: перезапуск хранилища, дедупликация, повреждение и
|
||||
повторное добавление исходника, запрет подмены происхождения именем файла,
|
||||
ограничения размера/имён/модели и same-origin доступ.
|
||||
- Ruff, архитектурные проверки (4), TypeScript, 1015 frontend-тестов и
|
||||
production build прошли. Design Guideline: пакеты прошли typecheck,
|
||||
registry validation, проверку иконок и сборку каталога.
|
||||
- Канонический API 8000 принял повторный импорт 155824-байтного образа 0.05,
|
||||
сохранил одну запись и вернул побайтово тот же файл. SHA-256:
|
||||
`bf71fc531b02917eac076d7b718b51698f3d787562ca37c959bb1c9954fe9927`.
|
||||
- В браузере `>_` открывает существующие команды и журнал, Escape закрывает
|
||||
окно. Раздел «Прошивка» показывает 0.01 с датой чтения и образ 0.05.
|
||||
Проверены раскрытие/выбор файла, кнопка скачивания, загрузка реального
|
||||
образа через file chooser с подтверждением сохранения и повторное открытие.
|
||||
Обычный и развёрнутый режимы аппарата доступны, архив остаётся сохранённым.
|
||||
- Трекер продолжает передавать данные; во время этой работы команды B2 не
|
||||
отправлялись. Сервер 8000 оставлен работающим, новый раздел открыт для владельца.
|
||||
@@ -0,0 +1,121 @@
|
||||
# Идентичность SIM и очередь после горячей замены
|
||||
|
||||
Продолжение [проверки автоматического резерва](SIM_PREFERENCE_AND_FALLBACK_20260928.md).
|
||||
Условия: модель 231 / ПО 0.01, только МТС в SIM 2, первый слот пуст,
|
||||
непрерывное питание 12 В, USB отключён. VPS 0.1.38; Core опрашивает VPS.
|
||||
|
||||
## Проверка обычного запроса пакета
|
||||
|
||||
Приватная сессия `sim-hot-identity-bdf67e38d4b3429cadda5b4e1fc2ded5`.
|
||||
Штатная команда `request-position` (`01 01`) отправлена существующим
|
||||
долговечным рантаймом. Операция `943fdd43028a46f4afc898be8c43a0cd`:
|
||||
|
||||
- отправка VPS: 2026-09-28 11:20:05.600 UTC;
|
||||
- подтверждение B2: 11:20:07.959 UTC, код 0, первая попытка;
|
||||
- измеренный запрос/ответ: 2.360 с;
|
||||
- в сохранённом окне шесть записей, пять с координатами; новых пар тегов SID нет;
|
||||
- свежая сеть 250-01, активная SIM 2 / GPRS 4, SIM 1 отсутствует.
|
||||
|
||||
Подтверждение команды не подменяет получение идентичности: обычный запрос
|
||||
пакета в данном опыте не обновил SID. Настройки, SMS, выходы и перезапуск
|
||||
не использовались. Этот отрицательный результат относится к `01 01`,
|
||||
а не доказывает невозможность другого запроса.
|
||||
|
||||
## Проверка источников
|
||||
|
||||
В [руководстве именно B2, §10](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf)
|
||||
`SERV*1.2` описана как запрос SMS с данными устройства. В общем листе SMS_COM
|
||||
та же команда описана как повторный запрос ICCID. Семантика модели 231/0.01
|
||||
не разрешена этими противоречащими источниками. Команда не отправлялась.
|
||||
|
||||
Общий лист SERVER_COM описывает `01 00` как переключение диагностического
|
||||
режима. Длительность и завершение режима именно B2 не установлены; отправка
|
||||
не выполнена. Не превращать предполагаемую диагностику в квалифицированное
|
||||
чтение SIM и не добавлять слепой периодический опрос этим кодом.
|
||||
|
||||
Статически прочитан публичный JavaScript
|
||||
[официального web-конфигуратора](https://ws.arusnavi.ru/js/index.01d2841b.js),
|
||||
без входа в кабинет и без обращений к устройствам производителя. Он выводит
|
||||
ICCID из ответа `/coordinates`, отдельно сохраняя дату значения. Кнопка
|
||||
сервисной сессии вызывает серверный `commands/startServiceSession`; команды
|
||||
протокола устройства в этом участке не раскрыты. Блокировка кнопки на 120 с
|
||||
сама по себе не доказывает автоматическое завершение режима на B2.
|
||||
|
||||
## Дальнейшая независимая проверка
|
||||
|
||||
Свежая идентичность после горячей замены, обнаружение неактивной новой карты
|
||||
и ручной приоритет без запрета резерва остаются аппаратными вопросами.
|
||||
Старые SID не считать актуальными по совпадению оператора или APN.
|
||||
|
||||
Независимо можно проверить долговечный запрос во время смены мобильного
|
||||
канала: физически извлечь единственную МТС, дождаться подтверждённой потери
|
||||
свежих данных, создать один запрос координат, вернуть интернет через МегаФон
|
||||
SIM 1 без отключения питания. Принять только тот же ID операции с журналом
|
||||
ожидания/попыток и подтверждением B2, плюс свежие координаты по новому каналу.
|
||||
До подтверждения физического действия этот опыт не считается выполненным.
|
||||
|
||||
## Запрос поставлен при отсутствии обеих SIM
|
||||
|
||||
Сессия `hot-sim-command-queue-302d35116afd410cbb5379e96a132994`.
|
||||
Владелец подтвердил извлечение единственной МТС, сохраняя питание 12 В и
|
||||
отключённый USB. Последнее измерение B2 — 11:38:00 UTC, получение VPS —
|
||||
11:38:04.841. В 11:39:39.597 API подтвердил `online=false` и
|
||||
`position_fresh=false`; связь Core с VPS 0.1.38 сохранялась.
|
||||
|
||||
В 11:40:02.268 UTC через штатный API очереди создан один запрос координат
|
||||
`271d767df69c4934a897f3128050a62f`. В 11:40:08.876 тот же ID находился на VPS
|
||||
в состоянии `queued`, `runtime_phase=waiting-link`, `attempt_count=0`;
|
||||
время отправки отсутствовало. Факт ожидания сохранён отдельно до команды
|
||||
оператору вставить МегаФон в SIM 1, оставив второй слот пустым.
|
||||
|
||||
На этом этапе подтверждена только постановка и сохранение запроса при потере
|
||||
канала. Восстановление через другую карту и завершение запроса ещё ожидаются;
|
||||
их нельзя считать успешными по одному состоянию очереди.
|
||||
|
||||
## Восстановление через МегаФон и завершение того же запроса
|
||||
|
||||
Владелец подтвердил установку МегаФона в SIM 1 с пустым SIM 2 и непрерывным
|
||||
питанием; подтверждение записано в 11:41:03.209 UTC. USB не подключён.
|
||||
До возвращения B2 сохранялись `waiting-link` и ноль попыток. Новые запросы,
|
||||
команды настройки и перезапуска не создавались.
|
||||
|
||||
| Событие | UTC |
|
||||
| --- | --- |
|
||||
| Запрос принят Core | 11:40:02.268 |
|
||||
| Подтверждение установки МегаФона | 11:41:03.209 |
|
||||
| Первые пакеты после восстановления | 11:44:05.064 |
|
||||
| VPS отправил ожидавший запрос | 11:44:07.879 |
|
||||
| B2 подтвердил его, код 0 | 11:44:08.643 |
|
||||
|
||||
Операция сохранила ID `271d767df69c4934a897f3128050a62f`, завершилась
|
||||
`device_confirmed`, `runtime_phase=complete`. Журнал VPS содержит ровно одну
|
||||
попытку. От принятия до отправки — **245.612 с**, от отправки до ответа —
|
||||
**0.764 с**, полный срок — **246.376 с**. Не представлять срок одного
|
||||
запроса как 0.764 с без времени ожидания соединения.
|
||||
|
||||
От регистрации подтверждения вставки до первого пакета — **181.855 с**;
|
||||
точное физическое время вставки не измерялось. Общий разрыв доставки
|
||||
360.223 с включает период с пустыми слотами и не является временем
|
||||
подключения после вставки.
|
||||
|
||||
В контрольном окне получены семь различных свежих GNSS-измерений через
|
||||
SIM 1 / GPRS 4, сеть 250-02, SIM 2 отсутствует. Времена измерений:
|
||||
11:44:00, 11:44:05, далее каждые 15 с до 11:45:20 UTC. Не приписывать
|
||||
внеочередную координату конкретной команде лишь по близости времён;
|
||||
её подтверждение установлено отдельным ответом с токеном. Владелец также
|
||||
сообщил появление активного индикатора первого слота в интерфейсе.
|
||||
|
||||
**Принято:** один запрос чтения, созданный при отсутствии мобильной связи,
|
||||
сохранился на VPS и завершился после горячего перехода с МТС на МегаФон
|
||||
без ручного повторного создания, внешнего отключения питания или нашей
|
||||
команды перезапуска. Это не приёмка всех типов команд, сбоев после отправки
|
||||
или перезапуска процессов — эти сценарии имеют отдельные доказательства.
|
||||
|
||||
Новых пар SID при этом снова не было. Передача данных восстановилась,
|
||||
но свежая идентичность заменённой карты по-прежнему не подтверждена.
|
||||
Окончательное физическое состояние: МегаФон в SIM 1, SIM 2 пуст,
|
||||
питание 12 В, USB отключён. Временные наблюдатели завершены.
|
||||
|
||||
Последующая разовая [проверка сервисной команды 01 00](SERVICE_MODE_PROBE_20260928.md)
|
||||
через VPS 0.1.39 получила ответ B2 за 1.230 с, но не дала свежих SID или
|
||||
отдельного диагностического канала. Команда не включена в автоматический опрос.
|
||||
@@ -0,0 +1,161 @@
|
||||
# B2: сравнение помещения и улицы, 27 сентября 2026
|
||||
|
||||
На улице пять из пяти запросов позиции подтверждены за 0,519–1,105 с. После
|
||||
возврата в помещение на той же версии VPS — также пять из пяти, за 1,191–2,264 с.
|
||||
Медиана выросла с 0,604 до 1,677 с. В помещении после возврата наблюдались
|
||||
14–17 спутников: первоначальные 8 спутников не являются постоянной комнатной
|
||||
характеристикой. Это короткие серии, а не гарантия связи или доказательство
|
||||
причины предыдущих отказов. Дальнейшая работа по решению владельца — в помещении.
|
||||
|
||||
## Условия и метод
|
||||
|
||||
Один и тот же тестовый B2; активна SIM1, конфигурация трекера в уличном опыте не
|
||||
менялась. Команды идут Mission Core → собственный VPS Host 0.1.25 → мобильная
|
||||
сеть → B2. USB-порт для команд или чтения не открывался; Mac видит USB-устройство.
|
||||
Никаких команд выходам, прошивок, перезапусков или обращений к сервису производителя
|
||||
в этой серии не было.
|
||||
|
||||
В помещении USB был отключён, оператор ранее сообщил о внешнем питании 12 В.
|
||||
Перед уличным опытом оператор подключил USB и вынес B2 наружу. По его словам,
|
||||
питание, вероятно, не прерывалось. Непрерывность питания, отсутствие аппаратного
|
||||
перезапуска и фактический источник питания измерением не подтверждены.
|
||||
Место, подключение USB, возможное питание и время изменились совместно.
|
||||
|
||||
Время ниже московское (UTC+3). Предварительный снимок помещения снят в 13:28.
|
||||
Уличные команды отправлены в 13:30:43, 13:34:59, 13:35:11, 13:35:23 и 13:35:35.
|
||||
Это две отдельные сетевые записи длительностью 45 и 75 секунд, а не непрерывная
|
||||
запись всего промежутка. Четыре последних запроса отправлялись отдельно,
|
||||
примерно через 10 секунд после подтверждения предыдущего; автоматических
|
||||
повторов команд не было. Максимальная пропускная способность не измерялась.
|
||||
|
||||
Успех — не просто TCP ACK или зелёный статус в интерфейсе. В каждой записи
|
||||
проверен пакет INTERNAL типа 9 с корректной контрольной суммой, совпадающим
|
||||
токеном команды и кодом 0. Это подтверждение команды устройством; состояние
|
||||
физических реле в данном опыте не проверялось.
|
||||
|
||||
## Сравнение
|
||||
|
||||
| Показатель | В помещении | На улице |
|
||||
| --- | --- | --- |
|
||||
| Спутники | 8 в снимке перед переносом | 14–16 в сохранённых снимках |
|
||||
| Сигнал активной SIM1, шкала B2 0–31 | 16 в снимке перед переносом | 20–22 |
|
||||
| Активная SIM | SIM1 | SIM1 во всех сохранённых снимках |
|
||||
| Передача телеметрии | Свежая телеметрия поступала | Свежая телеметрия поступала |
|
||||
| Запрос позиции на VPS 0.1.25 | Последний записанный запрос: подтверждение не получено за 30 с | 5 из 5 подтверждены, 0,519–1,105 с |
|
||||
| Более ранний положительный контроль в помещении | 1,320 с, VPS 0.1.24; это отдельная версия и опыт | Медиана текущих 5 запросов 0,604 с |
|
||||
| Очередь VPS | 4,791 мс у последнего неподтверждённого запроса | 4,783–5,231 мс |
|
||||
| Повторные TCP-передачи команд | Четыре повтора последнего неподтверждённого запроса | Ни одного у пяти запросов |
|
||||
| Сброс соединения в записях | VPS оборвал неподтверждённую очередь около 30 с | Ни входящих, ни исходящих RST в двух окнах |
|
||||
|
||||
В уличной серии сохранено девять различных измерений позиции: два в первом
|
||||
опыте и семь во втором. Повторные опросы одного измерения не считаются новыми
|
||||
измерениями. Данные антенны, HDOP и точность по известной опорной координате
|
||||
здесь не измерены: больше спутников ещё не означает доказанную точность в метрах.
|
||||
|
||||
Разность времени приёма и времени измерения позиции составила 4,222 с в
|
||||
предварительном комнатном снимке и 3,521–5,685 с в сохранённых уличных снимках.
|
||||
Явного ускорения обычной телеметрии по этим данным не видно. Эта разность
|
||||
включает формирование/буферизацию/передачу и возможную погрешность часов B2;
|
||||
это не чистая задержка мобильной сети. Возраст записи в момент открытия
|
||||
интерфейса не следует смешивать с задержкой доставки.
|
||||
|
||||
SIM2 не использовалась для передачи. Её показатель сигнала в уличных снимках
|
||||
менялся в диапазоне 15–24 при исходном 22. Улучшение всех операторов не
|
||||
подтверждено; проверка МТС по действующему каналу этой серией не выполнена.
|
||||
|
||||
## Все пять уличных запросов
|
||||
|
||||
| № | От отправки VPS до ответа B2, с | Независимая проверка PCAP, с | Очередь VPS, мс | Результат |
|
||||
| --- | ---: | ---: | ---: | --- |
|
||||
| 1 | 0,546 | 0,539 | 5,094 | Код 0, токен совпал |
|
||||
| 2 | 0,604 | 0,597 | 5,231 | Код 0, токен совпал |
|
||||
| 3 | 0,740 | 0,731 | 4,783 | Код 0, токен совпал |
|
||||
| 4 | 1,105 | 1,099 | 4,918 | Код 0, токен совпал |
|
||||
| 5 | 0,519 | 0,512 | 4,993 | Код 0, токен совпал |
|
||||
|
||||
Среднее время ответа — 0,703 с; медиана — 0,604 с. Приведённая задержка измерена
|
||||
от отправки на VPS до обработки подтверждения устройства. Она не включает
|
||||
полный путь от нажатия кнопки пользователем до перерисовки интерфейса.
|
||||
PCAP даёт отдельную границу от исходящего до входящего сетевого кадра.
|
||||
|
||||
## Вывод и следующий контроль
|
||||
|
||||
В текущих уличных условиях короткие команды через собственный VPS проходят
|
||||
быстро. Сам VPS не держит их в очереди секунды: измеренная очередь около 5 мс
|
||||
как в успешных, так и в неуспешном опыте. GNSS и мобильная связь — разные
|
||||
показатели; по росту числа спутников нельзя вывести причину улучшения команд.
|
||||
|
||||
Из этих пяти успехов нельзя вычислить надёжность в поле или максимальную
|
||||
скорость команд. Комнатная база не является одинаковой по длительности серией,
|
||||
а один из успешных комнатных контролей выполнен на прошлой версии VPS.
|
||||
Нельзя считать тайм-аут «задержкой исполнения 30 секунд»: исполнения мы не
|
||||
подтвердили. Нельзя утверждать ни что USB помогает, ни что он мешает.
|
||||
|
||||
Контроль с возвратом в помещение выполнен ниже. Следующие исследования остаются
|
||||
в помещении и должны раздельно проверять потерю соединения, питание и второй
|
||||
оператор. Переключение SIM и полная запись настроек не считаются
|
||||
квалифицированными только по успешным запросам позиции.
|
||||
|
||||
## Возврат в помещение: сопоставимая серия
|
||||
|
||||
Владелец вернул B2 внутрь. VPS оставался на 0.1.25, SIM1 и настройки не менялись.
|
||||
Mac перечислял подключённый USB, serial не открывался. Фактический источник
|
||||
питания и его непрерывность отдельно не измерены. Пять отдельных запросов
|
||||
отправлены примерно через 10 секунд после подтверждения предыдущего.
|
||||
|
||||
| Показатель | Улица, 0.1.25 | Возврат в помещение, 0.1.25 |
|
||||
| --- | ---: | ---: |
|
||||
| Подтверждённые команды | 5 из 5 | 5 из 5 |
|
||||
| Медиана ответа B2, с | 0,604 | 1,677 |
|
||||
| Диапазон ответа B2, с | 0,519–1,105 | 1,191–2,264 |
|
||||
| Очередь VPS, мс | 4,783–5,231 | 4,306–6,526 |
|
||||
| Спутники | 14–16 | 14–17 |
|
||||
| Сигнал SIM1, шкала 0–31 | 20–22 | 15–22 |
|
||||
| Измерение позиции → приём, с | 3,521–5,685 | 3,964–5,556 |
|
||||
| Повторы TCP-кадра команды | 0 | 1 у пятого запроса |
|
||||
|
||||
Комнатные времена по порядку: 1,843; 1,677; 1,397; 1,191; 2,264 с.
|
||||
Восемь различных снимков телеметрии, во всех выбран SIM1. В PCAP у каждой
|
||||
команды ровно один прикладной кадр и ответ типа 9 с правильной контрольной
|
||||
суммой, токеном и кодом 0. Дополнительная передача пятого кадра имеет тот же
|
||||
TCP sequence number: это повтор транспорта, а не новая команда приложения.
|
||||
|
||||
В комнатном окне есть один исходящий RST и нет входящих; это счёт по всему
|
||||
окну записи, а не свидетельство сброса каждой команды. Запись рассчитана на
|
||||
95 секунд, промежуток между первым и последним сохранённым пакетом — 86,865 с.
|
||||
Улица дала меньшую задержку команд в этой серии; существенное улучшение GNSS
|
||||
после сравнения с возвратом в помещение не установлено. Максимальная
|
||||
пропускная способность и статистика редких отказов не измерены.
|
||||
|
||||
## Приёмка runtime 0.1.26 в помещении
|
||||
|
||||
После установки [runtime 0.1.26](WEAK_LINK_RUNTIME.md) выполнены ещё три
|
||||
отдельных запроса: 2,224; 0,887; 1,157 с, все подтверждены B2. Очередь VPS —
|
||||
3,042–4,841 мс. Каждый HTTP-запрос к Core повторён с теми же параметрами и
|
||||
ревизией: вернулся прежний ID операции. PCAP подтверждает один прикладной
|
||||
кадр на операцию; у первого был один TCP-повтор. Окно содержит один исходящий
|
||||
RST и ни одного входящего, промежуток пакетов — 62,465 с.
|
||||
|
||||
Эта приёмка проверяет рабочий тракт и дедупликацию запроса. Она не доказывает
|
||||
улучшения радиоканала от изменения серверного кода: три наблюдения и другое
|
||||
время не дают такого вывода. Отказы Core/VPS и восстановление очереди отдельно
|
||||
проверены воспроизводимыми тестами; физический B2 в этой серии не перезапускался.
|
||||
|
||||
## Воспроизводимые свидетельства
|
||||
|
||||
Закрытые сетевые записи и снимки лежат в игнорируемом каталоге
|
||||
`outputs/vps-host-20260926/autonomy/`; манифесты содержат SHA-256 файлов.
|
||||
Точные координаты, сетевые адреса клиента и уникальные идентификаторы трекера
|
||||
в этот отчёт не включены.
|
||||
|
||||
- `placement-1faf3f3c3c8e4ad6af5b4167f15a711f` — снимок помещения.
|
||||
- `network-only-b5c513eb06da42d599fb515e66b8a83d` — неподтверждённый запрос на 0.1.25.
|
||||
- `network-only-278ac319e262481d971a22cd1b4480ef` — прежний успех на 0.1.24.
|
||||
- `outdoor-usb-5213234f77604f9ea6eeafd5d56ed565` — первый уличный запрос.
|
||||
- `outdoor-series-dd05233e6d6346be8feea79b75eaaaaa` — ещё четыре запроса и телеметрия.
|
||||
- `indoor-return-e666220d1d0049acb15d59d3dd789900` — пять запросов после возврата.
|
||||
- `indoor-runtime26-f1b801e1ea7f404fbcc51a0cda28deef` — три запроса на 0.1.26.
|
||||
- `runtime-b54eb15f6b1e48d09c687801f7347617` — артефакт, установка и проверки runtime.
|
||||
|
||||
Обе программы сетевой записи завершились по заданному сроку; tcpdump сообщил
|
||||
об отсутствии пакетов, потерянных ядром. Это не оценка потерь мобильного канала.
|
||||
@@ -0,0 +1,107 @@
|
||||
# МТС: запуск модема и работа без USB, 2026-09-28
|
||||
|
||||
Сессия: `mts-modem-diagnostic-b0fb46ee12a849ff96fe25db140f4d0f`.
|
||||
Физический B2 модели 231, прошивка 0.01; только МТС во втором слоте.
|
||||
Сырые записи, идентификаторы SIM, координаты и конфигурация находятся в
|
||||
приватном каталоге этой сессии под `outputs/arnavi-b2/`, вне Git.
|
||||
|
||||
## Результат
|
||||
|
||||
Трекер установил связь с собственным VPS с уже сохранёнными настройками МТС.
|
||||
После отключения USB и сохранения внешнего питания 12 В он продолжил передавать
|
||||
свежие измерения и подтвердил отдельный запрос координат за **3,066 секунды**
|
||||
с первой попытки. Прежний отказ связи не воспроизвёлся в этом запуске;
|
||||
его причина пока не установлена.
|
||||
|
||||
Конфигурация прочитана штатным USB-адаптером продукта после пассивной записи.
|
||||
207 записей, 983 байта, SHA-256 до и после совпадает:
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
Новых записей APN, конфигурации, прошивки и команд управления выходами не было.
|
||||
Физический перезапуск выполнил владелец по согласованной последовательности.
|
||||
|
||||
## Метод
|
||||
|
||||
На VPS выполнялся ограниченный захват только TCP 9922 в обе стороны:
|
||||
600 секунд, до 20 000 пакетов, снимок 96 байт. Параллельно Mac пассивно читал
|
||||
диагностический USB-поток запуска B2: наш наблюдатель не отправлял AT-команд,
|
||||
не менял параметры tty и явно не переключал линии управления модемом.
|
||||
Поток записывался около 286 секунд, получено 88 391 байт, ошибки USB не отмечены.
|
||||
|
||||
Core опрашивал API VPS. Направление соединений не менялось: Core → VPS,
|
||||
B2 → VPS. VPS не открывал соединений к Core. Запросы координат проходили через
|
||||
существующий журнал команд и штатный сетевой исполнитель.
|
||||
|
||||
Время USB-событий — время получения блока данных Mac, не точное время
|
||||
исполнения внутри B2. Подтверждение владельцем включения питания пришло позже
|
||||
начала потока; вычислять время запуска от этого подтверждения нельзя.
|
||||
|
||||
## Что показал запуск
|
||||
|
||||
1. До активации мобильного интернета в потоке обнаружены ответы внутреннего
|
||||
модема на `AT+CCID` и `AT+CIMI`: ICCID из 20 цифр и IMSI из 15 цифр.
|
||||
Префикс IMSI согласуется с наблюдавшейся сетью МТС `250-01`.
|
||||
2. Затем зафиксированы регистрация в сети `25001`, применение уже сохранённого
|
||||
APN `internet.mts.ru`, активация пакетных данных, получение IP и открытие
|
||||
TCP-соединений к нашему VPS. Наблюдались четыре `CONNECT OK`; в записанном
|
||||
интервале не найдено `CONNECT FAIL` или `PDP DEACT`.
|
||||
3. Свежая телеметрия подтвердила SIM 2, GSM state 4, сеть `250-01` и координаты.
|
||||
Первые полученные записи о SIM 1 были накопленными: возраст измерения около
|
||||
79 минут. Их свежее время получения не означает свежий выбор SIM 1.
|
||||
|
||||
Полные идентификаторы в этом потоке — полезный источник для будущего
|
||||
автораспознавания SIM до появления интернета. Штатный USB-ответ SID по-прежнему
|
||||
нельзя выдавать за полный ICCID. Пока не квалифицированы запрос полных данных
|
||||
по требованию, надёжная привязка к слоту при двух SIM и распознавание MVNO.
|
||||
Нативный автоматический выбор APN прошивкой также не доказан.
|
||||
|
||||
Позднейший [опыт перестановки SIM](SIM_SLOT_IDENTITY_20260928.md) расширил
|
||||
этот результат: штатный запрос `I 7` вернул полный ICCID в обоих слотах.
|
||||
Ограничение ранних 12-значных ответов нельзя распространять на все чтения B2.
|
||||
|
||||
## Команды и очередь
|
||||
|
||||
| Проверка | Создано, UTC | Подтверждено, UTC | Результат |
|
||||
| --- | --- | --- | --- |
|
||||
| Запрос, созданный во время прежнего отсутствия связи | 06:02:56.496 | 07:29:03.115 | Та же операция завершилась; последняя попытка 7,801 с |
|
||||
| Новый запрос при подключённом USB | 07:31:30.572 | 07:31:32.714 | Одна попытка, 2,123 с |
|
||||
| Новый запрос после отключения USB | 07:39:03.810 | 07:39:06.895 | Одна попытка, 3,066 с |
|
||||
|
||||
Во всех трёх случаях VPS сохранил `device_confirmed`, код устройства 0.
|
||||
Время попытки измерено от отправки VPS до подтверждения B2; это не полная
|
||||
задержка пользовательского интерфейса. Два отдельных свежих запроса не дают
|
||||
статистики производительности и не доказывают влияние USB на задержку.
|
||||
|
||||
У ранее ожидавшей операции четыре записи попыток: две без подтверждения,
|
||||
одна истекла до отправки и одна подтверждена. Поэтому это не четыре доказанных
|
||||
доставки устройству. Операция сохранила исходную идентичность и дождалась
|
||||
восстановления; полное ожидание заняло около 86 минут, а не 7,8 секунды.
|
||||
|
||||
## Проверка после отключения USB и завершение
|
||||
|
||||
Владелец подтвердил отключение USB в 07:34:53 UTC при сохранении 12 В.
|
||||
Mac независимо подтвердил отсутствие USB-устройства. В следующие 105 секунд
|
||||
наблюдения получены семь различных измерений мобильной связи с временем
|
||||
**после** отключения: SIM 2, GSM state 4, сеть `250-01`. Затем отдельный
|
||||
запрос из таблицы выше подтвердил обратный путь команды без USB.
|
||||
|
||||
При финальной проверке в 07:40:39 UTC USB отсутствовал, B2 был на связи через
|
||||
SIM 2; возраст последнего пакета около 19 секунд, измерения — 23 секунды.
|
||||
Core на каноническом порту 8000 и сервис VPS оставлены работающими.
|
||||
|
||||
Захват VPS завершён: 453 пакета захвачено, 453 получено фильтром, 0 потерь ядра.
|
||||
Локальная копия PCAP сверена по SHA-256 с удалённой; временный процесс остановлен,
|
||||
его удалённый каталог удалён. Локальный USB-наблюдатель и наблюдатель после
|
||||
отключения USB завершились. В приватном каталоге сохранён итоговый манифест
|
||||
с UTC, монотонными метками, заметками владельца и хешами артефактов.
|
||||
|
||||
## Граница результата и следующий шаг
|
||||
|
||||
Доказано работающее соединение этой МТС во втором слоте с нашим VPS, передача
|
||||
данных и подтверждение команды без USB. Не доказаны устранение причины прежнего
|
||||
сбоя, холодный запуск без USB в этом опыте, надёжность повреждённого USB-кабеля,
|
||||
автоматическая настройка произвольной новой SIM и работа всех операторов.
|
||||
|
||||
Следующий этап [плана автоматизации](AUTOMATIC_CONNECTIVITY_DESIGN_20260928.md) —
|
||||
квалифицировать получение идентичности SIM и её привязки к слоту, затем использовать
|
||||
эти доказательства в подборе параметров из версионируемого справочника. Не менять
|
||||
работающие APN на основании одного кода обслуживающей сети или старой телеметрии.
|
||||
@@ -0,0 +1,159 @@
|
||||
# МТС и МегаФон в обоих слотах с пустыми APN
|
||||
|
||||
28.09.2026, VPS 0.1.41, B2 0.01. Приватная сессия
|
||||
`native-slot-swap-795c8fb195a74ee99e92b2a519470091`.
|
||||
|
||||
Владелец заменил МегаФон на МТС в первом слоте по инструкции сохранять питание
|
||||
12 В, не подключать USB и оставить второй слот пустым. Время подтверждения
|
||||
получено уже после восстановления связи и не является временем физической
|
||||
замены. При подготовке сохранён курсор журнала 18802 и конфигурация SHA-256
|
||||
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
|
||||
Оба слота разрешены, APN, логин и пароль обоих слотов пусты.
|
||||
|
||||
## Результат связи
|
||||
|
||||
До восстановления не отправлялись команды выбора SIM, перезапуска либо
|
||||
изменения настроек. Из существующего журнала:
|
||||
|
||||
| Наблюдение | UTC |
|
||||
| --- | --- |
|
||||
| Последний свежий пакет МегаФона | 14:30:09.048 |
|
||||
| Первое получение накопленных пакетов после замены | 14:31:06.308 |
|
||||
| Первое свежее измерение МТС с GPRS 4 | 14:31:04.000 |
|
||||
| Получение этого измерения на VPS | 14:31:08.909 |
|
||||
|
||||
Пауза между свежими пакетами с работающим интернетом — 59.861 с.
|
||||
Это измеренный разрыв потока, не точное время от физического извлечения.
|
||||
Получены координаты и сеть 250-01, сигнал 22/31, активный слот 1,
|
||||
состояние слота 2 — отсутствие SIM. Более старые сообщения поступали после
|
||||
новых и не использовались для подмены текущего состояния.
|
||||
|
||||
## Команда и независимое чтение
|
||||
|
||||
Запрос координат `0ccc64e8b1074af984a0954dc6259e1b`:
|
||||
|
||||
- одна попытка, ответ B2 с кодом 0;
|
||||
- ожидание отправки 7.421 с;
|
||||
- ответ после отправки 1.842 с;
|
||||
- полное время 9.262 с;
|
||||
- TCP ACK зафиксирован отдельно, наблюдение через 2.006 с.
|
||||
|
||||
Штатное чтение `0b96389cd96c40ce8493b8136596799c` прошло с первой попытки:
|
||||
полный образ принят через 5.375 с после отправки. Образ побайтово совпал с
|
||||
исходным SHA. Все шесть полей APN/логина/пароля остались пустыми, запреты GPRS
|
||||
обоих слотов сняты. Ни параметров оператора, ни нового образа прошивки для
|
||||
этого подключения не потребовалось.
|
||||
|
||||
Это подтверждает МТС с пустыми параметрами также в первом слоте. Ранее МТС
|
||||
проверена во втором и МегаФон в первом. МегаФон во втором с этим образом
|
||||
проверен в заключительной фазе ниже. Работа этих карт не доказывает универсальный
|
||||
каталог APN внутри прошивки или совместимость с любым корпоративным тарифом.
|
||||
|
||||
## Ограничение имени оператора
|
||||
|
||||
На свежем пакете с полным кодом реальная функция представления интерфейса
|
||||
вернула единственную опцию `SIM 1 (МТС)`, состояние использования для интернета
|
||||
и пустой второй слот. Историческая привязка первого слота к МегаФону имеет
|
||||
`binding_current=false` и не подменяет новый оператор. Это проверка функции
|
||||
представления на записанном API-пакете, не снимок открытого браузера.
|
||||
|
||||
Однако после чтения конфигурации в последующих пакетах сам B2 заменил TAG8
|
||||
`01fa0016` на `01000016`: MNC остался 1, сигнал 22, MCC изменился с 250 на 0.
|
||||
Первое такое измерение в сохранённой записи — 14:33:56 UTC. Поэтому текущий
|
||||
API отдаёт `mcc=null`, а интерфейс может снова показывать неизвестного оператора.
|
||||
Содержимое исходного пакета подтверждает, что это не просто потеря подписи UI.
|
||||
Связь и свежие координаты при этом сохраняются.
|
||||
|
||||
Совпадение по времени с чтением не доказывает причинную связь. Не надо выдавать
|
||||
MNC без страны за достоверного оператора, либо использовать прежнюю SIM-привязку.
|
||||
Стабильность определения сети требует отдельного анализа; история полного кода
|
||||
может отображаться только с явным обозначением своего возраста и происхождения.
|
||||
В этом опыте продуктовый код не менялся.
|
||||
|
||||
## Продолжение
|
||||
|
||||
Перед следующей инструкцией сохранён курсор 18860: вставить МегаФон в пустой
|
||||
второй слот, оставив работающую МТС в первом, без отключения питания, USB и
|
||||
ручного выбора слота. Сначала наблюдать сохранение работы МТС и обнаружение
|
||||
резерва; извлечение МТС — только отдельным следующим шагом. Сам факт вставки
|
||||
неактивной SIM не считается доказанным её опросом модемом.
|
||||
|
||||
## Добавление МегаФона во второй слот при работающей МТС
|
||||
|
||||
Владелец подтвердил вставку МегаФона по инструкции оставить МТС в первом
|
||||
слоте, питание 12 В и отключённый USB. Подтверждение записано в
|
||||
14:42:44.973 UTC; это не точное время вставки. Приватная фаза `megafon2-added`
|
||||
содержит периодические снимки API и исходные пакеты после курсора 18860.
|
||||
|
||||
Пассивное наблюдение API продолжалось до 14:43:35.153 UTC. Во всех снимках
|
||||
связь и координаты оставались свежими, активный слот — 1 / GPRS 4. Дополнительно
|
||||
выгружены пакеты до измерения 14:43:55 UTC, принятого в 14:43:58.826 UTC.
|
||||
После подтверждения получено семь свежих записей с координатами; во всех
|
||||
второй слот продолжает сообщать состояние 0, новых SID нет. Код страны сети
|
||||
первого слота остаётся неполным, как отмечено выше.
|
||||
|
||||
Добавление карты не переключило рабочий канал. Автоматическое обнаружение
|
||||
неактивного МегаФона **не подтверждено**: прошивка продолжает передавать
|
||||
«SIM не обнаружена», несмотря на подтверждённую владельцем вставку.
|
||||
Это не доказывает отсутствие контакта или невозможность использовать карту.
|
||||
Ни команды, ни записи настроек, ни перезапуск в этой фазе не выполнялись.
|
||||
|
||||
В 14:44:07 UTC сохранён курсор 18932 перед следующим физическим шагом:
|
||||
извлечь только МТС из первого слота, оставив МегаФон во втором и непрерывное
|
||||
питание. Проверить переход на второй слот с теми же пустыми APN; не подменять
|
||||
нативный переход удалённым выбором слота или перезапуском.
|
||||
|
||||
## Извлечение МТС: самостоятельный переход на МегаФон SIM 2
|
||||
|
||||
Владелец подтвердил извлечение только МТС. Условия по инструкции: МегаФон
|
||||
остаётся во втором слоте, питание 12 В сохраняется, USB отключён, ручного
|
||||
выбора в интерфейсе нет. Фаза `megafon2-fallback` хранит исходные пакеты после
|
||||
курсора 18932, подтверждение владельца и отдельные результаты двух запросов.
|
||||
Время регистрации подтверждения позже восстановления; оно не использовано
|
||||
как время физического извлечения.
|
||||
|
||||
| Наблюдение | UTC |
|
||||
| --- | --- |
|
||||
| Последнее свежее измерение SIM 1 / GPRS 4 | 14:46:39.000 |
|
||||
| Получение этого измерения на VPS | 14:46:43.492 |
|
||||
| Первое свежее измерение SIM 2 / GPRS 4 | 14:47:24.000 |
|
||||
| Получение этого измерения на VPS | 14:47:28.291 |
|
||||
|
||||
Разрыв между свежими пакетами — **44.799 с**, не точная задержка от извлечения.
|
||||
Первый свежий пакет нового канала содержит координату, сеть 250-02, сигнал
|
||||
20/31, отсутствие SIM 1 и регистрацию SIM 2. Команды переключения, перезапуска
|
||||
или записи конфигурации в фазе восстановления не отправлялись. Отсутствие
|
||||
внутреннего перезапуска модема/контроллера этим не доказано.
|
||||
|
||||
После подтверждённого восстановления выполнены два последовательных запроса:
|
||||
|
||||
- Запрос координат `c7da7a72bf5443c8b780e841971acb36`: `device_confirmed`,
|
||||
одна попытка, код 0. Ожидание отправки 9.656 с, ответ после отправки 0.927 с,
|
||||
полное время 10.583 с. TCP ACK наблюдался отдельно через 1.006 с.
|
||||
- Полное чтение `5f9e591b53d94d65a6f88611ef8b78ce`: `observed`, одна попытка,
|
||||
конфигурация получена через 2.453 с после отправки. Образ побайтово совпал
|
||||
с исходным SHA `624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
|
||||
Оба слота остаются разрешены, обе тройки APN/логина/пароля пусты.
|
||||
|
||||
В контрольном снимке 14:52:58 UTC канал продолжает работать через SIM 2:
|
||||
свежие координаты, сеть 250-02, сигнал 21/31, SIM 1 не обнаружена.
|
||||
Новых идентификаторов SIM в выгруженных пакетах перехода нет; прежние
|
||||
идентичности обоих слотов остаются `binding_current=false`.
|
||||
|
||||
## Итог матрицы и оставшиеся ограничения
|
||||
|
||||
| Карта | SIM 1 с пустыми параметрами | SIM 2 с пустыми параметрами |
|
||||
| --- | --- | --- |
|
||||
| МТС владельца | Связь, координаты, команда и чтение подтверждены | Подтверждены в предыдущей сессии |
|
||||
| МегаФон владельца | Подтверждены в предыдущей сессии | Связь, координаты, команда и чтение подтверждены |
|
||||
|
||||
На этих двух картах не требуется закреплять операторский APN за номером
|
||||
слота, чтобы восстановить интернет. Нативное резервирование с двумя
|
||||
разрешёнными слотами работает в проверенных переходах. Это не приёмка всех
|
||||
тарифов, всех таймеров и всей пользовательской матрицы.
|
||||
|
||||
Остаются отдельные вопросы: своевременный опрос вставленной неактивной SIM,
|
||||
новые идентификаторы после горячей замены, неполный код страны сети и ручное
|
||||
предпочтение без запрета резервного слота. Последнее нельзя реализовать
|
||||
переименованием существующего исключительного `select-sim`. Прошивка в этих
|
||||
проверках не менялась, продуктовый код в заключительной фазе также не менялся.
|
||||
@@ -0,0 +1,112 @@
|
||||
# MTS path observation, 2026-09-28
|
||||
|
||||
This report preserves the earlier failed observations. A later
|
||||
[startup and post-USB test](MTS_MODEM_DIAGNOSTIC_20260928.md) established a working
|
||||
MTS SIM-2 path with the same configuration and completed the previously queued
|
||||
position request. The earlier failure's cause remains unresolved.
|
||||
|
||||
Private experiment `mts-path-34f895b1aaa54313870ebe88842ca17a` observed the
|
||||
existing VPS receiver on TCP 9922 without changing device settings, firmware,
|
||||
firewall or service. Core remained the outbound API client. B2 used external
|
||||
power; no USB operation was performed during the TCP capture. The subsequent
|
||||
phone test and read-only USB inspection are recorded separately below.
|
||||
|
||||
## Method and result
|
||||
|
||||
A bounded tcpdump on the VPS captured both directions on TCP 9922 only, with
|
||||
96-byte snapshots. The established MegaFon control path yielded 37 inbound
|
||||
packets and four inbound SYNs before the owner confirmed the first change.
|
||||
Core telemetry was also recorded, preserving measurement and receipt times.
|
||||
|
||||
The owner powered off, removed MegaFon from SIM 1, retained MTS in SIM 2 and
|
||||
powered on. For 308.453 seconds between owner reports there were **zero incoming
|
||||
packets** on the receiver port. The only two captured packets were outbound
|
||||
resets closing predecessor connections. This is a lower bound after the
|
||||
confirmation, not an exact power-on duration.
|
||||
|
||||
The owner then moved MTS into SIM 1 and restarted B2. During the next
|
||||
363.649 seconds after that report there were **zero packets in either direction**
|
||||
on the receiver port. This is not a controlled slot comparison: slot 1 retained
|
||||
its previous `internet` APN and credentials, while slot 2 had the verified
|
||||
public MTS profile (`internet.mts.ru`). No APN was changed during this test.
|
||||
|
||||
The capture ended with 82 packets captured, 82 received by filter, and zero
|
||||
kernel drops. Receiver service remained active. Private PCAP SHA-256:
|
||||
`5a2f27b6371b397545d1249778a31a5af365b808fe3a6527243250f18389b405`.
|
||||
The capture and local temporary observer were stopped.
|
||||
|
||||
## Device evidence and interpretation
|
||||
|
||||
The owner reported one long and three short blue flashes during the SIM-2
|
||||
phase. The [B2 manual](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf)
|
||||
describes this as cellular search/registration and more than eight satellites.
|
||||
|
||||
An additional analysis of the previous night's delayed SIM-2 records found
|
||||
28 distinct DS2 observations with GPRS state 4 and all four server states zero
|
||||
(closed/not used). The present MegaFon baseline had server 1 and 2 states 2
|
||||
(connected). These are recorded device states, not independent proof of a
|
||||
usable packet-data path. The difference from the observed LED is unresolved.
|
||||
|
||||
No new tracker session reached our receiver during either MTS-only interval.
|
||||
The evidence does not identify whether the issue is in modem/SIM configuration,
|
||||
the mobile service or the upstream path, and does not prove a damaged SIM slot.
|
||||
It also does not qualify MTS as a working backup channel.
|
||||
|
||||
## Runtime during the capture
|
||||
|
||||
One position request was persisted during the outage. At this capture's close
|
||||
it was in `waiting-link`, with zero attempts; the same identity was retained for recovery.
|
||||
There was no configuration or output command. A lost reply must not be confused
|
||||
with this never-dispatched request.
|
||||
|
||||
## Phone hotspot test
|
||||
|
||||
The owner removed all SIM cards from B2, put this MTS SIM in a phone and connected
|
||||
the Mac to that phone's hotspot. Session
|
||||
`phone-15c0af3223b64a5b96a2461437aae19d` bound every probe to the physical `en0`
|
||||
interface; the Mac's default VPN route was not used. No route, VPN, firewall or
|
||||
device settings were changed.
|
||||
|
||||
TCP connection to receiver port 9922 succeeded in 0.062 seconds and API port
|
||||
19443 in 0.061 seconds. An authenticated, certificate-pinned read of VPS status
|
||||
succeeded in 0.250 seconds and reported version 0.1.37. No tracker identity or
|
||||
command was sent on the receiver connection. All temporary probes completed;
|
||||
raw evidence and its hash manifest remain in the private session directory.
|
||||
|
||||
Thus this SIM's owner-confirmed phone Internet path can reach both VPS ports.
|
||||
This does not qualify the B2 modem's 2G path or identify the cause of its failure.
|
||||
The phone hotspot is no longer needed for this completed measurement; the Mac
|
||||
can return to its ordinary Wi-Fi connection.
|
||||
|
||||
## USB observation and automatic APN investigation
|
||||
|
||||
With B2 still containing no SIM cards and powered externally, the owner connected
|
||||
the existing damaged USB cable and held it still. One qualified read in session
|
||||
`usb-mts-slot1-d2a5482f40bb402aa3b51abec0705158` identified the expected B2 with
|
||||
firmware 0.01 and returned 207 configuration records, 983 bytes, SHA-256
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
SIM 1 retained APN `internet`, SIM 2 `internet.mts.ru`; GPRS was allowed for both.
|
||||
|
||||
A proposed diagnostic write of the public MTS settings to slot 1 stopped at its
|
||||
local preflight, before target construction or any device write. The conservative
|
||||
check encountered the already queued position request. This was not a failed
|
||||
write to B2. The owner then asked to resolve automatic configuration when SIM
|
||||
cards are replaced; no new USB settings were written.
|
||||
|
||||
The model-231 manufacturer configuration schema exposes separate APN/login/
|
||||
password settings for slots 1 and 2 (67–69 and 89–91). The B2 manual documents
|
||||
explicit APN assignment and clearing it, but does not establish that an empty APN
|
||||
or the string `auto` enables automatic selection. Network codes already observed
|
||||
in telemetry demonstrate network identification; that is separate from selecting
|
||||
Internet credentials. Native automatic APN selection for this B2 firmware remains
|
||||
unconfirmed. Instructions for other ARNavi models must not be treated as B2
|
||||
capability evidence.
|
||||
|
||||
The product must not bind a carrier permanently to a slot. Any future automatic
|
||||
APN workflow needs qualified SIM/network detection and an available configuration
|
||||
path: a VPS-only repair cannot reach a tracker whose sole Internet path is broken.
|
||||
A controlled MTS slot comparison still requires known appropriate settings in
|
||||
each tested slot. The subsequent diagnostic linked above restored the SIM-2
|
||||
path without a configuration write and checked the existing queued request by
|
||||
its identity rather than replacing it. A controlled two-slot comparison remains
|
||||
unperformed.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Режим двух SIM без заданного APN в Mission Core
|
||||
|
||||
28.09.2026. Продолжение [аппаратной матрицы двух карт и двух слотов](MTS_SLOT1_EMPTY_APN_20260928.md).
|
||||
Используется штатная B2 231 / 0.01 и собственный VPS 0.1.41. Прошивка не менялась.
|
||||
|
||||
## Поведение продукта
|
||||
|
||||
В существующем разделе «Сервер и связь» добавлен режим
|
||||
**«Обе SIM — без заданного APN»**. Его можно применять через VPS и сохранять
|
||||
в обычный профиль для первоначальной настройки следующего B2 по USB.
|
||||
|
||||
- `connectivity.strategy=native` очищает поля 67/68/69 и 89/90/91 целиком,
|
||||
включая логины и пароли. Снимает только запреты GPRS в битах 10/20 поля 72.
|
||||
- Остальные записи конфигурации сохраняются, если они отдельно не изменены
|
||||
профилем. Отсутствующие обязательные поля отклоняют подготовку целиком.
|
||||
- Это явное действие пользователя. Чтение конфигурации, появление неизвестной
|
||||
SIM или сохранение прочих параметров сами по себе не включают данный режим.
|
||||
- Прежний `both` отображается как «Обе SIM — сохранить APN» и не очищает
|
||||
параметры специальных/корпоративных тарифов. Старые профили не мигрируются.
|
||||
- Одиночные варианты подписаны «Только SIM …»: они по-прежнему реализуют
|
||||
исключительный выбор и запрещают интернет другой SIM. Они не представлены
|
||||
как предпочтение с резервированием.
|
||||
- Подпись состояния 0 больше не утверждает физическую пустоту слота: B2
|
||||
может не сообщать о вставленной неактивной карте до перехода на неё.
|
||||
Фиктивная карта не добавляется в список, старый оператор не подставляется.
|
||||
|
||||
Использованы существующие `Select`, `SettingsCard`, `StatusBadge` и окно
|
||||
настроек по product-ui canon; новой страницы, визуального компонента или CSS
|
||||
нет. Убран локальный дубликат выбранного режима: поле отражает текущий профиль,
|
||||
включая загрузку другого профиля в открытом окне.
|
||||
|
||||
## Выполнение через VPS
|
||||
|
||||
Явный выбор режима, изменение запретов либо очистка непустых полей создают
|
||||
существующую долговечную операцию `select-sim` с `sim_policy=both`.
|
||||
Она сначала читает текущую конфигурацию, проверяет предшественника, при
|
||||
необходимости записывает и читает обратно целевой образ, затем выполняет
|
||||
штатный перезапуск и ждёт нового соединения со свежим GPRS через любой слот.
|
||||
Одна только проверка записанного образа не объявляется успешным подключением.
|
||||
|
||||
Для этой политики не требуется устаревшая идентичность определённой карты:
|
||||
настройка явно относится к обоим слотам. Существующая защита привязанных
|
||||
к карте операторских параметров сохранена. Ни APN-каталог, ни искусственная
|
||||
подмена названия оператора для native не используются.
|
||||
|
||||
Применение сохранённого native-профиля при уже совпадающих полях и запретах
|
||||
не превращает несвязанную правку в постоянный перезапуск модема. Повторное
|
||||
«Сохранить настройки» без изменений не создаёт новую команду. Явный повторный
|
||||
выбор режима сохраняет прежнюю семантику отдельного пользовательского действия.
|
||||
|
||||
VPS не обновлялся: используется его существующий контракт обеих разрешённых
|
||||
SIM. Core продолжает опрашивать VPS; входящий канал VPS → Core не добавлен.
|
||||
|
||||
## Аппаратная приёмка через интерфейс
|
||||
|
||||
Приватная сессия `native-policy-b41f534e55054955b861d1cce8367376` хранится в outputs;
|
||||
содержит исходный образ, снимок экземпляра, резервные копии БД Core перед
|
||||
штатной перезагрузкой приложения, результаты VPS и временную шкалу.
|
||||
|
||||
Условия по последнему подтверждению владельца: только МегаФон в SIM 2,
|
||||
SIM 1 пуст, питание 12 В сохраняется, USB отсутствует. Перед нажатием кнопки
|
||||
проверено: целевой образ нового режима **уже побайтово совпадает** с текущим
|
||||
аппаратным образом SHA-256
|
||||
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
|
||||
Других желаемых изменений нет. Этот опыт проверяет полный пользовательский
|
||||
путь, чтение и перезапуск; он не выдаётся за новую физическую очистку полей.
|
||||
Физическая очистка ранее квалифицирована в аппаратной матрице.
|
||||
|
||||
В открытом Mission Core выбран новый режим и нажата «Сохранить настройки».
|
||||
Операция `c32d4ff183844614a3cdd837ae0ce3c0`, одна попытка:
|
||||
|
||||
| Событие | UTC |
|
||||
| --- | --- |
|
||||
| Операция принята VPS | 15:09:18.307 |
|
||||
| Совпадение конфигурации подтверждено | 15:09:21.122 |
|
||||
| Штатная команда перезапуска отправлена | 15:09:21.134 |
|
||||
| Новый сеанс со свежим GPRS SIM 2 подтверждён | 15:10:08.837 |
|
||||
|
||||
От отправки перезапуска до подтверждения — 47.703 с, от принятия операции —
|
||||
50.530 с. Результат `sim_selected`, активная SIM 2, `unchanged=true`.
|
||||
В следующем контрольном снимке получены свежие координаты и сеть МегаФона
|
||||
через SIM 2; временная задержка проекции Core учтена отдельно от результата VPS.
|
||||
|
||||
Окно во время операции осталось открытым, показывало ожидание новой связи,
|
||||
после завершения разблокировало действия. Через кнопку «Сохранить профиль»
|
||||
создан **«ARNavi B2 — обе SIM, без APN»**. API подтвердил сохранение native
|
||||
без IMEI/SIM-идентичности. Повторное сохранение устройства без изменений
|
||||
оставило тот же ID завершённой операции: дополнительного перезапуска нет.
|
||||
Визуально проверены форма, меню, правый footer и Escape для меню.
|
||||
|
||||
## Проверки и оставшаяся граница
|
||||
|
||||
Пройдены focused Python-проверки native/both, операторских настроек, сетевого
|
||||
журнала, регистрации и bootstrap; 32 связанных frontend-проверки, Ruff,
|
||||
TypeScript и production build. Канонический Core оставлен на 8000.
|
||||
|
||||
Режим подтверждён на имеющихся МТС и МегаФоне. Это не утверждение о каталоге
|
||||
операторов внутри B2 или гарантии для любого тарифа. Ручное предпочтение SIM
|
||||
с сохранением второго канала, своевременный опрос неактивного слота и свежая
|
||||
идентичность после горячей замены остаются открытыми аппаратными вопросами.
|
||||
В просмотренных [руководстве B2](https://8888.arusnavi.ru/Arnavi%20B2/)
|
||||
и таблице SERVER_COM не установлена подходящая команда предпочтения.
|
||||
Пост производителя об изменениях APN прошивки 0.43 относится к L1/L2/A1/A2/A3,
|
||||
а не B2, поэтому не используется как основание менять прошивку этого трекера.
|
||||
@@ -0,0 +1,319 @@
|
||||
# Нативная логика SIM: пустые APN и горячие переходы
|
||||
|
||||
Продолжение анализа сетевых задержек и исправление отправителя VPS:
|
||||
[доставка команд, TCP и свежесть соединения](TRANSPORT_EVIDENCE_20260928.md).
|
||||
|
||||
Дополнительные физические проверки закрыли обе карты в обоих слотах:
|
||||
[МТС SIM 1 и МегаФон SIM 2 с пустыми APN](MTS_SLOT1_EMPTY_APN_20260928.md).
|
||||
Последний переход с МТС SIM 1 на МегаФон SIM 2 выполнен без нашей команды
|
||||
переключения, перезапуска и отключения питания; разрыв свежего потока 44.799 с.
|
||||
После перехода ответ на команду и полное чтение получены с первой попытки,
|
||||
конфигурация с двумя пустыми тройками параметров осталась неизменной.
|
||||
|
||||
Продолжение по распоряжению владельца: исследовать саму прошивку и не ждать
|
||||
ответа производителя. Тестовый B2 разрешено экспериментально изменять.
|
||||
Отсутствие резервного образа установленной 0.01 явно разъяснено; настройки
|
||||
и архивные 0.05/0.06 не дают гарантии возврата к 0.01.
|
||||
|
||||
## Подтверждённая исходная точка
|
||||
|
||||
Сессия `native-sim-c7c154e1886344a7b81ca13432312891`. 28.09.2026,
|
||||
12:59:53 UTC создано штатное долговечное чтение конфигурации через Core → VPS.
|
||||
При проверке 13:00:25 UTC оно завершено с первой попытки, состояние `observed`.
|
||||
Трекер передаёт свежие пакеты через SIM 1, SIM 2 сообщает отсутствие карты.
|
||||
Последние физические условия владельца: МегаФон в первом, второй пустой,
|
||||
внешнее питание 12 В, без USB. По сетевому сообщению нельзя подтвердить наличие
|
||||
или отсутствие физического USB — это условие со слов владельца.
|
||||
|
||||
Сохранён полный исходный конфигурационный образ: 207 записей, SHA-256
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
Оба запрета GPRS сняты, APN 1 — `internet`, APN 2 — `internet.mts.ru`.
|
||||
Исходные байты и журнал с UTC/монотонным временем хранятся приватно в outputs.
|
||||
Это свежая копия конфигурации, не новый дамп исполняемой прошивки.
|
||||
|
||||
## Противоречие, которое нельзя скрывать в автоматизации
|
||||
|
||||
`profiles.prepare` при `strategy=sim, activate=true` ставит запрет GPRS
|
||||
противоположному слоту (поле 72). VPS `select-sim` затем перезапускает B2 и
|
||||
подтверждает новый сеанс. Эта операция доказывает исключительный выбор,
|
||||
но противоречит требованию постоянно разрешённого резервного канала.
|
||||
Значение `both` оставляет решение внутреннему алгоритму B2; оно сейчас применено.
|
||||
|
||||
Отправлять после эксклюзивного выбора вторую команду «снять запрет» не решает
|
||||
проблему: если выбранный канал не заработает, вторая команда не достигнет B2.
|
||||
Без подтверждённого локального таймера или иной команды такой двухшаговый
|
||||
механизм не вводится как гарантированное резервирование.
|
||||
|
||||
## Статический анализ файлов и конфигуратора
|
||||
|
||||
Проверены неизменённые образы производителя, SHA указаны в
|
||||
[перечне исходных файлов](FIRMWARE_BASELINE_20260928.md).
|
||||
|
||||
| Файл | Байт | Энтропия, бит/байт | Остаток размера по 16 |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| B2 0.05 | 155824 | 7.99874 | 0 |
|
||||
| B2 0.06 | 157760 | 7.99889 | 0 |
|
||||
|
||||
В найденных печатных строках этих файлов нет APN/SIM/версии/идентификатора
|
||||
архитектуры. Это совместимо с упаковкой или шифрованием, но **не определяет**
|
||||
алгоритм и не доказывает криптографическую защиту. Исполняемый код внутреннего
|
||||
алгоритма SIM не извлечён; произвольную правку байтов нельзя выдавать за его
|
||||
осмысленную кастомизацию.
|
||||
|
||||
Официальный PC Configurator исследовался статически, без запуска EXE:
|
||||
SHA-256 `f79af698160ce6009c58608ec5511fab1680eea472ba9d689835fb032f2fc6ec`.
|
||||
В найденной ветке локальной загрузки:
|
||||
|
||||
- выбирается файл `.dfw`; отображаемые major/minor извлекаются из имени;
|
||||
- подготовлен переход командой `>D 3;0` и поиск тома загрузчика
|
||||
`BH24` либо `LOADER_…`;
|
||||
- другая ветка читает выбранный файл порциями и формирует контрольную сумму
|
||||
для передачи; строка «Ошибка чтения данных из firmware» относится к этому
|
||||
чтению файла, а не к экспорту прошивки из трекера.
|
||||
|
||||
Команды загрузчика не отправлялись. Общий код конфигуратора ещё не доказывает
|
||||
применимость каждой его ветки именно к B2. В этих фрагментах не найден механизм
|
||||
редактирования APN-каталога внутри `.dfw`. Точные фрагменты дизассемблирования
|
||||
и измерения сохранены в приватной сессии. Поиск/идентификация формата остаются
|
||||
отдельной инженерной задачей.
|
||||
|
||||
## Ближайшая физическая проверка
|
||||
|
||||
Проверить, даёт ли сама B2 соединение с пустыми APN/логином/паролем.
|
||||
Публичное руководство ARNavi 5 описывает это как автоматический режим,
|
||||
но переносить его на B2 без проверки нельзя. В руководстве B2 есть явная
|
||||
очистка APN; результат работы после очистки для этой прошивки пока неизвестен.
|
||||
|
||||
Подготовлен, **не применён**, образ для очистки только полей 89/90/91 (SIM 2).
|
||||
SHA-256: `a7b3eabf7988b1ba388d6695290e75716f039d3c98490b9bb44d2e3b48fa681b`.
|
||||
Проверено побайтово: настройки SIM 1, разрешения обоих слотов, адреса серверов
|
||||
и прочие записи сохраняются.
|
||||
|
||||
1. Подтвердить наличие МТС, установить её во второй слот по сигналу записи,
|
||||
оставив МегаФон в первом и питание включённым.
|
||||
2. Получить исходное состояние, записать подготовленные пустые параметры
|
||||
SIM 2 через VPS и подтвердить их независимым чтением.
|
||||
3. Извлечь активный МегаФон без отключения питания. Никаких команд выбора
|
||||
слота, запрета GPRS или перезапуска в фазе наблюдения не отправлять.
|
||||
4. Сопоставить время последнего пакета SIM 1, данные перехода, первое свежее
|
||||
сообщение SIM 2 и её реальные ответы. Старую накопленную телеметрию
|
||||
учитывать отдельно. Если связи нет, вернуть МегаФон; исходные параметры
|
||||
доступны для восстановления через сохранившийся канал.
|
||||
5. После восстановления прочитать фактические APN и сравнить с целевым образом.
|
||||
Успех соединения с пустыми полями доказывает только этот сценарий/карту;
|
||||
он не отличает автоподбор от APN по умолчанию или допуска пустого APN сетью.
|
||||
Для этого нужны дополнительные наблюдения модема и другие карты.
|
||||
|
||||
## Начало аппаратного опыта
|
||||
|
||||
Владелец подтвердил наличие МТС. Перед сигналом установки в 13:10:38.262 UTC
|
||||
сохранён курсор журнала пакетов 18268 и монотонное время. SIM 1 передавала
|
||||
свежие пакеты, SIM 2 сообщала отсутствие карты.
|
||||
|
||||
В 13:12:21.458 UTC записано подтверждение владельца: МТС установлена во второй
|
||||
слот, МегаФон остаётся в первом, питание не отключалось, USB не подключён.
|
||||
Это время получения подтверждения, а не точный момент физической установки.
|
||||
SIM 2 продолжала сообщать состояние 0; такое значение не опровергает
|
||||
физическую установку, пока неактивный слот не опрошен самим модемом.
|
||||
|
||||
В 13:14:41.112 UTC собственный VPS принял операцию `configure-all`
|
||||
`9caac38f79d54ef69cd52398641023fc` через существующий долговечный рантайм.
|
||||
Перед этим очереди Core/VPS проверены на отсутствие другой ожидающей работы.
|
||||
Исходный образ прочитан устройством повторно и совпал с SHA выше. Целевая
|
||||
запись очищает только поля 89/90/91; SIM 1, разрешения обоих слотов и серверы
|
||||
сохранены. В 13:15:42.122 UTC VPS передал ответ с целевыми настройками.
|
||||
В 13:16:19.188 UTC независимое чтение подтвердило побайтовое совпадение
|
||||
с целевым SHA `a7b3eabf7988b1ba388d6695290e75716f039d3c98490b9bb44d2e3b48fa681b`:
|
||||
операция завершилась `verified` за одну попытку. Поля 89/90/91 действительно
|
||||
пусты, APN SIM 1 остался `internet`, оба запрета GPRS сняты. Прошивка
|
||||
и питание в этой операции не изменялись.
|
||||
|
||||
В 13:17:02.259 UTC зафиксирован курсор 18322 перед сигналом вынуть только
|
||||
МегаФон. Владелец получил инструкцию оставить МТС в SIM 2 и питание 12 В,
|
||||
без USB и переключений в интерфейсе.
|
||||
|
||||
## МТС с пустыми APN, логином и паролем: связь подтверждена
|
||||
|
||||
В 13:18:51.677 UTC записано подтверждение владельца: МегаФон вынут,
|
||||
МТС остаётся во втором слоте, питание не отключалось. В фазе перехода
|
||||
команды выбора слота, запрета GPRS и перезапуска не отправлялись.
|
||||
|
||||
| Событие | UTC |
|
||||
| --- | --- |
|
||||
| Последний свежий пакет с SIM 1 | 13:18:33.002 |
|
||||
| Первое получение накопленных пакетов после перехода | 13:19:26.394 |
|
||||
| Первое свежее измерение SIM 2 / GPRS 4 | 13:19:25.000 |
|
||||
| Получение этого свежего пакета на VPS | 13:19:32.237 |
|
||||
| Отправка тестового запроса координат | 13:20:05.277 |
|
||||
| Подтверждение B2, код 0 | 13:20:06.455 |
|
||||
|
||||
Первый свежий пакет SIM 2 содержит координату и сеть 250-01, сигнал 23/31,
|
||||
SIM 1 отсутствует. Разрыв между последним свежим пакетом SIM 1 и первым
|
||||
свежим SIM 2 — 59.235 с; от получения подтверждения владельца — 40.561 с.
|
||||
Это не точное время от физического извлечения: оно произошло раньше
|
||||
подтверждения. В накопленных сообщениях есть переход отсутствия SIM 1
|
||||
к регистрации SIM 2; порядок получения отличается от порядка измерений.
|
||||
Старые сообщения не принимаются за свежую связь.
|
||||
|
||||
Операция `request-position` `eeb05a1e6c76485f8bc8ee7484d81b3e` выполнена
|
||||
с первой попытки, подтверждение за 1.178 с. Повторное штатное чтение через
|
||||
Core (`1a19032d86bf4128977c0f419001239d`, `observed`, первая попытка)
|
||||
вернуло тот же целевой SHA. APN/логин/пароль SIM 2 остались пустыми; фактическая
|
||||
конфигурация обновлена также в Core. Возвращать исходный APN ради связи
|
||||
не понадобилось.
|
||||
|
||||
## Повторное подключение после программного перезапуска
|
||||
|
||||
После завершения фазы горячего перехода отдельно отправлена штатная команда
|
||||
перезапуска `68b3038119e842d5aaf998c23c6cfb85` — 13:22:15.104 UTC.
|
||||
Новый сеанс зафиксирован в 13:23:02.157 UTC, операция `reconnected`, одна
|
||||
попытка; 47.053 с от отправки. Питание и карты пользователь не менял.
|
||||
Свежая телеметрия SIM 2 / GPRS 4 измерена в 13:23:12 и получена в 13:23:16.294.
|
||||
Сам факт нового сеанса не доказывает очистку всех внутренних/NVRAM-кэшей
|
||||
модема. Он подтверждает повторный выход в сеть после команды перезапуска
|
||||
с конфигурацией, где параметры SIM 2 пусты.
|
||||
|
||||
Последующее полное чтение `a819c30cc57f4ed486a80edbe6388f58` принято в
|
||||
13:25:15.560 UTC. Первая попытка, отправленная в 13:25:21.546, закончилась
|
||||
`unconfirmed`; телеметрия при этом продолжала поступать. Тот же долговечный
|
||||
запрос автоматически создал вторую попытку, отправленную в 13:28:25.231.
|
||||
В 13:28:27.877 получена конфигурация с тем же SHA, состояние `observed`.
|
||||
Полное время запроса — 192.317 с, время второй отправки до чтения — 2.646 с.
|
||||
Дополнительного ручного запроса или перезапуска для восстановления не было.
|
||||
Причина отсутствия ответа в первой попытке не установлена; единичный быстрый
|
||||
ACK не является гарантией постоянной задержки всего управляющего канала.
|
||||
|
||||
Дополнительный запрос координат после перезапуска не отправлялся:
|
||||
инженерная проверка остановила его до создания ID, поскольку на тот момент
|
||||
последний пакет был старше 30 с. Повтор такого запроса не выполнялся;
|
||||
ответом после перезапуска служит самостоятельное успешное чтение выше.
|
||||
|
||||
## Практический вывод и границы
|
||||
|
||||
На текущем B2 0.01 данная МТС работает без заданных в конфигурации APN,
|
||||
логина и пароля — при горячем переходе и после программного перезапуска.
|
||||
Для этого случая кастомизация прошивки не потребовалась. Это не доказательство
|
||||
встроенного каталога всех операторов: остаются варианты выбора APN устройством,
|
||||
допуска пустого APN оператором и внутреннего состояния модема.
|
||||
Другие SIM/тарифы, корпоративные APN, МТС в первом слоте, МегаФон во втором
|
||||
с пустыми параметрами и ручной приоритет без блокировки резерва требуют
|
||||
отдельной проверки. Пустые группы одновременно проверены ниже. Задержка
|
||||
обнаружения неактивной карты этим опытом не устранена.
|
||||
|
||||
## Следующая проверка: МегаФон без прописанного APN
|
||||
|
||||
Подготовлен образ с пустыми полями 67/68/69 первого слота.
|
||||
Вторая группа 89/90/91 остаётся пустой и совпадает с успешно прочитанной
|
||||
конфигурацией МТС; прочие записи неизменны. SHA целевого образа:
|
||||
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
|
||||
|
||||
В 13:29:58.642 UTC сохранён курсор 18410 перед инструкцией вернуть МегаФон
|
||||
в первый слот, оставив МТС во втором и непрерывное питание. Подтверждение
|
||||
владельца получено в 13:31:31.614 UTC. В 13:31:32.928 принята операция
|
||||
`0ab723fff3354433ab90c39d715c0bb4`; в 13:33:08.124 независимым чтением
|
||||
подтверждён целевой SHA, `verified`, одна попытка. Обе группы APN/логина/пароля
|
||||
теперь пусты; обе SIM разрешены. МТС продолжает передавать свежие данные,
|
||||
добавленный неактивный первый слот по-прежнему сообщает состояние 0.
|
||||
|
||||
В 13:34:00.171 UTC сохранён курсор 18437 перед инструкцией вынуть только
|
||||
МТС и оставить МегаФон в SIM 1 при непрерывном питании. Подтверждение
|
||||
владельца записано в 13:36:01.221 UTC; первый свежий пакет МегаФона пришёл
|
||||
раньше этой записи, поэтому задержку от физического действия по времени
|
||||
подтверждения здесь не вычисляем. В фазе перехода команды выбора SIM
|
||||
и перезапуска не отправлялись.
|
||||
|
||||
Последний свежий пакет SIM 2 получен в 13:34:52.076 UTC. Первое свежее
|
||||
измерение SIM 1 / GPRS 4 — 13:35:33, получение — 13:35:36.184. Разрыв между
|
||||
свежими пакетами разных слотов — 44.108 с. В пакете есть координата, сеть
|
||||
250-02, сигнал 23/31, отсутствие SIM 2. Операция `request-position`
|
||||
`08e40e186a9b4153af431b4806483e54` отправлена в 13:36:37.004, подтверждена
|
||||
кодом 0 в 13:36:40.707; одна попытка, 3.703 с. Это подтверждает выход данной
|
||||
карты МегаФон и двусторонний обмен с пустыми параметрами первого слота.
|
||||
|
||||
## Пауза связи во время контрольного чтения на МегаФоне
|
||||
|
||||
Штатное чтение `6fc32694766845109a3e7948245542dd` принято в 13:37:19.564,
|
||||
первая попытка отправлена в 13:37:25.239 UTC. Последний обычный пакет был
|
||||
получен в 13:37:25.648; после этого перестали приходить и настройки,
|
||||
и мониторинговая телеметрия. Около 13:39 Core честно показал устаревшую
|
||||
позицию и отсутствие свежей связи. Совпадение по времени с командой
|
||||
не доказывает причину: APN, транспорт и поведение прошивки не разделены.
|
||||
|
||||
Ограниченный захват на собственном VPS с 13:39:17.960 до 13:40:48.956
|
||||
для TCP-порта трекера 9922 содержит только заголовок PCAP, ноль пакетов.
|
||||
Захват начат после возникновения паузы и не устанавливает, был ли первый
|
||||
запрос чтения подтверждён TCP. Процесс завершился по собственному таймеру;
|
||||
он не отправлял команд трекеру и не менял сеть сервера.
|
||||
|
||||
К 13:41:11 UTC запрос перешёл в ожидание связи, сохранив тот же ID и одну
|
||||
попытку. Новая команда и слепая повторная запись настроек не создавались.
|
||||
В 13:41:38.095 зафиксирован курсор 18464 и выдана инструкция вернуть МТС
|
||||
во второй слот, оставив МегаФон в первом и питание включённым.
|
||||
|
||||
Связь восстановилась через SIM 1 до следующей команды оператора.
|
||||
Последнее уточнение владельца: МТС **не вставлялась**, в устройстве всё время
|
||||
оставался только МегаФон в SIM 1. Более ранний ответ кнопкой «Да» владелец
|
||||
явно исправил; в выводах используется его последнее недвусмысленное уточнение.
|
||||
Просьба добавить резерв отменена; вмешательства питанием/USB не было.
|
||||
|
||||
Первый пакет после паузы получен в 13:43:00.629 UTC: разрыв приёма —
|
||||
334.982 с. В последующей выгрузке найдены 14 разных измерений с координатами,
|
||||
сделанных во время паузы; это доказывает буферизацию части телеметрии, но не
|
||||
полноту записи всей траектории. Внутренние статусы за этот период показывают
|
||||
SIM 1 и GPRS 3/4. Причина затянувшегося восстановления не установлена.
|
||||
|
||||
Тот же запрос чтения завершился `observed` со второй попытки:
|
||||
отправка 13:42:59.251, получение конфигурации 13:43:01.308 UTC. Вся операция
|
||||
заняла 341.745 с. Полный образ совпал с SHA пустых параметров **обоих** слотов;
|
||||
Core сохранил этот фактически прочитанный образ. Повторного изменения
|
||||
настроек, отдельного ручного запроса или команды перезапуска для восстановления
|
||||
не было. Этот результат подтверждает сохранность намерения в рантайме,
|
||||
но не устраняет пятиминутную паузу связи устройства.
|
||||
|
||||
## Контрольное чтение с записью TCP до отправки
|
||||
|
||||
С теми же настройками и только МегаФоном в SIM 1 выполнено ещё одно чтение
|
||||
`7adb124ecf51457e9f99148f1073a387`. Захват TCP на собственном VPS был
|
||||
подтверждён заголовком PCAP до создания запроса; ограничение — 120 с / 500
|
||||
пакетов. Фактически записано 95 TCP-пакетов. Процесс завершился по таймеру.
|
||||
|
||||
| Событие | UTC / задержка |
|
||||
| --- | --- |
|
||||
| Принят запрос чтения | 13:47:21.529 |
|
||||
| Команда `SERV*1.9` в TCP-записи | 13:47:37.689 |
|
||||
| TCP ACK от B2 | через 0.437 с |
|
||||
| Полная загрузка конфигурации, opcode 5 | 13:47:40.043 |
|
||||
| VPS сохранил фактический образ | 13:47:40.046 |
|
||||
| HTTP-ответ собственного VPS | 13:47:40.052 |
|
||||
|
||||
Одна попытка, 18.517 с от принятия запроса, 2.362 с от отправки до сохранения
|
||||
полной конфигурации. Образ снова совпал с SHA `624d6b…e99e383`.
|
||||
После чтения в оставшемся окне захвата продолжалась телеметрия; предыдущая
|
||||
длительная пауза не воспроизвелась. Следовательно, нельзя объявлять её
|
||||
неизбежным следствием каждого чтения. Захват успешного запроса также
|
||||
не объясняет транспортную причину предыдущего неудачного.
|
||||
|
||||
## Итог этого этапа и состояние устройства
|
||||
|
||||
- На неизменённой прошивке 0.01 обе имеющиеся карты смогли подключиться
|
||||
без прописанных APN/логина/пароля: МТС в SIM 2 и МегаФон в SIM 1.
|
||||
- Горячие переходы после извлечения активной карты произошли без команды
|
||||
выбора слота/перезапуска и без отключения питания: разрывы между свежими
|
||||
пакетами 59.235 и 44.108 с соответственно.
|
||||
- Проверены ответы на команды, запись и независимое чтение конфигурации;
|
||||
МТС также повторно подключилась после отдельной программной перезагрузки.
|
||||
- Два чтения завершились только со второй попытки; одно сопровождалось
|
||||
паузой мониторинга 334.982 с. Быстрый ACK не означает стабильности всей цепи.
|
||||
- Неактивный вновь вставленный слот продолжал сообщать отсутствие карты
|
||||
до переключения модема. Пустые APN не решают это ограничение обнаружения.
|
||||
- Сейчас физически только МегаФон в SIM 1, SIM 2 пустой, питание 12 В,
|
||||
без USB. Обе SIM разрешены, обе группы доступа пусты; настройки подтверждены
|
||||
через штатное чтение Core. Прошивка, серверы и прочие настройки не менялись.
|
||||
|
||||
Не включать это как доказанную универсальную автоматическую настройку всех
|
||||
операторов: данные относятся к двум конкретным картам и указанным слотам.
|
||||
Следующее направление — объяснить и сократить восстановление канала при
|
||||
сохранении долговечных операций, затем проверить карты в противоположных
|
||||
слотах и вынести квалифицированный режим в первичную настройку. Кастомизация
|
||||
прошивки ради этих двух подключений не понадобилась; поведение неактивного
|
||||
слота и ручной приоритет остаются отдельными вопросами.
|
||||
@@ -0,0 +1,90 @@
|
||||
# B2 network configuration: qualified endpoint change
|
||||
|
||||
This document records the original Host 0.1.6 endpoint-only acceptance. Current
|
||||
full-profile network support, owner configuration endpoint and post-restart
|
||||
qualification are described in [autonomy and commands](AUTONOMY_AND_COMMANDS.md).
|
||||
The historical limitations below must not be read as the current feature list.
|
||||
|
||||
## Accepted scope, 2026-09-26
|
||||
|
||||
B2 model 231, firmware 0.01, can change its **first monitoring server address and
|
||||
port** through the owner's VPS (Host 0.1.6). The already configured second server
|
||||
must remain the current VPS. A real change and reversal completed over INTERNAL;
|
||||
independent USB reading after reversal was byte-identical to the initial backup.
|
||||
USB was used only as independent qualification evidence, never to perform these
|
||||
writes. The owner's first server migration can now run from Core settings.
|
||||
|
||||
This is not full-profile network support. Trajectory, sensor thresholds, APN,
|
||||
other server slots and vendor-web polling are not admitted network writes.
|
||||
Unchanged fields in the saved profile may remain present; if comparison against
|
||||
the last USB baseline finds any other requested changes, Core rejects the entire
|
||||
network operation before dispatch. A verified endpoint never marks all 78 USB
|
||||
profile parameters as remotely applied.
|
||||
|
||||
## Protocol authority
|
||||
|
||||
- [B2 manufacturer documentation](https://8888.arusnavi.ru/Arnavi%20B2/), manual
|
||||
sections 9.3–9.4: GETP and SETP #1 host/port, omitted parameters preserved.
|
||||
- [Manufacturer INTERNAL protocol](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit), SERVER_COM and SMS:
|
||||
FC Windows-1251 text, one-byte length, sum checksum, asynchronous TCP commands.
|
||||
|
||||
The operation sends `password*SETP*#1=host,port` (under 160 ASCII characters).
|
||||
It does not alter protocol, ID, the undocumented fifth server value or any other
|
||||
group. It requires the qualified group shape: INTERNAL, ID zero, empty fifth
|
||||
value. Core also requires registered, reachable source and target hosts assigned
|
||||
to the same vehicle. Credentials come from private enrollment evidence and never
|
||||
from portable profiles or browser requests.
|
||||
|
||||
## Durable state and readback
|
||||
|
||||
1. Core persists operation ID and requested revision before POST. Lost POST
|
||||
responses are reconciled by GET; Core never blindly resubmits. USB operations,
|
||||
desired settings changes and tracker reassignment are blocked while pending.
|
||||
2. VPS admits one pending operation per IMEI, expiring after 120 seconds.
|
||||
3. Fresh GETP must match the expected primary and show this VPS as secondary.
|
||||
An unexpected configuration stops the write. All returned groups are retained
|
||||
privately as the precondition/baseline.
|
||||
4. Dispatch is committed before sending. SETP is sent at most once. Receipt is
|
||||
not proof of application. Restart during any uncertain stage never replays it.
|
||||
5. After at least 15 seconds, a separate GETP verifies the target endpoint and
|
||||
equality of every other reported group. Only this read may move to a new TCP
|
||||
session following a reconnect; its answer must belong to that session.
|
||||
6. Core exposes only endpoint, stage, timestamps and outcome. Original GETP,
|
||||
access parameters, password and raw replies never reach the browser. The
|
||||
footer saves desired settings and starts a bounded remote operation; the
|
||||
separate Read through VPS action reconciles an uncertain endpoint without
|
||||
writing. A profile save never initiates a fleet rollout.
|
||||
|
||||
Packets are checksum-validated before command processing. Evidence rejects
|
||||
stale timestamps, duplicates and responses from another session. Real B2 text
|
||||
clock lag was about four seconds; the accepted window is at most ten seconds
|
||||
behind and five seconds ahead of host time. Successive stages require strictly
|
||||
increasing device timestamps. FC supplies **no transaction token**: this bounds
|
||||
freshness, but cannot provide cryptographic correlation of a response to a
|
||||
command. Do not describe a TCP ACK or any arbitrary text as verified settings.
|
||||
|
||||
Desired endpoint changes retain admission on observed/confirmed prior endpoints
|
||||
of already assigned hosts. This prevents saving a new address from revoking the
|
||||
old uplink before device confirmation. The secondary channel is not retired
|
||||
automatically. Replacing a host or losing Core connectivity cannot cause a write
|
||||
replay. On reconnect Core polls the persisted operation; unresolved outcomes stay
|
||||
uncertain. Queue expiry is not an indefinite offline rollout.
|
||||
|
||||
## Physical qualification
|
||||
|
||||
- 0.1.4 rejected a fresh preflight due to clock skew; no write occurred.
|
||||
- 0.1.5 sent the documented change, independently visible over USB, but correctly
|
||||
withheld success when B2's response arrived after TCP reconnection.
|
||||
- 0.1.6 verified the network reversal through the surviving secondary, including
|
||||
a fresh GETP after reconnection. USB backup and restored configuration hashes
|
||||
were equal; no other configuration bytes changed.
|
||||
- Synthetic checks cover stale/wrong-session/duplicate replies, missing ACK,
|
||||
reconnect, restart, expiry, altered unrelated fields, expected-value conflict,
|
||||
mixed unsupported profiles, private-field projection and desired/admission
|
||||
separation. This is not a thousand-device load qualification.
|
||||
|
||||
Full USB CONF is larger than the FC frame. Do not split it into guessed chunks,
|
||||
map binary field IDs directly into SETP, or invent FD file/apply semantics.
|
||||
The B2 manual says accepted changes synchronize to its vendor web configurator;
|
||||
existing vendor polling remains enabled. Full vendor-cloud independence,
|
||||
factory-empty devices and network delivery of every settings field remain open.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Идентичность двух SIM через собственный VPS
|
||||
|
||||
Дата: 2026-09-28. Область: наблюдение идентичности, без записи APN или команд
|
||||
переключения SIM. Направление связи прежнее: B2 → VPS, Core опрашивает VPS.
|
||||
|
||||
## Установлено на B2 231 / 0.01
|
||||
|
||||
В трёх сохранённых стартовых сетевых пакетах присутствуют две пары тегов:
|
||||
|
||||
| Слот | Теги INTERNAL | Представление |
|
||||
| --- | --- | --- |
|
||||
| SIM 1 | 253, 254 | `89` + две девятизначные десятичные части |
|
||||
| SIM 2 | 202, 203 | То же |
|
||||
|
||||
Части — четыре байта little-endian каждая, строго меньше 1 000 000 000.
|
||||
Правило опубликовано в [спецификации INTERNAL, TAGS](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit).
|
||||
Обе части берутся из **одного** пакета с проверенными длиной и контрольной
|
||||
суммой. Пропущенные части не достраиваются из другого пакета.
|
||||
|
||||
Полные 20 цифр обоих слотов совпали с SID в пассивном USB-потоке запуска.
|
||||
Это подтверждено на расстановках МегаФон 1 / МТС 2 и МТС 1 / МегаФон 2.
|
||||
У МТС SID также совпадает с сырым CCID модема. У испытанной МегаФон сырой
|
||||
ответ CCID заканчивается на `ff` и отличается от SID. Поэтому название поля
|
||||
в общей спецификации не превращает его в канонический ICCID на этой прошивке.
|
||||
|
||||
Полные сетевые SID поступают в стартовых пакетах; обычные пакеты координат
|
||||
не обязаны их содержать. В исследованном журнале это три пары двух SIM
|
||||
и отдельные более ранние отчёты SIM 2. Чтение по требованию через сеть
|
||||
полного IMSI либо гарантированный повтор этих тегов ещё не квалифицированы.
|
||||
|
||||
Один ограниченный USB-запрос `I 0`, найденный в официальном конфигураторе,
|
||||
вернул те же длины SID 12/20, что `I 7`. Он не вызвал полный обмен CCID/CIMI.
|
||||
Запрос был обрамлён чтениями идентичности; записи настроек не выполнялись.
|
||||
Не отправляли `SERV1.2`: общий лист SMS_COM и
|
||||
[руководство B2](https://8888.arusnavi.ru/Arnavi%20B2/) описывают разные
|
||||
семантики, а руководство B2 связывает его с отправкой SMS.
|
||||
|
||||
## Реализация
|
||||
|
||||
`sim_network.py` отделяет приватные идентификаторы от публичной сотовой
|
||||
телеметрии. Core сохраняет проекцию `b2_sim_identity` в той же транзакции
|
||||
SQLite, что исходный пакет и курсор его получения. Сырые пакеты остаются
|
||||
первичным журналом. Сбой пакета в середине пачки откатывает также проекцию.
|
||||
|
||||
Проекция изолирована по экземпляру трекера и VPS. Перенос аппарата за пределы
|
||||
обслуживаемых VPS аппаратов или замена VPS не выдаёт данные прежнего хоста.
|
||||
Сохраняются время измерения B2, время получения VPS и номер записи журнала.
|
||||
Пакеты, пришедшие позже, не заменяют более новое измерение. Противоречивые
|
||||
значения с одинаковым временем остаются неопределёнными до нового измерения.
|
||||
|
||||
Отсутствие/появление SIM и начало поиска сети инвалидируют предыдущее
|
||||
наблюдение слота. Нулевые части, неполные пары, противоречивые повторения
|
||||
и один SID в обоих слотах не подтверждают идентичность. Нулевые части сами
|
||||
по себе не означают отсутствие SIM. История не стирается из исходного журнала.
|
||||
|
||||
API `/api/v1/fleet/vps-hosts/telemetry` возвращает отдельное `sim_identity`:
|
||||
источник, времена, свежесть и ссылку на известную карту, если найдено точное
|
||||
однозначное совпадение SID с ранее квалифицированным USB-обменом CCID/IMSI.
|
||||
Поиск ограничен тем же трекером и не зависит от прежнего слота. Короткое `I 7`,
|
||||
настроенный APN или код обслуживающей сети не участвуют в сопоставлении.
|
||||
Несколько разных CCID/IMSI с тем же SID дают неопределённость.
|
||||
|
||||
Публичная ссылка случайная; SID, CCID, IMSI и IMEI не добавляются в ответ.
|
||||
Домашняя сеть в ссылке происходит из сохранённого модемного обмена, а не из
|
||||
угадывания оператора по цифрам SID. Это не доказательство тарифа или MVNO.
|
||||
Историческое совпадение не означает, что карта остаётся в слоте сейчас.
|
||||
`observation_fresh` требует возраста измерения менее 90 секунд, такой же
|
||||
границы между измерением и приёмом и отсутствия последующей инвалидации.
|
||||
Повторное открытие базы или получение буферизованного пакета не освежает время.
|
||||
`automatic_write_authorized` всегда `false`: этот этап не запускает подбор APN.
|
||||
|
||||
Старый журнал не импортируется в текущую проекцию с новым временем. После
|
||||
обновления Core проекция наполняется следующими реальными пакетами B2.
|
||||
|
||||
## Проверено
|
||||
|
||||
- Пары тегов, границы значений, длина и контрольная сумма пакетов.
|
||||
- Раздельные части в разных пакетах, нули, конфликты, дубли в двух слотах.
|
||||
- Перестановка известных карт, неизвестный SID, коллизия алиаса и приватность.
|
||||
- Запоздавшие пакеты, будущие метки времени, извлечение/возврат карты,
|
||||
перезапуск хранилища, смена VPS и атомарный откат пачки.
|
||||
- Новый код обработал три физических стартовых пакета: обе расстановки
|
||||
сопоставлены с исходными USB-парами; исходные времена не изменены.
|
||||
- Регрессии существующего приёма пакетов, ACK, сотовой телеметрии,
|
||||
выходов и сетевых операций настроек прошли. Loopback-тест отдельно повторён
|
||||
вне sandbox, запрещавшего локальный bind; он прошёл.
|
||||
|
||||
Приватная сессия: `outputs/arnavi-b2/sim-on-demand-c865521669014936a08be61eefebc847/`.
|
||||
Свежие проверки без USB выполнены после двух действий владельца:
|
||||
|
||||
| Питание / расстановка | Получение VPS (UTC) | Результат |
|
||||
| --- | --- | --- |
|
||||
| Только 12 В; МТС 1, МегаФон 2 | 09:16:07.149 | Оба SID сопоставлены с прежними картами, без USB-чтения |
|
||||
| Только 12 В; МегаФон 1, МТС 2 | 09:19:54.674 | Ссылки тех же карт поменялись слотами, без ручного назначения оператора |
|
||||
|
||||
Владелец подтвердил отключённый USB в обоих опытах. Во втором опыте новая
|
||||
телеметрия показывает активную SIM 1; позже получены также обслуживающие
|
||||
сети 250-02 и 250-01. Настройки APN в этих опытах не менялись.
|
||||
Исходные пакеты, временные метки и подтверждения владельца сохранены в
|
||||
`network-live-a60ece87eb4841bc8ff44b5b0415a55e/` и
|
||||
`network-swap-*` внутри указанной приватной сессии.
|
||||
|
||||
Контрольные команды шли штатно через Core → VPS → B2:
|
||||
|
||||
- До перестановки запрос координат подтверждён с первой попытки, код 0,
|
||||
0,564 с от отправки VPS до ответа B2.
|
||||
- После перестановки первые две попытки не получили подтверждения. Один
|
||||
долговечный запрос остался в рантайме и завершился на третьей попытке:
|
||||
**100,414 с от создания запроса до ответа**, из них 0,467 с — третья
|
||||
отправка/ответ. Не объявляем весь запрос выполненным за 0,467 с.
|
||||
- Три попытки использовали разные TCP-сеансы. Подтверждение третьей пришло
|
||||
через другой активный сеанс; сопоставление токена нашло правильный запрос.
|
||||
Отсутствие ответа на первые попытки не доказывает, что B2 их не исполнил.
|
||||
Точная причина задержки по этому журналу не установлена.
|
||||
|
||||
После завершения команды перезапущен канонический Core. Проекция SIM,
|
||||
ссылки карт и исходные времена сохранились без изменений; прежнее наблюдение
|
||||
не стало свежим. Core оставлен работающим на 8000, B2 продолжает передавать
|
||||
данные через VPS. Временные наблюдатели завершены.
|
||||
|
||||
Это приёмка сетевого распознавания **этих двух уже известных карт** и
|
||||
сохранения запроса при неподтверждённых попытках. Это не гарантия задержки,
|
||||
не испытание произвольных новых SIM и не готовый автоподбор APN.
|
||||
|
||||
## Следующий этап
|
||||
|
||||
Применение APN остаётся отдельной задачей: редакции справочника, связь
|
||||
намерения с картой, восстановление после разрыва и проверка результата.
|
||||
Для совершенно новой неизвестной SIM одного SID может быть недостаточно
|
||||
для выбора тарифа. Если после замены SIM B2 вообще не выходит на VPS,
|
||||
сетевое наблюдение также недоступно; нужен квалифицированный независимый
|
||||
канал настройки либо подтверждённая нативная функция прошивки.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Outbound readiness and physical recovery — 2026-09-27
|
||||
|
||||
This report describes the 0.1.27 increment. Later opcode-7 qualification,
|
||||
Host 0.1.29 and the remaining post-write failure are recorded in
|
||||
[the clock/freshness follow-up](CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md).
|
||||
|
||||
## Result
|
||||
|
||||
Host 0.1.27 is installed through the reproducible installer and available from
|
||||
Mission Core. Its bounded synthetic transport/runtime checks passed. It prevents
|
||||
new commands from being placed behind an already unacknowledged stream prefix.
|
||||
The physical settings restoration still failed. USB restored and independently
|
||||
verified the exact original image; remote configuration reliability remains open.
|
||||
|
||||
## Why the change is needed
|
||||
|
||||
The newest incoming telemetry connection can still have stalled outgoing data.
|
||||
Previously, selecting solely by recent input allowed that connection to take a
|
||||
command while another stream had drained. Host 0.1.27 requires no queued asyncio
|
||||
bytes and, on the qualified Linux host, zero TIOCOUTQ bytes before dispatch.
|
||||
New production sessions begin ineligible until their transport is checked.
|
||||
Selection then uses the most recently active eligible stream.
|
||||
|
||||
This is admission, not an execution acknowledgment. A connection can fail after
|
||||
the check. Original operation deadlines, durable dispatch, cancellation limits
|
||||
and prohibition on automatic write/actuation replay remain unchanged. Idle
|
||||
senders stay event driven; already-pending operations use the existing bounded
|
||||
poll. Non-Linux engineering runs retain the conservative expiry watchdog and do
|
||||
not qualify this kernel check.
|
||||
|
||||
## Physical observations
|
||||
|
||||
One owner-controlled model 231 / firmware 0.01; indoors, 12 V. The operator
|
||||
confirmed all indicators extinguished, ten seconds unpowered, then 12 V only.
|
||||
That duration is operator-reported, not measured by the VPS.
|
||||
|
||||
| Operation | Evidence | Outcome |
|
||||
| --- | --- | --- |
|
||||
| Read after physical cycle on 0.1.26 | Fresh full image in 15.039 s | Field 25 still 16; 207 records / 983 bytes |
|
||||
| First restoration | 180.824 s, preflight | No image served |
|
||||
| Second restoration after new connection | 180.889 s, write request | No image served |
|
||||
| Restoration on 0.1.27 | Fresh predecessor received; request-write stage expired at 180.864 s | No image served; not restored |
|
||||
| USB restoration | Identity checked around a fresh read and one CONF write | Only field 25 restored, 16 → 15 |
|
||||
| Independent USB read | All 207 records match baseline | Restoration confirmed at 14:03:28 UTC |
|
||||
| Core USB inspection | Same exact image, existing desired policy retained | Product cache reconciled; failed network history preserved |
|
||||
| One UI position request via 0.1.27 | Matching B2 command token | Confirmed 3.662211 s after dispatch; VPS queue 0.003103 s |
|
||||
|
||||
The position sample used Core → VPS → cellular B2. USB was connected after
|
||||
recovery, with no serial operation during the command; it is not a USB-unplugged
|
||||
qualification and is not a GNSS-fix or physical-output latency guarantee.
|
||||
|
||||
In the 0.1.27 capture, TCP acknowledged the SERV 1.8 request after 0.723 s, yet
|
||||
the B2 did not request the target settings image. The preceding upload was
|
||||
followed by three empty HTTP opcode-7 requests. The current strict decoder rejects
|
||||
opcode 7; its meaning and response are unqualified. This is a concrete protocol
|
||||
coverage gap and a candidate for the next investigation, **not proof of the
|
||||
cause**. No guessed reply was sent. The captured opcode-5 image itself remains
|
||||
valid read evidence; it does not prove the whole configuration dialogue ended.
|
||||
|
||||
The manufacturer's [B2 manual](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf),
|
||||
sections 9–10, describes configuration methods and control commands. It must
|
||||
not be used to invent a response to an undocumented HTTP opcode. No device
|
||||
reference request to a manufacturer service occurred in this increment.
|
||||
|
||||
## Release and validation
|
||||
|
||||
- VPS installer SHA-256:
|
||||
`d1e95c56302136cd66a725572f015fc577dddf1a18b8856992cbcd748652a9c7`.
|
||||
- Two builds produced identical installer, tar and manifest hashes. All 22
|
||||
installed manifest files match the artifact. Existing identity files and
|
||||
journal were backed up; all four identity-file hashes were preserved.
|
||||
- Bounded artifact-owned Linux delivery, runtime and six fault/crash scenarios
|
||||
passed in isolated temporary state. A blocked stream expired near its 0.75 s
|
||||
test deadline; the independent healthy stream delivered its 12-byte frame.
|
||||
These are synthetic checks, not cellular performance results.
|
||||
- 178 focused backend tests passed, followed by the two-version compatibility
|
||||
case for 0.1.26/0.1.27. Ruff passed. Thirteen focused frontend tests and four
|
||||
architecture checks passed; typecheck and production build passed.
|
||||
- Core/API/bootstrap and frontend admit qualified version 0.1.27. The settings
|
||||
timeout message now distinguishes initial-read failure from an unconfirmed
|
||||
write-stage completion. No product layout or shared control changed.
|
||||
- Browser QA used the rebuilt canonical service, enabled settings controls and
|
||||
a real UI position request. Core remains on 8000 with no listener on 8765.
|
||||
The downloaded installer hash matches the installed qualified release.
|
||||
|
||||
The final original image SHA-256 is
|
||||
`7e7798a5e2c1909454dfab500dac4cc2d0917555a02f2afac711b167c9ae1ee8`.
|
||||
No firmware, relay actuation or onboard Node update occurred. Temporary captures
|
||||
completed. The private journal has no pending command or outbox item.
|
||||
|
||||
## Next acceptance gate
|
||||
|
||||
Resolve the configuration dialogue's opcode-7 behavior using authoritative
|
||||
protocol evidence, then qualify repeated network write/readback/reconnect cycles
|
||||
from the restored baseline. Separately remove persisted one-shot SIM activation
|
||||
intent from unrelated profile edits. Do not mask either issue with blind retries,
|
||||
longer indefinite spinners, success inferred from telemetry, or automatic USB
|
||||
fallback. Factory-fresh bootstrap and unimplemented configuration sections retain
|
||||
their separate gates in the coverage audit.
|
||||
|
||||
Private sessions: `power-cycle-0f472bc4c1d04d7c8616a66326942b2b` and
|
||||
`readiness-1521085259cb48938c2f563bad5e44e2`, beneath the configuration audit.
|
||||
Raw traffic, identities, SIM data and settings stay in ignored owner storage.
|
||||
Redacted manifests retain timestamps, source hashes, receipts and test artifacts.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Atomic B2 packet acceptance — VPS Host 0.1.36
|
||||
|
||||
Scope: communication and command-result durability on the owner's existing
|
||||
Core → VPS → B2 path. Further clean-Ubuntu installation qualification is deferred
|
||||
at the owner's request. No tracker setting, SIM selection, USB, output or firmware
|
||||
change belongs to this increment.
|
||||
|
||||
## Defect and change
|
||||
|
||||
The receiver committed a raw packet, then processed its command receipt and
|
||||
modem observation in separate database transactions. Core could fetch and
|
||||
acknowledge that packet between those steps. A receiver failure in that window
|
||||
could leave the durable operation without a receipt that had already reached
|
||||
the receiver, leading to an unnecessary retry after recovery.
|
||||
|
||||
The receiver now commits the raw packet, command evidence and modem observation
|
||||
in one SQLite FULL transaction. The same synchronous worker owns the connection
|
||||
for all three consumers. Neither Core nor the command sender can observe a
|
||||
partial result. Only after commit does the receiver wake the sender and write
|
||||
the B2 packet ACK. Storage/processing failure rolls the transaction back, closes
|
||||
the connection and sends no packet ACK. Connection sharing is thread-local and
|
||||
ends on every exit path; no socket I/O or wait belongs to that transaction.
|
||||
|
||||
This closes a local persistence gap. It does not establish exactly-once physical
|
||||
execution, recover a reply never received by the VPS, or guarantee radio reachability.
|
||||
|
||||
## Validation
|
||||
|
||||
The regression reproduced both failure boundaries on the preceding receiver:
|
||||
before command receipt processing and after it, the raw packet remained visible.
|
||||
Both cases pass with the new transaction. Additional cases cover successful ACK
|
||||
ordering, SQLite rollback including modem state, connection cleanup, concurrent
|
||||
read isolation, and abrupt process exit before/after commit. A committed command
|
||||
result survives process recovery and packet removal without a second attempt.
|
||||
The existing receiver, durable-operation, receipt, Core outbox/reconciliation,
|
||||
network-configuration and bootstrap checks also passed. Ruff passed.
|
||||
|
||||
Frontend compatibility was extended to 0.1.36; architecture checks, typecheck,
|
||||
all 1011 frontend tests and the production build passed. Existing bundle-size
|
||||
warnings remain. Settings stay enabled on this host version; the actual command
|
||||
history and per-attempt receipt were checked in the canonical UI.
|
||||
|
||||
Actual owner B2, indoor cellular path:
|
||||
|
||||
- Pre-change position request: code 0, one attempt, **2.626855 s** after dispatch.
|
||||
- Post-change full configuration read: one attempt; exact baseline SHA-256,
|
||||
207 records / 983 bytes, stationary interval still 15 seconds.
|
||||
- Post-change position request: code 0, one attempt, **1.159116 s** after dispatch.
|
||||
VPS and Core outcomes agree; the UI shows the matching receipt and one attempt.
|
||||
|
||||
These two position samples are working-exchange evidence, not a throughput or
|
||||
latency improvement claim. The radio outage and remote SIM fallback limitations
|
||||
remain separate from this persistence correction.
|
||||
|
||||
The versioned installer updated the existing receiver from 0.1.35 to 0.1.36,
|
||||
preserved four identity files and the journal, and all 28 installed manifest
|
||||
files matched. The same installer is available through Core.
|
||||
Installer SHA-256:
|
||||
`e55bb2d85e6b6882710d343aca09d95f2e36b6430711a16fa817acf4cc793e62`.
|
||||
|
||||
Private evidence session:
|
||||
`communication-runtime-05425c85f4004be6908506bfb4406a2e`.
|
||||
Raw configurations, identifiers, database backups and tokens stay outside Git.
|
||||
@@ -0,0 +1,168 @@
|
||||
# Independent equipment and portable B2 profiles
|
||||
|
||||
Owner-approved surface: Fleet → apparatus → Equipment root plus. The task is
|
||||
initial admission, repeat admission with a saved profile, and reassignment of
|
||||
an independently connected tracker. An onboard-device submenu is rejected:
|
||||
USB bootstrap runs on the operator host and the tracker works without Node.
|
||||
No new primary navigation or shared visual primitive is introduced.
|
||||
|
||||
The root chooser preserves the existing computer-invitation branch and adds
|
||||
ARNavi B2. USB inspection supplies real identity and a private CRC-checked
|
||||
configuration snapshot. Registering creates a durable independent instance;
|
||||
several instances may reference one existing apparatus. IMEI, not tty name or
|
||||
SIM, is the deduplication key. Reassignment retains instance identity, original
|
||||
snapshot, and revision history. Computer connectivity never gates this flow.
|
||||
|
||||
A profile is an immutable named snapshot, not a device clone or live reference.
|
||||
Editing a tracker does not mutate a profile or fan out changes to other devices.
|
||||
Saving another profile creates another identity, even with the same name.
|
||||
Instances retain the applied selection and their own editable desired policy.
|
||||
|
||||
Profile v1 carries an optional DNS/IP endpoint + port + slot (INTERNAL), APN
|
||||
strategy, and an explicit allowlist of trajectory, roaming, motion, GNSS and
|
||||
driving thresholds. Missing = preserve; zero is explicit. Unique identity,
|
||||
SIM identifiers, phone numbers, detected carrier, per-server ID, passwords,
|
||||
Bluetooth codes/MACs, sensor addresses, API tokens and vehicle assignment are
|
||||
excluded server-side. Existing firmware fields and unknown bits are preserved.
|
||||
Profile overlay fails if a requested field is absent or has incompatible width.
|
||||
This is deliberately not a universal export of all 207 firmware settings.
|
||||
|
||||
Connectivity is a separate profile component: preserve device access, explicitly
|
||||
supply APNs, or select a versioned public carrier preset and SIM slot. MTS and
|
||||
MegaFon presets write APN plus their documented public access login/password
|
||||
together for that slot. They are not a copy of subscriber credentials. No carrier is guessed from an incomplete ICCID, no default APN is
|
||||
blindly written, and no "automatic" mode is advertised without a qualified
|
||||
resolver. An M2M/private APN may depend on a contract rather than the visible
|
||||
network name. Authentication secrets must later be device-scoped credentials,
|
||||
never plaintext shared-profile fields. Known working connectivity is preserved
|
||||
by default. Factory-empty devices require an explicit verified connectivity
|
||||
configuration; signal bars alone do not prove Internet access.
|
||||
|
||||
State grammar: loading, empty catalog, USB read pending, read failure,
|
||||
verified USB candidate (expires in ten minutes), registered with saved desired
|
||||
policy, conflict on stale revision. Saving policy/profile does not write USB,
|
||||
connect a gateway, or claim operational telemetry. A separate local USB apply operation writes a saved policy with backup and
|
||||
readback, currently qualified on model 231 / firmware 0.01. VPS packet acceptance
|
||||
remains separate and unqualified here.
|
||||
The source and target profile never grant actuation, firmware or reboot rights.
|
||||
|
||||
Product UI uses canonical Window, FeatureSettingsWindow, fields, Select,
|
||||
ResourceRow and StatusBadge. Settings footer owns Save settings and Save profile. The operator
|
||||
can review actual USB observation separately from desired settings and move
|
||||
the device to any existing apparatus. Runtime/API acceptance evidence is
|
||||
recorded after validation; real snapshots and IDs stay outside Git.
|
||||
|
||||
## Acceptance — 2026-09-26
|
||||
|
||||
- Canonical Core 8000: real USB inspection through the enrollment UI, independent
|
||||
registration under an existing offline-Node apparatus, and named profile save
|
||||
succeeded. Device and profile survive browser reload and service restart.
|
||||
- Firmware 0.01 returned 78 of the 86 allowlisted scalar policy fields. Separate
|
||||
parameters 241–248 were absent; they are not synthesized from the web schema.
|
||||
The settings editor offers only fields qualified in the device snapshot.
|
||||
- UI checks: normal/expanded Fleet, root equipment chooser, disabled Add before
|
||||
USB inspection, real identity auto-fill, settings header profile modal,
|
||||
resulting profile available for another enrollment, missing-endpoint save
|
||||
disabled, and Escape without persistence. Existing onboard peripherals retain
|
||||
their independent offline state.
|
||||
- Automated: 48 focused backend tests including existing Fleet replacement and
|
||||
board-layout regressions; 987 frontend tests, architecture checks, TypeScript,
|
||||
production build; Ruff and strict scoped mypy for the eight new backend files.
|
||||
- USB configuration SHA-256 matches the initial read; no configuration-write
|
||||
command was transmitted. Private evidence is outside normal Git. This is
|
||||
enrollment/profile acceptance, not clean-device provisioning, cloud removal
|
||||
or receipt of telemetry on the owner's VPS.
|
||||
|
||||
Follow-on qualification: exact vendor USB write envelope and acknowledgment,
|
||||
backup/readback/rollback, per-firmware configuration coverage, separate Mission
|
||||
Core gateway readiness and packet acceptance, credential references and carrier
|
||||
resolver. Factory-empty physical hardware and cross-carrier replacement remain
|
||||
separate acceptance cases; preserving an empty APN is not an Internet setup.
|
||||
|
||||
|
||||
## Carrier replacement and USB apply — 2026-09-26
|
||||
|
||||
The owner supplied two SIM phone numbers and authorized using them in the names
|
||||
of immutable local profiles. The labels are stored in the private equipment
|
||||
registry; numbers are not serialized to the tracker or inferred from ICCID.
|
||||
A profile name is descriptive history, not a live association with a SIM.
|
||||
|
||||
A newly inserted MTS card was observed in the firmware's second SIM identity
|
||||
field. Its exact reported identifier was preserved privately. The selected
|
||||
standard MTS preset targeted SIM 2; the previous SIM 1 settings and server route
|
||||
were preserved. Generic automatic carrier/APN selection is not claimed.
|
||||
|
||||
The settings window exposes Save profile in its footer, separate Save settings
|
||||
and Apply via USB operations, actual APNs for both slots, observed USB timestamp,
|
||||
and an honest distinction between applied configuration and server telemetry.
|
||||
A dirty form cannot apply directly; stale revision, identity and configuration
|
||||
checks prevent a write against another snapshot.
|
||||
|
||||
Focused transport tests and the actual device confirmed complete nonblocking
|
||||
transmission, `SR=1`, exact changed fields, readback and bounded rollback.
|
||||
The physical MTS write passed independent post-operation inspection. The full
|
||||
frontend suite passed 988 tests, plus architecture checks, typecheck and build.
|
||||
This extends the earlier enrollment-only acceptance; the earlier no-write status
|
||||
above describes that earlier experiment, not the current hardware state.
|
||||
|
||||
Public carrier references:
|
||||
[MTS access settings](https://support.mts.ru/mts_mobilnyy_internet/nastroiki-mobilnogo-interneta/kak-nastroit-internet-na-telefone),
|
||||
[MegaFon official access-settings post](https://t.me/s/megafon_online?after=1143).
|
||||
Corporate/private APNs still require the actual contract settings.
|
||||
|
||||
## Remote endpoint application — 2026-09-26
|
||||
|
||||
With VPS Host 0.1.6, Save settings preserves the desired profile and attempts a
|
||||
bounded network operation. Only primary monitoring host/port changes are admitted;
|
||||
mixed unsupported changes are rejected without partial device writes. Separate
|
||||
Read through VPS reconciles the observed primary endpoint. USB apply is grouped
|
||||
with initial setup/recovery, not presented as the routine remote control path.
|
||||
The existing profile collection remains immutable and no fleet-wide propagation
|
||||
is implied. Pending operations prevent conflicting edits and assignment changes.
|
||||
|
||||
Product acceptance selected the owner's registered VPS in server slot 1 and
|
||||
clicked Save settings: the device's independent readback reached verified,
|
||||
visible in the open window without a reload; fresh GNSS continued. This confirms
|
||||
endpoint control, not all parameters in the portable profile.
|
||||
|
||||
## Target-SIM editor simplification — 2026-09-27
|
||||
|
||||
Owner requested one target selector with automatically updated operator names,
|
||||
not separate mode/carrier/slot controls. The admitted connection section now
|
||||
uses one Select (`Целевая SIM`) and one APN TextField. Selecting a card navigates
|
||||
its APN; it does not switch the modem or write anything. Existing operator and
|
||||
manual policies remain readable for compatibility, but the editor no longer
|
||||
asks the operator to select a carrier preset. Editing a field creates a `sim`
|
||||
policy with an explicit slot/APN and preserves the other slot and both sets of
|
||||
credentials. Existing preset intent is displayed as its desired APN, separately
|
||||
from the last APN actually read from B2.
|
||||
|
||||
The options come only from fresh, online DS2 presence/status evidence. No-SIM,
|
||||
unknown/reserved status or unavailable/stale telemetry do not fabricate an
|
||||
installed slot. Labels use fresh serving-network MCC/MNC, never the configured
|
||||
APN, old USB identity, phone number or saved preset. Labels and available slots
|
||||
recompute when new telemetry arrives. During network search, after removal,
|
||||
or with unknown codes, the operator remains explicitly unknown. The Core
|
||||
journal invalidates the previous network after a reported removal, reinsertion
|
||||
or a transition to searching, and prevents delayed older packets from restoring
|
||||
that discarded name. A swap that B2 does not report cannot be detected by Core.
|
||||
|
||||
The current test device still reports `250-00` for SIM 2; the recent sample has
|
||||
no live ICCID tag pairs, so this increment cannot establish MTS identity from
|
||||
its telemetry. It must not claim universal carrier detection, APN auto-provisioning,
|
||||
modem-SIM switching, or successful remote writes. Future operator sources can
|
||||
extend the resolver without restoring manual carrier selection.
|
||||
|
||||
No new workspace, navigation or visual primitive: novelty A, existing
|
||||
FeatureSettingsWindow/SettingsCard/Select/TextField. Keeping separate mode and
|
||||
carrier controls was rejected as duplication of the device observations. Tests
|
||||
cover one/two/removed/swapped/new-operator SIMs, missing/stale/searching evidence,
|
||||
old-packet rejection after reinsertion, isolated APN writes and server-side
|
||||
presence checks before network submission. Physical SIM swaps were not performed
|
||||
for this UI increment.
|
||||
|
||||
Selecting a different SIM clears a previous single-slot APN intent from the
|
||||
local draft, preserving endpoint and other parameters. It does not silently
|
||||
move that APN to another card or leave an invisible write targeting the old
|
||||
slot. Editing the visible APN establishes the new explicit target. Returning
|
||||
to the same selected slot preserves its draft. No selection is sent to B2.
|
||||
@@ -0,0 +1,32 @@
|
||||
# ARNavi: текущая реализация и доказательства
|
||||
|
||||
Начинать передачу контекста с двух текущих руководств (28.09.2026):
|
||||
|
||||
- [VPS сервер](../handoff/ARNAVI_VPS_SERVER_20260928.md): сборка/установка,
|
||||
pairing, admission, API, долговечный runtime, transport evidence, backup/migration.
|
||||
- [B2 трекер](../handoff/ARNAVI_B2_TRACKER_20260928.md): USB, профили, настройки,
|
||||
команды, multi-SIM, identity, native/automatic интернет, firmware и ограничения.
|
||||
|
||||
Датированные документы ниже — журнал исследования, а не совокупность одновременно
|
||||
действующих требований. Старые слова «не реализовано» относятся к указанной
|
||||
версии; старое «проверено» не переносится на другую прошивку или окружение.
|
||||
|
||||
| Тема | Основные материалы |
|
||||
| --- | --- |
|
||||
| USB и профили | `USB_BOOTSTRAP.md`, `PROFILES_AND_EQUIPMENT.md` |
|
||||
| Собственный config endpoint | `AUTONOMY_AND_COMMANDS.md`, `CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md` |
|
||||
| Покрытие настроек | `CONFIGURATION_COVERAGE_20260927.md` |
|
||||
| Очередь и recovery | `DURABLE_MAINTENANCE_20260927.md`, `RUNTIME_RECOVERY_20260927.md`, `FAULT_RECOVERY_20260927.md` |
|
||||
| Атомарный приём / ответы | `PACKET_COMMIT_20260927.md`, `TRACKER_CONFIRMATIONS_20260927.md` |
|
||||
| TCP и слабый канал | `TRANSPORT_EVIDENCE_20260928.md`, `COMMUNICATION_LIMITS.md` |
|
||||
| Identity SIM | `SIM_OBSERVATION_RUNTIME_20260928.md`, `NETWORK_SIM_IDENTITY_20260928.md`, `HOT_SIM_IDENTITY_AND_QUEUE_20260928.md` |
|
||||
| Привязанный к карте доступ | `CARD_ACCESS_APPLICATION_20260928.md` |
|
||||
| Горячая замена / пустой APN | `NATIVE_SIM_EXPERIMENT_20260928.md`, `MTS_SLOT1_EMPTY_APN_20260928.md` |
|
||||
| Текущий native UI | `NATIVE_INTERNET_POLICY_20260928.md` |
|
||||
| Предпочтение и резерв | `SIM_PREFERENCE_AND_FALLBACK_20260928.md` |
|
||||
| Firmware archive / отсутствие backup0.01 | `FIRMWARE_SETTINGS_20260928.md`, `FIRMWARE_BASELINE_20260928.md` |
|
||||
| Помещение и улица | `INDOOR_OUTDOOR_COMPARISON_20260927.md` |
|
||||
|
||||
Raw config, SID/IMSI, PCAP, журналы устройства, recovery archives и firmware
|
||||
бинарники находятся в private operator state/ignored evidence, не в исходниках.
|
||||
Synthetic fixtures в тестах не идентифицируют стендовое устройство.
|
||||
@@ -0,0 +1,134 @@
|
||||
# Command durability and automatic recovery
|
||||
|
||||
This increment addresses the owner's requirement that restarting Core, the VPS
|
||||
or the tracker must not silently erase accepted work. It does not establish
|
||||
unconditional delivery through an unavailable modem or reliable USB-only power.
|
||||
|
||||
## Contract
|
||||
|
||||
Core persists an accepted intent before returning its ID. Its bounded per-device
|
||||
FIFO, outgoing request body and original deadline survive a Core restart. The
|
||||
VPS commits acceptance and dispatch state to SQLite with `synchronous=FULL`.
|
||||
An idempotent repeat of the same ID cannot create a second operation; changed
|
||||
contents under the same ID are rejected. Losing an HTTP response is different
|
||||
from losing the underlying accepted operation.
|
||||
|
||||
| Interruption point | Recovery behavior |
|
||||
| --- | --- |
|
||||
| Accepted in Core, not submitted | Continue the persisted FIFO within its original deadline and device/host guards |
|
||||
| VPS acceptance response lost | Query/retry the same ID and unchanged request; do not invent a new operation |
|
||||
| Undispatched position read on VPS | Wait for a new admitted session until original expiry, including VPS restart |
|
||||
| Effectful command dispatched, no conclusive reply | Retain an unknown outcome; no automatic action replay |
|
||||
| Full settings image committed for transmission; verification interrupted | In 0.1.30, continue independent readback after VPS restart or a new B2 connection |
|
||||
| Original deadline elapsed | Keep the terminal record; do not turn an old relay/restart request into a delayed action |
|
||||
| Result received on VPS while Core was unavailable | Reconcile the durable result by operation ID; no new physical command |
|
||||
|
||||
The distinction between queued and dispatched is durable before writing to the
|
||||
socket. A crash in that narrow interval can leave an unknown outcome even if no
|
||||
bytes reached the tracker. Without device-side durable deduplication, neither
|
||||
TCP ACK nor our database can establish exactly-once physical actuation. A lost
|
||||
reply after an effect must not be interpreted as failure-to-execute.
|
||||
|
||||
## 0.1.30: resumable verification
|
||||
|
||||
The new behavior is narrowly admitted for `configure-all`, stage `verify`, with
|
||||
a previously committed `write_reply_sent_at`. Both queued and already dispatched
|
||||
readback survive a VPS process restart. A newer B2 monitoring connection can
|
||||
take over a dispatched readback while an old TCP stream remains half-open.
|
||||
|
||||
The same operation retains its target, predecessor, absolute deadline and stage
|
||||
pacing. Fresh device input and a drained TCP sender are still required. The only
|
||||
reissued command is `SERV*1.9`, an upload/read of actual configuration. `SERV*1.8`
|
||||
and the settings image are not reissued. Exact target -> verified; exact old
|
||||
image -> not applied; any other image -> uncertain. Another unavailable read
|
||||
still expires uncertain; restart does not extend the bound. Recovery timestamp
|
||||
and count are persisted and projected into Core history.
|
||||
|
||||
SIM selection and restart/output actions deliberately retain their prior
|
||||
no-replay behavior. Automatic verification here never advances a SIM workflow
|
||||
into another modem restart. Already terminal historical operations are not
|
||||
reopened. There is no automatic post-expiry configuration reconciliation in this
|
||||
increment; continued inspection must remain distinct from the expired command.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Private session: `restart-recovery-d51782434e5449abac423f0f4b0196c4`.
|
||||
Accepted candidate: `candidate-ee690dcabdbc481eb1d538dedb950b5d`.
|
||||
Installer SHA-256:
|
||||
`5042dfcb3ace38c66133779d9561a66ed2066df9ca830223966af80b6938985f`.
|
||||
|
||||
The shipped `qualify_recovery.py` ran on the Ubuntu VPS with temporary SQLite,
|
||||
isolated loopback streams and a synthetic B2. Two `SIGKILL` interruptions and one
|
||||
tracker-side reconnect produced one image write, three independent readback
|
||||
requests and one durable verified operation. A further process restart retained
|
||||
the final result. Original expiry did not change. This is real process/socket
|
||||
qualification, not a physical B2 firmware acceptance.
|
||||
|
||||
Existing delivery, queue, lost-HTTP-response, expiry, no-effect-replay and clock
|
||||
qualification also passed from the same artifact. Source tests cover target,
|
||||
predecessor and divergent readbacks, repeated restarts, expiry, old versus newer
|
||||
connections and recovery timestamps. Frontend compatibility was built and its
|
||||
21 focused architecture/command/equipment tests passed.
|
||||
The final focused Python run passed 195 tests; Ruff passed. The frontend build
|
||||
retained its existing chunk-size warning. The first sandboxed test attempt
|
||||
could not bind its loopback socket; the permitted full rerun passed.
|
||||
|
||||
The first uninstalled candidate failed because the new harness expected EOF
|
||||
instead of Linux's intentional abortive close for a denied image download. Its
|
||||
evidence and artifact were retained; the corrected candidate was rebuilt and
|
||||
qualified before installation. No failed candidate was installed.
|
||||
|
||||
The versioned installer updated 0.1.29 -> 0.1.30 with a SQLite backup and four
|
||||
unchanged identity files. All 24 installed manifest files matched. The installer
|
||||
download was published in Core. The onboard computer was not updated.
|
||||
|
||||
Physical position checks through the actual Core queue after installation:
|
||||
|
||||
| Sequence | Result from B2 after dispatch |
|
||||
| --- | --- |
|
||||
| Two requests accepted together in Core FIFO | First confirmed in 1.183 s; second expired without confirmation |
|
||||
| Two requests with 15 s pause after completion | Confirmed in 0.610 s and 0.563 s |
|
||||
| Another pair without that pause | Confirmed in 1.514 s and 0.677 s |
|
||||
|
||||
Five of six requests were confirmed. The missing outcome remains visible in
|
||||
history. This small series does not establish a necessary 15 s pacing rule or
|
||||
an unconditional command-delivery guarantee. No such delay was added to the
|
||||
product. During the paced capture each command had one observed transmission;
|
||||
matching B2 token replies arrived on both monitoring connections, the other
|
||||
connection slightly earlier than the dispatch connection. This does not alone
|
||||
explain the earlier unconfirmed command, for which no simultaneous PCAP exists.
|
||||
|
||||
Core's command window was checked after reloading the actual build: successful
|
||||
and unconfirmed operations appear separately with dispatch times and measured
|
||||
round trips. It was left open for inspection. No physical configuration, relay
|
||||
or B2 restart command was sent in these checks; the USB serial port was not opened.
|
||||
|
||||
## Physical recovery and power limits
|
||||
|
||||
The operator later reported unplugging/replugging the unit. The first subsequent
|
||||
check observed fresh VPS telemetry (4.6 s packet age) and one USB interface.
|
||||
Duration, complete loss of power and whether 12 V remained attached were not
|
||||
confirmed. This is an observed return after reconnection, not a proved cold
|
||||
restart or a controlled USB-only power experiment. It also does not establish
|
||||
the cause of the earlier post-configuration cellular silence.
|
||||
|
||||
The [manufacturer's B2 manual](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf)
|
||||
specifies the main supply as 8–50 V and describes Mini USB for diagnostics,
|
||||
configuration and firmware maintenance. It gives no qualified continuous
|
||||
USB-only operating/power budget in the reviewed sections. Observed USB operation
|
||||
does not fill that documentation gap. LED modem status is not proof of fresh
|
||||
end-to-end delivery to the owner's VPS.
|
||||
|
||||
A USB connection to an inverter supplies power but provides no computer-side
|
||||
control channel. A local recovery agent requires an actual data connection to
|
||||
the onboard computer, or a separately controllable power path. Neither exists
|
||||
merely because a USB plug supplies power. Do not introduce an unconditional
|
||||
restart loop: distinguish old archived measurements, live telemetry, command
|
||||
responses, modem loss and local USB enumeration; retain command outcomes before
|
||||
any bounded recovery action.
|
||||
|
||||
Next physical gate: qualify the chosen power arrangement with a known sound
|
||||
cable, record actual supply conditions, reproduce the post-write failure with
|
||||
simultaneous modem/VPS evidence and qualify a bounded recovery mechanism. The
|
||||
present change improves server transaction recovery; it does not yet repair or
|
||||
explain the B2 modem outage.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Проверка сервисной команды через собственный VPS
|
||||
|
||||
## Вопрос и условия
|
||||
|
||||
Проверить, позволяет ли документированная в INTERNAL SERVER_COM команда
|
||||
`01 00` получить свежие сведения SIM после горячей замены. Это проверка
|
||||
поведения, а не заранее квалифицированная команда чтения ICCID.
|
||||
|
||||
Модель 231, ПО 0.01; МегаФон в SIM 1, SIM 2 пуст. По последнему подтверждению
|
||||
владельца питание 12 В непрерывное, USB отключён. Перестановок, изменений
|
||||
конфигурации и команд перезапуска в этом опыте не было.
|
||||
|
||||
Источник кода: лист SERVER_COM официального
|
||||
[протокола INTERNAL](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit).
|
||||
Его описание задаёт переключение диагностики, но не определяет срок и
|
||||
завершение режима на B2 0.01. Общий лист не доказывает конкретные эффекты
|
||||
этой прошивки.
|
||||
|
||||
## Реализация и установка
|
||||
|
||||
VPS 0.1.39 добавляет только инженерный `probe-diagnostic-mode`, без свободного
|
||||
ввода байтов или текста. Требуется отдельно включённое авторизованное окно
|
||||
наблюдения. Одно окно допускает одну команду; повтор с тем же ID возвращает
|
||||
существующий результат. Закрытое/истёкшее окно запрещает отправку.
|
||||
|
||||
Отправка разрешена в течение трёх секунд и только в уже существующее
|
||||
допущенное соединение. После отправки команда не повторяется при смене
|
||||
соединения или перезапуске VPS. Она не добавлена в пользовательский каталог
|
||||
или список долговечных операций. Ответ с токеном означает только ответ B2
|
||||
на команду; не означает чтение SIM либо подтверждение конкретного режима.
|
||||
|
||||
Окно 180 секунд ограничивает нашу запись и отправку. Его закрытие **не**
|
||||
является командой выключения режима B2. Отдельный сеанс диагностики или
|
||||
его завершение в опыте не подтверждены.
|
||||
|
||||
Использован штатный `scripts/build_vps_host.py` и установщик `.pyz`:
|
||||
|
||||
- исходный HEAD: `fb33a6d45c73e6d458faed586959ba1a12775355`, с рабочими изменениями;
|
||||
- предыдущая версия: 0.1.38, установлена 0.1.39;
|
||||
- SHA-256 установщика:
|
||||
`61b5f17706b6c55cfa24623dd2f54ab72fb55002167d2e7f96c242997b032eec`;
|
||||
- повторная сборка побайтово совпала, состав архива проверен;
|
||||
- перед обновлением создана приватная резервная копия журнала;
|
||||
- четыре файла идентичности/конфигурации VPS сохранили контрольные суммы;
|
||||
- штатный сервис после установки активен, Core опрашивает VPS как прежде.
|
||||
|
||||
Изменения совместимости добавляют 0.1.39 в существующие проверки Core и UI.
|
||||
Установщик опубликован в каталоге скачивания Mission Core. Схема на другой
|
||||
чистой Ubuntu по указанию владельца остаётся отдельной будущей проверкой.
|
||||
|
||||
## Измерение
|
||||
|
||||
Приватная сессия `service-mode-probe-00007b025a8b44b29971754f1d803d28`.
|
||||
Пакеты, UTC/монотонные отметки, ответ, установочный отчёт и SHA-манифест
|
||||
сохранены вне обычного Git. Идентичность SIM и координаты здесь не публикуются.
|
||||
|
||||
Обновление VPS закрыло TCP-соединения, B2 переподключился сам. До команды
|
||||
отдельно сохранены девять записей после обновления: новых SID не было.
|
||||
Эта фаза не смешивается с результатом запроса.
|
||||
|
||||
Команда `bd77db50c64f4be6a871b0e90493a924`:
|
||||
|
||||
| Событие | UTC, 28.09.2026 |
|
||||
| --- | --- |
|
||||
| Принятие VPS | 12:05:35.685 |
|
||||
| Отправка | 12:05:35.695 |
|
||||
| Ответ B2, код 0 | 12:05:36.924 |
|
||||
|
||||
Запрос/ответ — **1.230 с**, одна отправка. Ответ принят через другое
|
||||
допущенное соединение того же B2; действовал существующий контроль токена.
|
||||
|
||||
В сохранённом окне после начала запроса — 24 записи, 22 содержат позицию
|
||||
(14 разных времён GNSS-измерения), **ни одной пары тегов SID**. Получение
|
||||
записей: 12:05:36.005–12:08:51.092 UTC. Первая запись была измерена ещё до
|
||||
отправки; близость времени не приписывает обычную координату этой команде.
|
||||
Отдельных нетелеметрических соединений в окне наблюдения VPS — ноль.
|
||||
Передача данных продолжалась через SIM 1; SIM 2 оставалась отсутствующей.
|
||||
|
||||
**Результат:** B2 ответил на команду, но этот опыт не дал свежей идентичности
|
||||
SIM или собственного диагностического канала. Не использовать `01 00` как
|
||||
автоматический опрос SIM. Нулевой ответ не доказывает включение режима и
|
||||
не доказывает, что прошивка полностью игнорирует команду.
|
||||
|
||||
## Проверки и границы
|
||||
|
||||
Проверены истёкшее/закрытое окно, запрет другого запроса в том же окне,
|
||||
отсутствие повтора после отправки и перезапуска, запрет произвольного payload.
|
||||
Набор VPS/runtime/network/bootstrap: 236 тестов; единственный TCP-тест,
|
||||
первоначально запрещённый локальной песочницей, отдельно успешно выполнен
|
||||
с доступом к loopback. Дополнительно прошли два теста установщика, Ruff,
|
||||
TypeScript, 1015 frontend-тестов и production build.
|
||||
|
||||
Приёмка интерфейса на 8000: VPS показывает 0.1.39 и «На связи»; B2 передаёт
|
||||
данные, SIM 1 — МегаФон, SIM 2 — пустой слот. Сохранены полный сетевой доступ
|
||||
к настройкам, штатная геометрия окна и закрытие Escape. Проверены обычный и
|
||||
развёрнутый режимы окна оборудования. Через UI аппаратные команды не отправлялись.
|
||||
|
||||
Следующий нерешённый вопрос — точная семантика запроса идентичности `01 02` /
|
||||
`SERV*1.2` на B2 0.01. Общий SMS_COM называет перечитывание ICCID, руководство
|
||||
именно B2 — ответ SMS с данными устройства. В сохранённой конфигурации есть
|
||||
старый телефонный адресат, не совпадающий с двумя сообщёнными владельцем
|
||||
номерами; автоматически отправлять на него сообщения нельзя. Этот запрос
|
||||
не выполнялся. Общая автономность и обнаружение новой резервной карты
|
||||
по-прежнему не приняты.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Explicit SIM intent and physical settings acceptance — 2026-09-27
|
||||
|
||||
Owner direction: choosing a SIM/operator and pressing Apply is an explicit
|
||||
instruction. Applying unrelated settings must not repeatedly switch the SIM.
|
||||
The damaged USB cable and map infrastructure are deferred by the owner.
|
||||
|
||||
## Implementation
|
||||
|
||||
- `connectivity.activate` remains the portable desired exclusive SIM policy.
|
||||
- The network apply request carries a separate strict boolean `select_sim`.
|
||||
The settings window sends it after an explicit selection or connectivity edit,
|
||||
including selection whose stored configuration bits already match.
|
||||
- The job records this intent; retrying the same revision and intent returns the
|
||||
same job. Changing the intent against an already consumed revision conflicts.
|
||||
- Ordinary profile writes use `configure-all`. A change in the actual SIM policy
|
||||
bits still requires the full selection workflow, including initial profiles.
|
||||
Unchanged SIM bits do not turn an interval edit into a restart.
|
||||
- Fresh SIM-presence admission is scoped to an actual SIM/APN change or explicit
|
||||
SIM action. Unrelated edits are not blocked by stale cellular-slot metadata.
|
||||
- The initial USB bootstrap now accepts VPS Host 0.1.32 and 0.1.33. Its current
|
||||
release acceptance test caught the missing version in the earlier allowlist.
|
||||
|
||||
## Physical acceptance
|
||||
|
||||
Owned B2 model 231 / firmware 0.01; VPS Host 0.1.32; external 12 V, indoor.
|
||||
No USB or output-pin commands were used in this interval/restart cycle. Raw images and instance identities are
|
||||
private. The normal Core API and durable VPS runtime owned every operation.
|
||||
|
||||
| Operation | Result | Attempts |
|
||||
| --- | --- | --- |
|
||||
| Full configuration read | Observed original 15-second interval | 1 |
|
||||
| Field 25: 15 → 16 seconds | Verified by independent full readback | 1 |
|
||||
| Additional read as a new job | Observed 16 seconds | 1 |
|
||||
| Field 25: 16 → 15 seconds | Verified; exact original image restored | 1 |
|
||||
| Restart | Fresh telemetry on a new connection after 58.808 seconds | 1 |
|
||||
| Additional read after restart | Original configuration remained exact | 1 |
|
||||
|
||||
Each settings write took approximately 46 seconds including preflight, paced
|
||||
write, and readback. This is settings-workflow duration, not a general command
|
||||
latency guarantee. The complete 207-record / 983-byte image returned to SHA-256
|
||||
`7e7798a5e2c1909454dfab500dac4cc2d0917555a02f2afac711b167c9ae1ee8`.
|
||||
Only field 25 differed in the temporary image. Both settings operations were
|
||||
`configure-all`, with no `select-sim` or implicit restart operation.
|
||||
|
||||
Browser acceptance on canonical port 8000 showed the verified result and live
|
||||
SIM cards. Saving the unchanged settings displayed “Изменений настроек нет.
|
||||
Команда трекеру не отправлена.” No second command was created.
|
||||
|
||||
Regression checks: 80 equipment/network/profile tests; 35 bootstrap/runtime/
|
||||
reconciliation tests; 14 focused frontend behavior tests; frontend typecheck and
|
||||
production build. Existing build chunk-size warnings remain.
|
||||
|
||||
Private evidence session: `acceptance-e7e12e66a51b4510a2fd5b1a7cc3a93d`.
|
||||
|
||||
## Actual UI SIM selection and recovery
|
||||
|
||||
After that cycle, the normal settings window selected SIM 2 and saved settings.
|
||||
The current network measurement identified SIM 2 as MTS (250-01); no name was
|
||||
inferred from its APN. The admitted operation was `select-sim`, with one attempt.
|
||||
The VPS served the image, independently verified it, and dispatched restart.
|
||||
No fresh target-SIM return was established before the 360-second attempt ended.
|
||||
The owning durable job transitioned to `waiting-link`; it neither vanished nor
|
||||
reported success, and no second attempt was dispatched without fresh input.
|
||||
|
||||
The operation was explicitly stopped before local recovery. The operator then
|
||||
specifically approved use of the already connected damaged USB cable for this
|
||||
recovery only. USB found the exact verified SIM-2 target image. The recovery
|
||||
changed only field 72, restored the entire original 983-byte image, checked it
|
||||
independently, and sent one qualified restart. Core's desired SIM was returned
|
||||
to SIM 1 without admitting another switch job. A new independent network read
|
||||
then succeeded in one attempt and matched the exact original SHA-256 above.
|
||||
The UI again showed fresh SIM-1/GPRS use and VPS telemetry.
|
||||
|
||||
This is a failed remote SIM-2 connectivity qualification plus successful USB
|
||||
recovery and subsequent network read. It is not a successful remote roundtrip
|
||||
between both SIMs. It does not establish that MTS or the SIM itself is defective.
|
||||
The qualified selection mechanism prohibits GPRS on the other slot; it has no
|
||||
demonstrated automatic fallback. A server queue cannot restore connectivity
|
||||
through the same unavailable mobile path. Preferred-SIM fallback and an
|
||||
independent SMS recovery channel remain unqualified.
|
||||
|
||||
## Remaining acceptance
|
||||
|
||||
- A successful different-SIM selection and return remains unqualified; the
|
||||
concrete failure and bounded recovery are recorded above.
|
||||
- Same-device re-enrollment of a blank profile needs the qualified USB bootstrap;
|
||||
defer its physical run until the replacement cable, as requested by the owner.
|
||||
- Startup with the current qualified configuration returned to the owned VPS.
|
||||
Periodic background/no-update firmware dialogue is not yet fully qualified;
|
||||
this does not claim complete parity with the manufacturer's configurator.
|
||||
- Clean OS installation, firewall closure, independent backup/restore and a new
|
||||
host migration have their own acceptance. Updating an installed VPS is not
|
||||
proof of those outcomes.
|
||||
- Worker 006 (`mission-gpu`) was unreachable by SSH during this session. No
|
||||
thousand-device capacity claim or local-Mac load run was made.
|
||||
@@ -0,0 +1,111 @@
|
||||
# Наблюдения SIM в продуктовом чтении B2
|
||||
|
||||
Дата: 2026-09-28. Это реализация учёта идентичности, не приёмка автоматического
|
||||
подбора APN. Серверный протокол и направления сетевых соединений не менялись.
|
||||
|
||||
## Реализовано
|
||||
|
||||
Штатный USB-читатель сохраняет результаты в приватном журнале
|
||||
`independent-equipment/evidence/sim-identity/observations.sqlite3`.
|
||||
Каталог имеет права 0700, база — 0600; запись транзакционная с `synchronous=FULL`.
|
||||
Запись связана с IMEI трекера, идентификатором чтения, временным интервалом,
|
||||
USB-сеансом и SHA-256 исходного потока. USB-сеанс не объявляется сеансом
|
||||
загрузки: отключение кабеля не доказывает отключение питания B2.
|
||||
|
||||
`I 7` теперь имеет отдельную классификацию:
|
||||
|
||||
| Ответ | Смысл |
|
||||
| --- | --- |
|
||||
| Пустой / 0 | Идентификатор не сообщён; отсутствие SIM этим не доказано |
|
||||
| Меньше 19 цифр | Неполный отчёт |
|
||||
| 19–22 цифры | Непроверенный SID прошивки; длина не доказывает канонический ICCID |
|
||||
|
||||
Пассивный поток обрабатывается только для квалифицированной модели 231/0.01.
|
||||
Согласованное наблюдение требует непрерывной последовательности
|
||||
`AT+CCID → ответ → OK → SIDn → AT+CIMI → ответ → OK → HCn` с одинаковым номером
|
||||
слота и согласованным домашним кодом IMSI. Разрыв последовательности, ошибка,
|
||||
другая команда, смена слота или незавершённая строка не объединяются по времени.
|
||||
Наш читатель эти AT-команды не отправляет: они наблюдаются в обмене самой B2
|
||||
с её модемом.
|
||||
|
||||
Исходные CCID, SID и IMSI сохраняются раздельно и без нормализации.
|
||||
Квалифицированы наблюдаемые формы CCID: 19–20 цифр и 18 цифр с `ff`.
|
||||
Последняя форма сохраняется буквально; её преобразование в канонический
|
||||
ICCID не реализовано. Домашний код сети не объявляется поставщиком SIM,
|
||||
названием MVNO или тарифом.
|
||||
|
||||
Повторяющаяся точная пара **сырой CCID + IMSI** получает устойчивую случайную
|
||||
ссылку в пределах одного трекера. Номер слота в эту пару не входит.
|
||||
Разные карты в одном слоте за время записи либо одинаковая пара в обоих
|
||||
слотах дают неоднозначное наблюдение, без назначения ссылки слоту.
|
||||
Совпадение только SID не объединяет карты.
|
||||
|
||||
Неполные и обычные чтения остаются в журнале, но не заменяют полное наблюдение
|
||||
модема. API возвращает текущий отчёт и предыдущее наблюдение отдельно:
|
||||
`observed.sim_identity`. Историческое наблюдение содержит явные
|
||||
`historical: true`, `current_slot_binding: false`. Сроков, после которых
|
||||
старое наблюдение превращается в доказательство текущей карты, нет.
|
||||
Ни один из этих результатов сам по себе не разрешает автоматическую запись.
|
||||
|
||||
Обновление через штатный `/instances/{id}/inspect` сохраняет настройки,
|
||||
назначение роверу и историю экземпляра. Сведения о SIM не попадают в
|
||||
переносимые профили. Полные идентификаторы, IMSI и внутренние ключи совпадения
|
||||
не выдаются в публичной проекции; публичная ссылка случайная.
|
||||
Повторная запись того же снимка идемпотентна; другой материал под тем же
|
||||
идентификатором отвергается. Пропавшие/повреждённые файлы дают состояние
|
||||
«сведения недоступны», а не «SIM отсутствует».
|
||||
|
||||
Обычное чтение сохраняет прежнее двухсекундное пассивное окно. Инженерный CLI
|
||||
читателя поддерживает `--observe-seconds` от 2 до 180 для записи запуска,
|
||||
после которой следуют те же штатные чтения идентичности и конфигурации.
|
||||
Это ограниченная операция, не постоянно работающий USB-наблюдатель.
|
||||
|
||||
## Проверки
|
||||
|
||||
- Синтетические регрессии: две карты, перестановка, неоднозначные/повреждённые
|
||||
последовательности, неизвестная версия прошивки, неполный SID, повторное
|
||||
открытие базы, отсутствие утечки уникальных значений в профили и ответы API.
|
||||
- После двух полных записей и 40 последующих неполных чтений предыдущие
|
||||
данные модема остаются доступны как исторические; ссылки следуют за картами.
|
||||
- Обработка сохранённых физических записей обеих расстановок из
|
||||
`dual-sim-identity-e81e0384e86d442dbda64636d8dbd563` новым кодом: четыре
|
||||
согласованных наблюдения; точные пары CCID/IMSI переместились вместе с SIM.
|
||||
Старые записи не внесены в текущий продуктовый журнал и не выданы за свежие.
|
||||
- После загрузки кода в канонический Core выполнено новое штатное чтение:
|
||||
SIM 1 — 12 цифр, SIM 2 — 20; состояния `incomplete` / `unverified`.
|
||||
APN и остальные настройки не изменены. Потока запуска в этом чтении нет,
|
||||
и код не выдумал полные идентификаторы из короткого отчёта.
|
||||
- Владелец отключил 12 В и USB на 10 секунд, затем подключил оба источника,
|
||||
сохранив МТС в первом слоте и МегаФон во втором. Штатный читатель с
|
||||
90-секундным пассивным окном получил две полные последовательности:
|
||||
домашние коды 25001 / 25002. Точные CCID, IMSI и SID совпали с предыдущей
|
||||
записью тех же карт в этих слотах. Эти свежие данные внесены в продуктовый
|
||||
журнал, без импорта старого опыта.
|
||||
- Затем перезапущен канонический Core и выполнено ещё одно обычное чтение.
|
||||
Получены прежние 12/20 цифр, но ссылки на обе полные записи и их исходное
|
||||
время сохранились как история. Конфигурация осталась побайтово прежней:
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
- Один контрольный запрос координат через Core → VPS → B2 подтверждён
|
||||
устройством с первой попытки, код 0: **0,960 секунды** от отправки VPS до
|
||||
ответа B2 (08:50:28.499–08:50:29.459 UTC). Это одиночное измерение,
|
||||
не гарантия задержки. Никаких записей APN, конфигурации или прошивки.
|
||||
|
||||
Приватная сессия проверки:
|
||||
`outputs/arnavi-b2/sim-observation-runtime-7164036dad134462917685b81e0c9719/`.
|
||||
В ней находятся результаты воспроизведения, хеши исходных материалов,
|
||||
состояния до/после чтения и запись проверки канонического сервиса.
|
||||
|
||||
## Оставшиеся границы
|
||||
|
||||
Это ещё не автоматический выбор и применение APN. Не реализованы: запрос
|
||||
полной пары CCID/IMSI по требованию без потока запуска, привязка ожидающего
|
||||
намерения настройки к подтверждённой карте, редактируемый версионируемый
|
||||
каталог и исполнитель подбора с проверкой свежего выхода на VPS.
|
||||
Существующие ручные операции по слотам этой доработкой не переопределяются.
|
||||
|
||||
Из неподключённого к компьютеру B2 VPS не получает USB-поток запуска.
|
||||
Следующий этап обнаружил и реализовал отдельный
|
||||
[сетевой источник SID двух SIM](NETWORK_SIM_IDENTITY_20260928.md): стартовые
|
||||
теги INTERNAL сопоставлены с полными USB-наблюдениями обеих расстановок.
|
||||
Это не сетевое чтение IMSI и не приёмка автоматического переноса APN для
|
||||
произвольной новой карты при питании только от адаптера.
|
||||
@@ -0,0 +1,287 @@
|
||||
# Выбор SIM с сохранением резерва
|
||||
|
||||
Дата: 2026-09-28. Требование владельца; полная аппаратная реализация пока не
|
||||
подтверждена. Это уточняет семантику выбора SIM из предыдущих этапов.
|
||||
|
||||
Последующее приращение: [режим двух разрешённых SIM без заданного APN](NATIVE_INTERNET_POLICY_20260928.md)
|
||||
доступен в интерфейсе и профилях, принят через собственный VPS с возвратом
|
||||
свежего GPRS после перезапуска. Он не реализует ручное предпочтение одной карты.
|
||||
|
||||
## Ожидаемое поведение
|
||||
|
||||
Оба слота разрешены постоянно. Пользователь выбирает предпочтительную карту,
|
||||
а не запрещает интернет через другую. Предпочтение относится к подтверждённой
|
||||
идентичности карты; номер слота — её текущее положение. Настройки интернета,
|
||||
предпочтение пользователя и фактически работающая SIM — разные сведения.
|
||||
|
||||
| Изменение | Ожидаемый результат |
|
||||
| --- | --- |
|
||||
| Новый трекер или обе карты заменены, вставлены две новые | Первая попытка через SIM 1; при неуспехе доступна SIM 2 |
|
||||
| Вставлена одна карта в любой слот | Попытка подключения через единственную карту |
|
||||
| Работает одна карта, добавлена вторая | Сохранить действующее подключение |
|
||||
| Работает SIM 2, в SIM 1 заменили карту | Сохранить действующее подключение через ту же карту SIM 2 |
|
||||
| Пользователь выбрал другую обнаруженную карту | Переключить связь и подтвердить новый канал, оставив прежний разрешённым |
|
||||
| Действующая карта извлечена или перестала обеспечивать связь | Автоматически попробовать оставшуюся карту; участия интерфейса не требуется |
|
||||
| Карты переставлены между слотами | Сохранить предпочтение, если идентичность прежней выбранной карты подтверждена |
|
||||
| Обеих карт нет | Состояние без SIM; не отправлять старые настройки в будущую неизвестную карту |
|
||||
|
||||
Начальный выбор SIM 1 не означает бесконечное ожидание неработающей карты.
|
||||
Отсутствие пакетов на VPS не доказывает извлечение SIM. После получения свежего
|
||||
сообщения об отсутствии карты её оператор исчезает из текущего слота и выбора;
|
||||
история и последняя координата сохраняются с исходным временем. При отсутствии
|
||||
канала интерфейс показывает последнее известное состояние, а не выдуманную замену.
|
||||
|
||||
После автоматического ухода на резерв рабочее соединение сохраняется; фоновый
|
||||
периодический возврат на прежнюю карту не вводится без отдельного требования.
|
||||
Это выбранная трактовка требования «остаёмся на той, на которой работали»;
|
||||
её нельзя объявлять поведением прошивки до проверки. Перезапуск сам по себе
|
||||
не должен стирать пользовательское предпочтение или журнал операции.
|
||||
|
||||
## Граница реализации B2 231 / 0.01
|
||||
|
||||
Проверены публичная схема модели 231, руководство B2 и доступные таблицы
|
||||
команд. Поле 72, биты 10 и 20, **запрещает** GPRS на SIM 1 и SIM 2.
|
||||
Оно не описывает предпочтение, временное переключение или таймер возврата.
|
||||
Отдельной документированной команды приоритета в проверенных источниках
|
||||
не найдено; это не утверждение о невозможности недокументированной функции.
|
||||
|
||||
- Существующий `strategy=both` очищает эти два запрета и сохраняет APN обоих
|
||||
слотов. Реализованный цикл проверяет конфигурацию и новый сеанс GPRS.
|
||||
- Существующий `strategy=sim, activate=true` устанавливает запрет для другой
|
||||
карты. Ранее принятые тесты подтверждают **исключительный** выбор. Этот
|
||||
механизм не реализует новое требование и не должен переименовываться в
|
||||
«предпочтение» без другого аппаратного исполнителя.
|
||||
- Временный запрет с последующим снятием через VPS также не является
|
||||
гарантированным резервированием: при потере нового канала запрет может
|
||||
остаться, а команда снятия до B2 не дойдёт.
|
||||
- Наш каталог и кэш проверенных параметров доступны на Core/VPS. Они не
|
||||
исполняются внутри B2. Две совершенно новые карты с неподходящими APN не
|
||||
смогут получить исправление по ещё не работающему мобильному интернету.
|
||||
- Для полного сценария автономного B2 нужны подтверждённые функции его
|
||||
прошивки. Альтернатива — независимый местный исполнитель с USB **данными**,
|
||||
офлайн-каталогом и долговечной политикой. USB от блока питания этого не даёт;
|
||||
обязательный бортовой компьютер не добавляется незаметно.
|
||||
|
||||
Сохраняются готовые механизмы идентичности, привязки к роверу, защиты от записи
|
||||
в заменённую карту, чтения результата и долговечного журнала. Новый механизм
|
||||
выбора должен использовать их, а не менять привязку оборудования к оператору.
|
||||
Core продолжает сам обращаться к VPS; входящее соединение VPS → Core не нужно.
|
||||
|
||||
## Приёмка следующего этапа
|
||||
|
||||
Уточнение владельца после подготовки проверки: основной сценарий требует
|
||||
**непрерывного внешнего питания**. Прежняя инструкция выключить питание перед
|
||||
удалением SIM отменена. Положительный запуск после обесточивания не закрывает
|
||||
горячее обнаружение замены. Нельзя незаметно отправлять программный перезапуск
|
||||
и считать его успешным переключением без перезапуска.
|
||||
|
||||
Руководство B2, раздел 7, рекомендует при первоначальном подключении установить
|
||||
SIM до внутреннего АКБ и внешнего питания. Отдельного утверждения о поддержке
|
||||
горячей замены либо её процедуры в просмотренном руководстве нет. Следующая
|
||||
проверка на принадлежащем владельцу тестовом экземпляре экспериментальная;
|
||||
результат не является подтверждением производителя для серийной эксплуатации.
|
||||
|
||||
1. Разрешить обе SIM существующим циклом: прочитать, изменить только запреты,
|
||||
записать, проверить чтением и свежим подключением после перезапуска.
|
||||
2. Сохранив 12 В и отсутствие USB, удалить только действующую SIM 1, оставив
|
||||
известную МТС в SIM 2. Проверить выход на VPS без ручной команды и обновление
|
||||
пустого слота в интерфейсе. Отдельно фиксировать подтверждение извлечения,
|
||||
последнее сообщение старого канала, TCP и первое свежее сообщение нового.
|
||||
Не выдавать отсутствие исходящего restart за доказательство отсутствия
|
||||
внутреннего перезапуска B2: для этого нужен отдельный признак запуска.
|
||||
3. Добавить вторую карту и проверить сохранение прежней. Холодный запуск с
|
||||
одной/двумя картами остаётся отдельной проверкой памяти выбора и восстановления,
|
||||
а не подменой основного сценария. Самостоятельное переключение на уже
|
||||
установленный резерв и обнаружение вновь вставленной карты проверяются отдельно.
|
||||
4. Отдельно подтвердить документированный исполнитель предпочтения с резервом
|
||||
и начальной настройки APN без интернета. До этого полную матрицу не считать
|
||||
реализованной и не обещать непрерывный/мгновенный переход.
|
||||
|
||||
## Применено на тестовом B2
|
||||
|
||||
Сессия `sim-preference-92e48b00ed4a4f22aa561baaf98a7801`, VPS 0.1.38.
|
||||
При старте: МегаФон в SIM 1, МТС в SIM 2; питание 12 В, USB отключён.
|
||||
Чтение `0c3f6ae7611f4dacbe08278ec0337a78` завершилось с первой попытки.
|
||||
Штатная операция `22101e0a920242ebb30d9e7c78dd9941` применила `strategy=both`.
|
||||
От создания до подтверждения прошло 98.409 с; одна попытка. Проверены точное
|
||||
чтение целевого образа, перезапуск и свежая связь через SIM 1. Меняется только
|
||||
поле 72, очищается запрет GPRS SIM 2; остальные 206 записей сохранены.
|
||||
|
||||
- До записи: SHA-256 `7e7798a5e2c1909454dfab500dac4cc2d0917555a02f2afac711b167c9ae1ee8`.
|
||||
- После записи: SHA-256 `a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
|
||||
При проверке 2026-09-28 10:30:11 UTC обе карты зарегистрированы, активна SIM 1,
|
||||
свежая позиция доступна. Первоначальное предложение удалить SIM 1 при выключенном
|
||||
питании отменено по уточнению владельца. В 10:43:10 UTC снова подтверждены
|
||||
свежие данные через SIM 1, обе SIM зарегистрированы, политика `both` применена.
|
||||
Подготовлена проверка извлечения только МегаФона при сохранении 12 В и без USB;
|
||||
новые команды и перезапуски не отправлялись. Подтверждение физического действия
|
||||
на тот момент ожидалось.
|
||||
|
||||
## Извлечение активной SIM без отключения питания: результат
|
||||
|
||||
Владелец подтвердил удаление МегаФона из SIM 1 при сохранении питания 12 В,
|
||||
МТС в SIM 2, USB отключён. Подтверждение записано около 10:44:41 UTC; позднее
|
||||
владелец уточнил, что карту уже извлёк примерно за 30 секунд до своего сообщения
|
||||
о старом статусе интерфейса. Точное время физического извлечения не измерялось.
|
||||
Во время наблюдения Core/VPS не отправляли команды переключения, настройки или
|
||||
перезапуска. Политика обеих разрешённых SIM была применена заранее.
|
||||
|
||||
Прочитан штатный долговечный журнал Core (пакеты с собственного VPS); исходные
|
||||
байты сохранены приватно с SHA-256. Время ниже — Москва, UTC+3:
|
||||
|
||||
| Событие | Измерение B2 | Получение VPS |
|
||||
| --- | --- | --- |
|
||||
| Последнее состояние SIM 1 / GPRS 4, обе карты зарегистрированы | 13:44:12 | 13:44:16.348 |
|
||||
| SIM 1 отсутствует; активна SIM 2, модем 2 | 13:44:27 и 13:44:42 | 13:44:59.396, один пакет с двумя записями |
|
||||
| SIM 1 отсутствует; SIM 2 / GPRS 4 | 13:44:57 | 13:45:00.933 |
|
||||
| Последующие свежие записи SIM 2 / GPRS 4 | каждые 15 с до 13:46:27 | до 13:46:31.211 |
|
||||
|
||||
За контрольное окно принято **7 последовательных пакетов** со свежими
|
||||
позициями и SIM 2 / GPRS 4 (номера 17216–17228, шаг 2 в общем журнале).
|
||||
Интервал измерений всех семи записей — 15 с; интервал их поступления около
|
||||
14–16 с. Между последним пакетом с активной SIM 1 и первым пакетом после
|
||||
восстановления прошло 43.049 с. Это разрыв доставки, не точное время реакции
|
||||
от извлечения SIM. Две записи периода перехода поступили с задержкой; нельзя
|
||||
выдавать их время получения за время измерения.
|
||||
|
||||
Владелец также подтвердил автоматическое изменение интерфейса на
|
||||
«SIM 2 используется для интернета». Ранее надпись SIM 1 сохранялась после
|
||||
извлечения: последнее сообщение ещё попадало в существующее 90-секундное
|
||||
окно актуальности, а сведения об отсутствии SIM пришли вместе с восстановлением
|
||||
канала. Сервер не мог узнать о физическом извлечении до этих сообщений.
|
||||
|
||||
**Принято в этой области:** извлечение активной МегаФон SIM 1 привело к
|
||||
самостоятельному восстановлению передачи через заранее установленную МТС
|
||||
SIM 2, без отключения внешнего питания и без нашей команды перезапуска.
|
||||
Отсутствие внутреннего сброса модема/контроллера не доказано отдельным счётчиком
|
||||
запусков. Вставка новой карты под питанием, обратный переход, предпочтение
|
||||
пользователя, новые операторы и повторяемость при других условиях ещё не приняты.
|
||||
|
||||
## Добавление резервной карты при работе через SIM 2
|
||||
|
||||
Фаза `02-insert-reserve`. До вставки: SIM 1 отсутствует, МТС SIM 2 передаёт
|
||||
свежие GNSS-данные. Владелец подтвердил вставку МегаФона в первый слот без
|
||||
отключения 12 В и без USB; подтверждение записано в 10:51:44 UTC. Команды,
|
||||
записи конфигурации и программный перезапуск во время фазы не выполнялись.
|
||||
|
||||
После подтверждения получены восемь новых измерений с позициями
|
||||
(13:51:57–13:53:42 по Москве, 15 с между измерениями). Во всех активна SIM 2,
|
||||
GPRS 4, а состояние SIM 1 по-прежнему 0 — карта не обнаружена. Последнее
|
||||
измерение сделано через 117.5 с после регистрации подтверждения владельца.
|
||||
Теги идентичности SIM в этом окне не поступали. Владелец независимо подтвердил
|
||||
ту же надпись в интерфейсе. Это свежие сообщения B2, а не застывший UI.
|
||||
|
||||
**Результат частичный:** действующий канал сохранился; обнаружение вставленной
|
||||
резервной карты в данном окне не произошло. Причина пока не установлена:
|
||||
нельзя по этому наблюдению утверждать ни дефект интерфейса, ни отсутствие
|
||||
горячей замены вообще, ни конкретный алгоритм опроса неактивного слота.
|
||||
|
||||
Подготовлена фаза `03-remove-mts`: оставить вставленный МегаФон SIM 1 и
|
||||
извлечь только активную МТС SIM 2, не отключая 12 В. Она проверит, обнаружит ли
|
||||
трекер первый слот после потери действующего канала. До подтверждения владельца
|
||||
следующий шаг не считается выполненным; автоматического перезапуска нет.
|
||||
|
||||
## Удаление МТС после вставки МегаФона: результат
|
||||
|
||||
Фаза `03-remove-mts`. Владелец подтвердил удаление МТС из SIM 2, оставив
|
||||
МегаФон в SIM 1 в рамках проверки с непрерывным питанием. Подтверждение
|
||||
зарегистрировано в 10:57:17 UTC, точное время извлечения не измерялось.
|
||||
Политика оставалась `both`; журнал Core не содержит новых команд после
|
||||
заранее завершённого применения обеих разрешённых SIM.
|
||||
|
||||
| Событие | Измерение B2, Москва | Получение VPS, Москва |
|
||||
| --- | --- | --- |
|
||||
| Последний своевременно полученный пакет через SIM 2 | 13:56:57 | 13:57:00.173 |
|
||||
| Обе SIM отмечены как отсутствующие, модем 2 | 13:57:27 | 14:00:07.034, накопленный пакет |
|
||||
| SIM 1: поиск сети, SIM 2 отсутствует | 13:59:27 | тот же накопленный пакет |
|
||||
| SIM 1 зарегистрирована, выбрана модемом | 13:59:42 | тот же накопленный пакет |
|
||||
| SIM 1 / GPRS 4, SIM 2 отсутствует | 13:59:55 | 14:00:08.020 |
|
||||
|
||||
Разрыв поступления данных — **186.861 с**. После восстановления приняты пять
|
||||
различных свежих GNSS-измерений через SIM 1 за 13:59:55–14:00:55. Повторные
|
||||
приходы архивных пакетов не считаются новыми измерениями; отчёт сохраняет
|
||||
исходные времена измерения и получения отдельно. VPS оставался доступным,
|
||||
Core штатно опрашивал его; во время разрыва `online`/`position_fresh` стали false.
|
||||
|
||||
**Принят ограниченный результат:** B2 сам обнаружил вставленный ранее
|
||||
МегаФон после удаления активной МТС и восстановил передачу, без отключения
|
||||
внешнего питания и без нашей команды переключения/перезапуска. Этот опыт
|
||||
не доказывает точный таймер прошивки или обязательную проверку только при
|
||||
отказе: установлена наблюдаемая последовательность одного перехода.
|
||||
|
||||
Дополнительная граница: свежие статусы слотов восстановились, но наблюдения
|
||||
полных SID в проекции остались от предшествующего запуска (10:29:30 UTC).
|
||||
Они уже инвалидированы извлечением/поиском. Поэтому восстановление интернета
|
||||
не даёт права автоматически считать прежнюю идентичность новой картой в слоте
|
||||
и применять к ней сохранённые настройки. Горячее повторное чтение идентичности
|
||||
остаётся отдельной задачей. Команда `SERV1.2` не отправлялась: общий лист
|
||||
команд и руководство B2 описывают разную семантику, включая отправку SMS.
|
||||
|
||||
## Оба слота пустые при включённом питании
|
||||
|
||||
Фаза `04-no-sims`: после восстановления через МегаФон владелец извлёк и его,
|
||||
подтвердив, что оба слота пусты, питание осталось включённым. Подтверждение
|
||||
зарегистрировано в 11:03:05 UTC. Последнее измерение B2 — 14:02:55 по Москве;
|
||||
его повторный пакет получен в 14:03:06.668. Это не новая координата после
|
||||
подтверждения извлечения. Новые измерения в этой фазе не поступили.
|
||||
|
||||
В 14:04:49 по Москве локальный API показал `online=false`,
|
||||
`position_fresh=false`; последнему приёму 103 с, измерению статуса 114.7 с.
|
||||
Связь Core с VPS оставалась исправной. Последние сведения сохранены как
|
||||
история; сервер не заявил новое подтверждённое состояние «обе карты отсутствуют»
|
||||
без сообщения B2. Отсутствие карт в этой фазе подтверждено оператором.
|
||||
|
||||
Подготовлена фаза `05-single-mts`: вставить только прежнюю МТС в SIM 2 после
|
||||
периода отсутствия обеих карт, сохранив питание и отключённый USB. Настройки
|
||||
APN заранее подходили этой МТС; даже успешный результат не означает
|
||||
автоподбор для произвольной новой SIM или другого оператора.
|
||||
|
||||
## Вставка единственной МТС после пустых слотов: результат
|
||||
|
||||
Фаза `05-single-mts`: владелец вставил прежнюю МТС во второй слот, первый
|
||||
оставил пустым. Подтверждение зарегистрировано в 11:07:29.939 UTC. Внешнее
|
||||
питание 12 В сохранялось; USB, команды переключения и перезапуска не
|
||||
использовались. В журнале Core последней операцией осталось заранее
|
||||
завершённое разрешение обеих SIM. Параметры APN в этой фазе не записывались.
|
||||
|
||||
| Событие | Измерение B2, Москва | Получение VPS, Москва |
|
||||
| --- | --- | --- |
|
||||
| Обе карты отсутствуют после предыдущего извлечения | 14:03:10 и далее | 14:09:21.776, накопленные записи |
|
||||
| МТС зарегистрирована в SIM 2, модем 2; SIM 1 отсутствует | 14:08:40 | 14:09:25.156 |
|
||||
| SIM 2 / GPRS 4, свежая GNSS-позиция | 14:09:10 | 14:09:29.616 |
|
||||
| Последняя запись контрольного окна, SIM 2 / GPRS 4 | 14:12:24 | 14:12:28.397 |
|
||||
|
||||
Первый пакет после восстановления получен через **111.837 с от регистрации
|
||||
подтверждения владельца**; первое свежее измерение с GPRS 4 — через 119.678 с.
|
||||
Это не точный замер от физической вставки. Первые пакеты содержали архив;
|
||||
поступление архива не выдано за появление новой координаты в момент приёма.
|
||||
|
||||
В контрольном окне 14 различных свежих GNSS-измерений через SIM 2: первый
|
||||
интервал 14 с, остальные 15 с. Наблюдалось 12–16 спутников, сеть 250-01.
|
||||
API подтвердил `online=true`, `position_fresh=true`, первый слот пуст,
|
||||
второй зарегистрирован и используется для GPRS. Исходные пакеты, времена,
|
||||
аудит команд и SHA-256 сохранены в приватных артефактах этой фазы.
|
||||
|
||||
**Принято:** после периода с обоими пустыми слотами единственная известная
|
||||
МТС в SIM 2 сама восстановила передачу через собственный VPS при непрерывном
|
||||
внешнем питании. Точная длительность реакции, отсутствие внутреннего сброса
|
||||
модема и начальная настройка произвольного нового оператора этим не доказаны.
|
||||
Новых тегов полной идентичности карты не пришло: действующая сеть известна,
|
||||
но старую идентичность из предыдущего запуска нельзя восстановить по одному
|
||||
названию оператора. Это остаётся препятствием для безопасного автоматического
|
||||
применения параметров конкретной заменённой карты.
|
||||
|
||||
Итог серии: автономное восстановление с известными картами и подходящими APN
|
||||
подтверждено в трёх переходах. Добавленная неактивная карта не обнаружилась
|
||||
немедленно, а сроки восстановления различались. Предпочтение пользователя
|
||||
с сохранением резерва, свежее чтение идентичности после замены и автоподбор
|
||||
APN для неизвестных карт остаются незакрытыми пунктами; серия не даёт основания
|
||||
объявлять всю ожидаемую матрицу готовой.
|
||||
|
||||
Источники:
|
||||
|
||||
- [Схема модели 231](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations)
|
||||
- [Руководство B2, разделы 9–10](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf)
|
||||
- [Проверка выбора карты и параметров доступа](CARD_ACCESS_APPLICATION_20260928.md)
|
||||
- [Автоматическая настройка связи: ограничения и исполнители](AUTOMATIC_CONNECTIVITY_DESIGN_20260928.md)
|
||||
@@ -0,0 +1,101 @@
|
||||
# Перестановка одной SIM между слотами B2, 2026-09-28
|
||||
|
||||
Сессия: `sim-slot-identity-d1551bdf0dd4457dba6f6d4122841f6e`.
|
||||
Испытан тот же B2 модели 231 с прошивкой 0.01 и одна физическая МТС.
|
||||
Цель — подтвердить распознавание карты независимо от слота и наблюдать
|
||||
этапы подключения, сохранив конфигурацию. Это не приёмка автоматического APN.
|
||||
|
||||
## Последовательность и результат
|
||||
|
||||
До начала опыта B2 работал через МТС во втором слоте, без USB, с внешним
|
||||
питанием 12 В. Core подтвердил свежую телеметрию и отсутствие ожидающих команд.
|
||||
Владелец выполнил два полных отключения питания и перестановки:
|
||||
|
||||
| Этап | Идентификация | Мобильное подключение |
|
||||
| --- | --- | --- |
|
||||
| МТС перемещена из второго в первый слот; второй пустой | Тот же 20-значный ICCID и 15-значный IMSI; полный ICCID сообщён как SID0 | В 173,2 с пассивной USB-записи не было `CSTT`, `CIICR` или `CIPSTART`. За окно 318,4 с до наблюдаемого отключения USB не было входящих пакетов на VPS:9922 |
|
||||
| Та же МТС возвращена во второй слот; первый пустой | Те же ICCID и IMSI; полный ICCID сообщён как SID1 | Использован сохранённый `internet.mts.ru`, открыты соединения с VPS; получены свежие данные SIM 2 / сеть 250-01 и подтверждение запроса координат |
|
||||
|
||||
Границы сетевых окон получены по временам наблюдения USB. Это не точные
|
||||
моменты включения и выключения внешнего питания. Нулевой сетевой результат
|
||||
первого этапа относится только к указанному окну, не означает постоянный
|
||||
отказ первого слота.
|
||||
|
||||
Запрос координат после возврата создан 07:56:25.228 UTC, отправлен
|
||||
07:56:25.244 UTC, подтверждён 07:56:26.895 UTC: `device_confirmed`, код 0,
|
||||
одна попытка, **1,651 секунды** от отправки VPS до подтверждения трекера.
|
||||
Это один контрольный запрос, не статистика задержки. Время указано в UTC.
|
||||
|
||||
## Идентичность карты подтверждена штатным чтением
|
||||
|
||||
В обеих фазах после завершения пассивной записи выполнено чтение через
|
||||
существующий USB-адаптер Mission Core: запрос идентичности `I 7`, чтение
|
||||
конфигурации и повторный `I 7` с проверкой неизменности идентичности.
|
||||
|
||||
Первое чтение вернуло 20-значный ICCID для SIM 1 и отсутствие карты в SIM 2;
|
||||
после возврата — отсутствие SIM 1 и тот же полный ICCID для SIM 2. SHA-256
|
||||
значений совпал с полным ответом внутреннего модема `AT+CCID` в предыдущем
|
||||
успешном запуске. На первом этапе это чтение работало без связи B2 с VPS.
|
||||
|
||||
Таким образом, полный ICCID для этой карты доступен не только в потоке
|
||||
запуска, но и штатным запросом по USB. Раннее наблюдение 12-значного SID
|
||||
не является универсальным ограничением прошивки. Продукт уже сохраняет
|
||||
исходную длину и значение; дополнять короткие отчёты цифрами нельзя.
|
||||
|
||||
Полный IMSI наблюдался в ответе внутреннего модема при запуске; его
|
||||
получение штатным запросом по требованию этим опытом не установлено.
|
||||
Две одновременно вставленные SIM, новый оператор и MVNO не испытывались.
|
||||
|
||||
Это ограничение относится к данной сессии с одной картой. Последующий
|
||||
[опыт с двумя картами](DUAL_SIM_IDENTITY_20260928.md) подтвердил их перестановку
|
||||
по потоку запуска, но выявил 12-значный ответ `I 7` для первого слота. Нельзя
|
||||
переносить успешное чтение одной МТС на сценарий двух одновременно вставленных SIM.
|
||||
|
||||
## Конфигурация и границы объяснения отказа
|
||||
|
||||
Оба чтения подтвердили неизменный образ из 207 записей, 983 байта, SHA-256:
|
||||
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
|
||||
В SIM 1 оставались прежние `internet` и данные доступа, в SIM 2 —
|
||||
`internet.mts.ru` и данные доступа МТС. Новых настроек, прошивки и команд
|
||||
управления выходами не записывали. Повторный запуск выполнял владелец.
|
||||
|
||||
Поэтому опыт не является сравнением слотов с одинаковым APN и не доказывает
|
||||
аппаратную неисправность SIM 1. При этом в записанном неуспешном запуске
|
||||
не наблюдалось даже отправки команды настройки APN или открытия TCP;
|
||||
нельзя объявить старый APN установленной причиной всего отказа.
|
||||
В диагностике повторялись ответы `CGATT`/`CGATTDS` со значением 0;
|
||||
точная причина этого состояния требует отдельной квалификации.
|
||||
|
||||
При восстановлении сервер сначала получил накопленные измерения о SIM 1.
|
||||
Для контрольной команды дождались измерения SIM 2 с временем после сообщения
|
||||
владельца о возврате. Время получения пакета не использовали вместо времени
|
||||
измерения для определения текущего слота.
|
||||
|
||||
## Доказательства и завершение
|
||||
|
||||
Приватный каталог `outputs/arnavi-b2/<session>/` содержит исходный поток
|
||||
первой фазы и подкаталог `return-slot2/` для второй, журналы времени UTC и
|
||||
монотонного времени, чтения продукта, заметки владельца, сетевой захват и
|
||||
итоговый манифест SHA-256. Идентификаторы SIM, сырые пакеты, координаты и
|
||||
полная конфигурация в обычный Git не включаются.
|
||||
|
||||
Захват VPS: 115 пакетов захвачено, 115 получено фильтром, 0 потерь ядра.
|
||||
Во второй фазе наблюдалось 60 входящих пакетов, включая пять SYN. Количество
|
||||
соединений не следует трактовать как количество физических трекеров.
|
||||
Удалённый процесс завершён, хеш локальной копии сверён, временные файлы на
|
||||
VPS удалены. Оба USB-наблюдателя завершились. Core остался на порту 8000,
|
||||
сервис VPS работает; итоговое состояние — МТС во втором слоте, 12 В и USB
|
||||
подключены, свежая связь с VPS подтверждена.
|
||||
|
||||
## Значение для автоматизации
|
||||
|
||||
Для испытанной карты доказана необходимая основа: получить ICCID без
|
||||
мобильного интернета, узнать ту же SIM после перестановки и определить слот.
|
||||
Это позволяет проектировать сохранение проверенных настроек по идентичности
|
||||
карты, а не постоянную связь «номер слота → оператор».
|
||||
|
||||
Рабочий автомат переноса настроек, каталог операторов, проверка результата
|
||||
и восстановление после неудачи ещё не реализованы этим опытом. Отдельно
|
||||
нужно подтвердить источник оператора для новой неизвестной SIM и исполнителя
|
||||
настройки: один VPS не может исправить APN через отсутствующий канал связи.
|
||||
См. [план автоматической связи](AUTOMATIC_CONNECTIVITY_DESIGN_20260928.md).
|
||||
@@ -0,0 +1,64 @@
|
||||
# B2 runtime boundary and correlated receipts
|
||||
|
||||
Owner scope, 2026-09-27: the current runtime ends at the tracker. External relays,
|
||||
motors and sensors are out of scope. Their physical feedback must not block work
|
||||
on tracker maintenance. Record the exact B2 acknowledgment and, where the
|
||||
operation changes B2 state, the independently observed tracker state. Never
|
||||
label a TCP acknowledgment as a B2 result.
|
||||
|
||||
The manufacturer's INTERNAL `Packet` specification defines a type-9 reply with
|
||||
a command token and result code: 0 = no error; 1–5 = command/argument/execution
|
||||
errors; 6 = accepted, needs time; 7 = command queue full; 8–9 = downstream device
|
||||
unavailable/no response. Code 6 is intermediate. FC text commands do not inherit
|
||||
the token guarantee of FF binary commands.
|
||||
|
||||
Source: [manufacturer INTERNAL protocol, Packet sheet](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit#gid=13).
|
||||
|
||||
## Host 0.1.31
|
||||
|
||||
Binary replies now correlate by admitted IMEI and exact token through any active
|
||||
monitoring connection of that device, including a newly connected stream. The
|
||||
former same-dispatch-socket condition discarded valid replies published through
|
||||
B2's second monitoring connection. Unknown/closed connections, revoked devices,
|
||||
other trackers, wrong tokens, expired operations and text actions remain excluded.
|
||||
The durable final result cannot be downgraded by a duplicate response. The first
|
||||
intermediate acceptance time survives duplicate ACKs and is projected into Core's
|
||||
history. UI distinguishes acceptance, the final B2 code, and restart reconnection.
|
||||
|
||||
Acceptance session: `command-receipts-09c3a2a404e5491ea3eb66854bc4a86a`.
|
||||
Installer SHA-256:
|
||||
`aededdbd96dd13b6fda9285637e3b8ee7279c8ef3f8be3c22a6e618048628f5f`.
|
||||
|
||||
- Synthetic source checks covered alternate/new/unknown/closed connections,
|
||||
another tracker, wrong token, revoked admission, ACK versus final reply,
|
||||
duplicate replies and persisted results. Core journal tests covered ACK
|
||||
projection, restart and duplicate-event suppression.
|
||||
- Shipped `qualify_receipts.py` ran on Ubuntu with two real loopback TCP streams
|
||||
and synthetic identity: one transmission, code 6 then code 0 through the other
|
||||
stream, duplicate rejection unable to change the final result, result retained
|
||||
after SIGKILL. Shipped runtime and fault qualification also passed.
|
||||
- Frontend architecture, typecheck, all 1009 unit tests and production build
|
||||
passed. Existing bundle-size warning remains. The command window was checked
|
||||
against actual history on the canonical service, including Escape.
|
||||
- Versioned installation preserved four host identity files and backed up SQLite;
|
||||
all 25 manifest files matched. Core download serves the same installer.
|
||||
- Two actual B2 position requests were confirmed, in 2.565 s and 1.054 s.
|
||||
The first was accepted through the other monitoring connection, the second
|
||||
through the sending connection. Core and VPS agreed on both terminal results.
|
||||
No physical configuration, reboot, output or USB serial command was sent.
|
||||
|
||||
## Subsequent runtime work
|
||||
|
||||
The job/attempt recovery below was subsequently implemented and qualified in
|
||||
[Host 0.1.32](DURABLE_MAINTENANCE_20260927.md). The following describes the boundary
|
||||
of 0.1.31 itself.
|
||||
|
||||
### Original 0.1.31 boundary
|
||||
|
||||
This increment fixes receipt loss; it does not implement durable intent recovery
|
||||
after an attempt expires. The owner requires one persisted job with distinct
|
||||
attempts, automatic per-tracker pause/resume, VPS reconciliation before retry,
|
||||
and readback before repeating a state change. Timeout of a transport attempt must
|
||||
not silently discard the accepted job. Invalid commands and configuration
|
||||
conflicts need an explicit terminal result; outages need a recoverable wait.
|
||||
Historical attempts are not silently replayed by this release.
|
||||
@@ -0,0 +1,135 @@
|
||||
# Доставка команд: подтверждения TCP и свежесть соединения
|
||||
|
||||
28.09.2026. Продолжение исследования паузы 334.982 с из
|
||||
[нативного опыта SIM](NATIVE_SIM_EXPERIMENT_20260928.md). Условия владельца:
|
||||
только МегаФон в SIM 1, SIM 2 пустая, непрерывное питание 12 В, USB отключён.
|
||||
Прошивка B2 остаётся 0.01. В этой проверке настройки B2 не записывались.
|
||||
|
||||
## Разделённые наблюдения
|
||||
|
||||
VPS 0.1.40 добавил постоянный журнал `command_transport`. Для каждой фактической
|
||||
отправки стадии сохраняются подготовка, запись в поток, наблюдение TCP ACK либо
|
||||
неподтверждённое закрытие с причиной. В журнале нет тела команды, пароля, адреса
|
||||
модема или идентификаторов SIM. Запись подготовки входит в транзакцию выбора
|
||||
команды до отправки. Подтверждение TCP не завершает команду и не доказывает
|
||||
исполнение прошивкой; ответ B2 и независимое чтение конфигурации учитываются
|
||||
прежним рантаймом отдельно.
|
||||
|
||||
Наблюдение TCP использует существующий Linux watchdog: учтены буферы asyncio
|
||||
и не подтверждённые ядром байты всего префикса потока. Поздние байты не продлевают
|
||||
срок предыдущей команды. Проверка планируется с шагом до 250 мс; сохранённое
|
||||
время — время наблюдения, а не точная отметка ACK на проводе. Из-за этого
|
||||
сохранённая отметка TCP может оказаться позже уже принятого ответа устройства.
|
||||
На платформе без Linux фактический TCP ACK не выводится из пустого буфера.
|
||||
|
||||
API команды, операции и история попыток возвращают отдельное поле `transport`.
|
||||
Поздние отметки доступны также после завершения операции. Журнал не меняет
|
||||
решение о повторе или проверке фактического состояния. После перезапуска VPS
|
||||
незавершённые транспортные записи становятся `unconfirmed / host_restarted`,
|
||||
а не выдуманным подтверждением доставки. Действует прежняя схема: Core опрашивает
|
||||
VPS; входящего соединения VPS → Core нет.
|
||||
|
||||
В 0.1.40 обнаружено окно отмены: закрытие сокета могло отменить отправитель
|
||||
между извлечением наблюдений из буфера и фиксацией. В 0.1.41 запись извлечённой
|
||||
порции защищена от отмены и завершается до регистрации закрытия. Это проверено
|
||||
регрессией с остановленной записью и отменой отправителя, а также восстановлением
|
||||
журнала после перезапуска. Проверки не приписывают исполнение неизвестной команде.
|
||||
|
||||
## Физический опыт на 0.1.40
|
||||
|
||||
Приватная сессия `transport-evidence-1a383db5a5f04e17845ce1fb6c9452d2`.
|
||||
После штатного обновления VPS B2 подключился самостоятельно. Запрос координат
|
||||
`821efc916e2a41a8bfd9e788b3c8b402` оставался одним долговечным намерением:
|
||||
|
||||
- создан в 14:12:35.249 UTC;
|
||||
- первые три попытки не получили ответа B2; у первой транспортная запись
|
||||
осталась промежуточной в окне отмены 0.1.40, у второй и третьей записан
|
||||
`delivery_deadline`;
|
||||
- запись сети непосредственно показывает отсутствие TCP ACK и повторные
|
||||
передачи второй и третьей попыток, несмотря на продолжающуюся телеметрию;
|
||||
- четвёртая отправка в 14:14:40.818 UTC получила код 0 через 1.575 с;
|
||||
- всего от создания до ответа прошло 127.144 с. Это не успешный RTT первых
|
||||
попыток и не четыре отдельных пользовательских запроса.
|
||||
|
||||
Запрос отмены инженерной серии был сделан уже после успешного завершения и
|
||||
вернул `device_confirmed`; он ничего не отменил и новых команд не создал.
|
||||
|
||||
В записи TCP неудачная третья отправка произошла через 19.555 с после последнего
|
||||
входящего содержимого на её соединении; успешная четвёртая — через 4.949 с.
|
||||
Во второй попытке последнее содержимое предшествует началу записи; точный возраст
|
||||
не установлен. Это наблюдение обосновывает проверку свежести, но не доказывает
|
||||
причину всех сетевых разрывов или наличие конкретного таймера прошивки.
|
||||
|
||||
Следующее штатное чтение `f2cb9dd0e80649c2aab7045eec1d63c7` ожидало в той же
|
||||
очереди и после запроса координат прошло с первой попытки:
|
||||
|
||||
| Событие | Значение |
|
||||
| --- | --- |
|
||||
| Отправка `SERV 1.9` | 14:14:44.270 UTC |
|
||||
| TCP ACK в PCAP | через 0.904 с |
|
||||
| Наблюдение TCP ACK в рантайме | через 1.003 с |
|
||||
| Полная конфигурация принята | 14:14:46.757 UTC |
|
||||
| От отправки до чтения | 2.491 с |
|
||||
|
||||
SHA конфигурации остался
|
||||
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`:
|
||||
оба слота разрешены, обе тройки APN/логин/пароль пусты. PCAP содержит 125 TCP
|
||||
пакетов, SHA `f0e2b5fac9672c5685b43c7477f62b3ab7559ade7c21734e2489053ae415ae67`.
|
||||
Содержимое и координаты хранятся только в приватном каталоге опыта.
|
||||
|
||||
## Изменение отправки в 0.1.41
|
||||
|
||||
Пустая очередь сокета сама по себе больше не допускает мониторинговую команду:
|
||||
выбранное соединение должно получить данные устройства не более пяти секунд
|
||||
назад. Такое дополнительное условие уже применялось к конфигурации; теперь оно
|
||||
действует на общий отправитель. Входящий пакет будит очередь без отдельного
|
||||
диагностического запроса. Исходные сроки попыток и долговечное намерение
|
||||
сохраняются. Ожидание свежего канала может быть дольше самого ответа B2.
|
||||
|
||||
Приватная сессия итогового выпуска:
|
||||
`transport-evidence-1e09166b1d3b44df8f6bb9fb74c7fb0c`.
|
||||
Два запроса намеренно созданы после паузы во входящих данных:
|
||||
|
||||
| Запрос | Ожидание отправки | Ответ B2 после отправки | Полное время | Попытки |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| `e286d960b75c4e238d7109a02bade7f7` | 1.716 с | 0.939 с | 2.656 с | 1 |
|
||||
| `4667f69d1a3d4e928379405ccc353dc4` | 17.671 с | 0.869 с | 18.539 с | 1 |
|
||||
|
||||
Оба получили код 0 и отдельное подтверждение TCP. Это два успешных опыта,
|
||||
не статистическая гарантия задержки и не доказательство отсутствия будущих
|
||||
перебоев. Исходная пауза 334.982 с пока не объяснена: её начало не было записано.
|
||||
По опубликованной схеме настроек B2 отдельный регулируемый таймер восстановления
|
||||
модема не найден. Прошивка не модифицировалась ради недоказанной гипотезы.
|
||||
|
||||
Контрольное чтение 0.1.41 `7479afab3e1d4330b2eefcf43a3d9a02`:
|
||||
отправка 14:22:08.951 UTC, полный образ принят в 14:22:12.039 UTC,
|
||||
3.088 с, первая попытка, SHA конфигурации прежний. При этом PCAP показывает
|
||||
повторные TCP-передачи исходного запроса и отсутствие ACK на его соединении.
|
||||
HTTP-образ пришёл отдельным соединением. Рантайм правильно сохранил одновременно
|
||||
`observed` для чтения и `unconfirmed / delivery_deadline` для транспортной
|
||||
записи. Отсутствие TCP ACK **не доказывает недоставку**: команда могла достигнуть
|
||||
устройства без возврата ACK. Самостоятельный ответ по другому каналу — отдельный
|
||||
факт. Нельзя превращать транспортную неопределённость в отрицание уже полученного
|
||||
результата или слепой повтор эффекта. Ретрансляции TCP — также не новые попытки
|
||||
нашего рантайма. Эти различия важны для дальнейших опытов.
|
||||
|
||||
## Поставка и проверка
|
||||
|
||||
Исходный HEAD `fb33a6d45c73e6d458faed586959ba1a12775355`, с существующими рабочими
|
||||
изменениями. Сборщик `scripts/build_vps_host.py`; повторная сборка каждого
|
||||
установщика совпала побайтово. Установка через штатный `.pyz`, перед каждой
|
||||
создана приватная копия SQLite и четырёх файлов идентичности; контрольные суммы
|
||||
этих файлов после установки сохранились. B2 вернулся после обоих обновлений
|
||||
без USB и действий владельца. Установщик 0.1.41 опубликован в Mission Core.
|
||||
|
||||
| Выпуск | SHA-256 установщика |
|
||||
| --- | --- |
|
||||
| 0.1.40 | `6332895b98d0b371ed502cb465a1c3683f6f1483b2190f72e025094c07adb1b4` |
|
||||
| 0.1.41 | `d63b5fd10b4dda32b6aaefa0f57ab4c71d322b2231d0c805922d0500ccd11db8` |
|
||||
|
||||
Фокусные проверки покрывают поздний TCP ACK, префиксы буферов, закрытие/таймаут,
|
||||
неизвестную доставку после перезапуска, отмену во время фиксации, идемпотентный
|
||||
ответ API, историю завершённой операции и запрет отправки в устаревший поток.
|
||||
Прошли также проверки очереди, квитанций, атомарности пакетов, совместимости
|
||||
Core и production-сборка интерфейса. Проверка другой чистой Ubuntu остаётся
|
||||
отложенной по указанию владельца.
|
||||
@@ -0,0 +1,179 @@
|
||||
# Arnavi B2: operator-host USB bootstrap
|
||||
|
||||
Qualified 2026-09-26 on macOS, Artery CDC ACM `2e3c:5740`, B2 model 231,
|
||||
firmware 0.01. The reader is integrated with independent equipment enrollment.
|
||||
A separate writer now applies a saved portable policy with private backup and
|
||||
readback. A VPS gateway and autonomous operation without the manufacturer cloud
|
||||
are not yet accepted.
|
||||
|
||||
## Qualified wire operations
|
||||
|
||||
| Request | Purpose | Expected response |
|
||||
| --- | --- | --- |
|
||||
| `>I 7\r\n` | Read model/device information | Complete `DI`, `DN`, `MN`, `SID0`, `SID1` lines |
|
||||
| `>D 15;0\r\n` | Read configuration | `>SF="<base64>"\r\n` |
|
||||
|
||||
These are application-level reads, although writing the request bytes to a
|
||||
serial port is necessary. Opening a tty also entails normal OS USB control
|
||||
traffic. No baud rate, tty settings, explicit modem line controls, configuration,
|
||||
firmware, relay or CAN state are changed by this reader.
|
||||
|
||||
`DI` carries model, firmware major and minor (optional fourth subtype field).
|
||||
`DN` is the device ID; `MN` is its 15-digit modem IMEI. Model must be 231.
|
||||
The USB serial string and tty path are discovery hints, never device identity.
|
||||
|
||||
The vendor labels `SID0/1` as ICCID. In the initial observation B2 returned **12 digits** for
|
||||
SID0 and `0` for SID1. Store the reported value and length without inventing a
|
||||
prefix or claiming a complete ICCID. `0` means no identifier was reported; it
|
||||
does not prove physical absence of a second SIM. SIM identifiers cannot replace
|
||||
the IMEI in device enrollment.
|
||||
|
||||
A [2026-09-28 slot-swap test](SIM_SLOT_IDENTITY_20260928.md) on the same firmware
|
||||
returned a full 20-digit ICCID through the qualified `I 7` read in both slots,
|
||||
matching the internal modem's `CCID` reply for the same physical MTS SIM.
|
||||
Thus short initial reports are not a universal firmware limit. Keep partial
|
||||
reports distinct from qualified complete identities; this one-card result does
|
||||
not establish all carriers, simultaneous two-SIM association or on-demand IMSI.
|
||||
|
||||
The subsequent [two-card test](DUAL_SIM_IDENTITY_20260928.md) established an
|
||||
important exception: with both cards inserted, each qualified `I 7` read returned
|
||||
12 digits for slot 1 and 20 for slot 2, despite both startup SID reports containing
|
||||
20 digits. This repeated with the cards swapped and on a second read. A 20-digit
|
||||
MegaFon SID also differed from the modem's raw CCID (18 digits followed by `ff`).
|
||||
Never equate a reported SID's length with canonical completeness. Preserve each
|
||||
source separately and reject incomplete/mismatched identity as an automatic-write
|
||||
precondition. The startup stream consistently distinguished both tested cards.
|
||||
|
||||
## Configuration framing
|
||||
|
||||
After JSON-string and base64 decoding:
|
||||
|
||||
```
|
||||
body_length:u16be | crc16:u16be | record ...
|
||||
record = 0x23 | parameter:u8 | value_length:u8 | value[value_length]
|
||||
```
|
||||
|
||||
The observed CRC matches CRC-16/CCITT-FALSE over the body (polynomial 0x1021,
|
||||
initial 0xffff, no reflection, no final xor). Length must match exactly. Reject
|
||||
CRC errors, truncation, duplicate parameter numbers and unsupported record
|
||||
formats. Integers are big endian, unlike some INTERNAL telemetry fields.
|
||||
Strings may be empty, plain ASCII or carry a trailing NUL. B2 0.01 removes
|
||||
a supplied trailing NUL when writing the SIM 2 access strings. The overlay
|
||||
preserves unchanged raw records and emits changed text without a terminator.
|
||||
|
||||
The physical sample had 207 records, a 946-byte body and 950 total bytes. The
|
||||
complete parse and re-encode matched every source byte. Five parameters were
|
||||
absent from the downloaded UI schema, including the manufacturer's configuration
|
||||
host and port. Preserve raw ordered records, including unknown fields; never
|
||||
regenerate the full device configuration from a UI schema and defaults.
|
||||
|
||||
The configuration includes credentials. `Configuration` and `Setting` omit raw
|
||||
values from repr. Public summary uses an explicit allowlist. Raw responses,
|
||||
identity and configuration snapshots go only into a newly created 0700 session
|
||||
directory with 0600 files. Do not commit these artifacts or return them through
|
||||
ordinary product logs/API responses.
|
||||
|
||||
`prepare_server_slot` is an **offline diff builder**, not a write command. It
|
||||
changes only a selected slot's host, port and INTERNAL protocol fields, preserving
|
||||
other records and order. Preparing a buffer does not prove that the server is reachable. The writer
|
||||
below owns hardware mutation; endpoint migration still requires a ready receiver
|
||||
and acceptance of an actual device packet.
|
||||
|
||||
## Reader behavior
|
||||
|
||||
`usb_read.read_snapshot` discovers qualified VID/PID interfaces under the
|
||||
operator Mac's IOService tree. Multiple candidates require explicit selection.
|
||||
It opens the existing tty mode, takes a cooperative OS lease, drains initial
|
||||
diagnostic output for two seconds, then reads identity, settings, and identity
|
||||
again. Both identities and the USB session must agree. Each response has an
|
||||
eight-second deadline and total receive data is bounded to 1 MB. No automatic
|
||||
reconnect, guessed commands, credential attempts or configuration repair runs.
|
||||
|
||||
Failures retain partial evidence with a failed receipt. Credentials are not
|
||||
included in error messages. An incomplete or invalid identity prevents the
|
||||
configuration request. Every descriptor is closed. The lease cannot arbitrate
|
||||
applications that ignore cooperative locking. The Fleet equipment service
|
||||
serializes inspection and writes with a shared lease.
|
||||
|
||||
Development CLI (not an operator installation flow):
|
||||
|
||||
```sh
|
||||
.venv/bin/python -m k1link.device_plugins.arnavi_b2.usb_read --list
|
||||
.venv/bin/python -m k1link.device_plugins.arnavi_b2.usb_read --output-dir /private/tmp/b2-evidence
|
||||
```
|
||||
|
||||
The successful result is `settings_read`, with `provisioned: false`. It is not
|
||||
"connected to Mission Core." There are no new dependencies or cloud calls.
|
||||
The current host profile supports macOS only. The integrated equipment master
|
||||
uses this reader on the local operator host. Packaging a helper for a remote
|
||||
Core remains a separate delivery boundary.
|
||||
|
||||
## Evidence and validation
|
||||
|
||||
The official published `Configurator_251111.exe` was inspected statically only,
|
||||
SHA-256 `f79af698160ce6009c58608ec5511fab1680eea472ba9d689835fb032f2fc6ec`.
|
||||
Relevant PE virtual addresses:
|
||||
|
||||
- SettingsGet registration 0x77b3b6, model interval 5..249, request at 0x77b870.
|
||||
- Model switch 0x78c392 / 0x78c3a7 maps model 231 to the B2 label.
|
||||
- `UpdateTypeInfo` 0x787bcc queues `>I 7` through 0x78aa08.
|
||||
- SF parser starts 0x69bae3; ordered record loop 0x69bb94..0x69c016.
|
||||
- MN to `_DeviceIMEI` mapping 0x6929b7..0x692a59.
|
||||
- SID0 to `_ModemSIMICCID0` mapping 0x692a63..0x692afc.
|
||||
|
||||
Sources: [manufacturer downloads](https://8888.arusnavi.ru/),
|
||||
[public model-231 metadata](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations).
|
||||
The public schema is research evidence, not a runtime dependency or the current
|
||||
configuration of a physical device. Do not execute the Windows configurator
|
||||
from this module or send device identifiers to its web API.
|
||||
|
||||
Synthetic tests cover damaged CRC/length, truncation, duplicate and unknown
|
||||
records, complete-line parsing, wrong model, partial SIM identifier, credential
|
||||
redaction, exact offline changes and USB instance separation. The native module
|
||||
was additionally run against the real device: same IMEI before/after, stable USB
|
||||
session, CRC valid, and configuration hash identical to the independent first
|
||||
read. Private run receipts are held outside the repository.
|
||||
|
||||
## Next integration boundary
|
||||
|
||||
Before applying any server change, prepare the independent gateway profile
|
||||
and deployment, then prove the selected endpoint and actual packet acceptance. Fleet identity must be the device IMEI,
|
||||
with separate vehicle binding and SIM observations. UI enrollment success must
|
||||
depend on reception from this instance by our gateway, not a USB response.
|
||||
The existing manufacturer's startup and periodic configuration checks remain
|
||||
enabled on the qualified unit. Disabling them and proving persistence through
|
||||
restart is a later hardware operation, not a consequence of this read module.
|
||||
|
||||
|
||||
## USB policy write acceptance — 2026-09-26
|
||||
|
||||
`usb_write` sends the statically qualified envelope
|
||||
`<existing six-digit device password>*CONF*<base64 configuration>\r\n`.
|
||||
The official configurator constructs it at 0x777cc0–0x777d12, calls its base64
|
||||
encoder at 0x66fe98, and handles `SR=1` at 0x69b951 before reading settings again.
|
||||
The executable was not run. No firmware, modem-line, relay, reboot or cloud-update
|
||||
command is used. The password is never returned through the API or receipt.
|
||||
|
||||
The transaction brackets the existing snapshot with fresh identity including
|
||||
reported SIM identifiers, rejects another firmware/configuration/USB session,
|
||||
fsyncs a private original and target before transmission, then reads the result.
|
||||
Every unchanged record must remain byte-identical. A confirmed different result
|
||||
on the same device permits one rollback to the saved original. Lost I/O produces
|
||||
an uncertain result with no automatic command retry. The operation and a separate
|
||||
post-operation inspection must both succeed before the UI says applied.
|
||||
|
||||
A nonblocking macOS tty accepted only 1024 bytes in the first write call. The
|
||||
transport now completes the same frame through bounded writable waits, advancing
|
||||
its offset only over accepted bytes; it never retransmits the accepted prefix.
|
||||
Receipts include expected/accepted byte counts. Synthetic cases cover backpressure,
|
||||
partial writes, timeout, missing ACK, I/O loss, stale identity and rollback.
|
||||
The exact console prompt prefix `> ` may precede a response line; arbitrary
|
||||
embedded or incomplete diagnostic fragments remain rejected.
|
||||
|
||||
Real acceptance changed only SIM 2 fields 89, 90 and 91 to the standard MTS
|
||||
access values. The tracker returned `SR=1`; both immediate and independent
|
||||
readback matched the expected configuration exactly. The earlier terminator
|
||||
mismatch exercised and confirmed restoration of the complete original image.
|
||||
The server route and all other records remained unchanged. Persistence after a
|
||||
power cycle, MTS packet delivery, server migration and manufacturer-cloud removal
|
||||
are separate checks, not implied by successful USB configuration.
|
||||
@@ -0,0 +1,120 @@
|
||||
# B2: runtime при нестабильной связи
|
||||
|
||||
Принятый выпуск VPS Host — 0.1.26, 27.09.2026. Один тестовый B2, модель 231,
|
||||
прошивка 0.01, текущая передача через SIM1. Дальнейшие аппаратные испытания
|
||||
проводятся в помещении. Потеря сотовой связи не должна удалять устройство из
|
||||
реестра или превращать неизвестный результат команды в успех.
|
||||
|
||||
## Доставка и восстановление
|
||||
|
||||
1. Core сохраняет намерение и приватное тело исходящего запроса в одной
|
||||
SQLite-транзакции с `synchronous=FULL` до сетевой отправки. ID, получатель,
|
||||
параметры и абсолютный срок действия фиксируются один раз.
|
||||
2. Если результат HTTP неизвестен, Core сначала запрашивает прежнюю операцию
|
||||
на VPS. Пока она не найдена, повторяет тот же запрос с тем же ID и сроком:
|
||||
интервалы 2/4/8/16/30 секунд плюс небольшое постоянное смещение для каждого
|
||||
ID. Рестарт Core не создаёт новую операцию и не продлевает срок действия.
|
||||
3. VPS сохраняет принятую операцию до ответа Core. Повтор ID с тем же телом
|
||||
возвращает имеющуюся запись, с другим телом отклоняется. Когда владение
|
||||
операцией подтверждено VPS, приватное тело из исходящей очереди Core удаляется;
|
||||
состояние операции сохраняется. Просроченный новый запрос фиксируется как
|
||||
`expired` без отправки в B2.
|
||||
4. На VPS для одного B2 допускается одна незавершённая операция. Новый запрос координат
|
||||
может ждать подключения до исходного срока 30 секунд и переживает рестарт
|
||||
VPS, если ни разу не был отправлен. Это ограниченное ожидание, не бесконечная
|
||||
очередь накопленных команд. Серверное ожидание покрывает разрыв между
|
||||
принятием и отправкой. Последующее [окно команд Core](COMMAND_RUNTIME_UI.md)
|
||||
добавляет долговечную FIFO перед VPS, до 32 незавершённых операций на B2.
|
||||
Оно допускает постановку без свежего `online`, но сохраняет короткие сроки
|
||||
и не предназначено для отложенных воздействий после длительного отсутствия связи.
|
||||
5. Воздействия требуют действующего соединения и короткого окна отправки.
|
||||
После зафиксированной отправки они не повторяются автоматически ни при
|
||||
пропаже ответа, ни после рестарта VPS. Фиксация до записи в сокет намеренно
|
||||
допускает неизвестный исход при аварии между этими шагами; гарантировать
|
||||
ровно одно физическое исполнение имеющимся протоколом нельзя.
|
||||
|
||||
Абсолютный срок Core поддерживается с VPS 0.1.26. Для старых версий остаётся
|
||||
опрос прежнего ID без автоматического повтора POST. При отсутствии VPS после
|
||||
истечения срока Core фиксирует неизвестный результат. Устройство продолжает
|
||||
существовать в реестре независимо от наличия свежего GNSS и TCP-соединения.
|
||||
|
||||
| Операция | Срок от намерения Core | Условие отправки |
|
||||
| --- | --- | --- |
|
||||
| Запрос позиции | До 30 с | Может дождаться нового соединения до исходного срока |
|
||||
| Выход/импульс | До 30 с | Действующее исходное соединение, отправка в течение 3 с после принятия VPS |
|
||||
| Restart | До 180 с | Действующее исходное соединение, отправка в течение 3 с; один restart |
|
||||
| Полная конфигурация | До 180 с | Последовательные чтение/запись/проверка; без повторной неопределённой записи |
|
||||
| Выбор SIM | До 360 с | Конфигурация, один restart, подтверждение свежей целевой SIM |
|
||||
|
||||
Срок VPS дополнительно ограничен абсолютным сроком Core, поэтому задержанный
|
||||
HTTP-запрос не начинает полное окно заново. Сетевые очереди Linux ограничены
|
||||
механизмом 0.1.25: неподтверждённая отправка прерывается не позднее выбранного
|
||||
таймера, ограниченного 30 секундами и сроком операции. Планировщик ОС не даёт
|
||||
гарантии жёсткого реального времени. Это не отменяет команду, уже принятую B2.
|
||||
|
||||
`device_confirmed` означает проверенный ответ B2, а не измерение контактов реле.
|
||||
`expired` означает истечение срока неотправленной операции. `unconfirmed` или
|
||||
`uncertain` сохраняют неопределённость уже начатого обмена; интерфейс не должен
|
||||
показывать их как успешное исполнение. Терминальная история переживает рестарт.
|
||||
|
||||
## Что оптимизировано
|
||||
|
||||
- Обработчики пакетов и отправки выбирают только незавершённые команды через
|
||||
индекс по устройству и состоянию. Вся история больше не разбирается при
|
||||
каждом пакете/такте отправителя; история по-прежнему хранится. При создании
|
||||
новой операции остаётся чтение истории конфигурации данного устройства.
|
||||
- Отправитель без активных операций спит до события. Активные многошаговые
|
||||
операции сохраняют ограниченный секундный контроль таймеров. Завершившиеся
|
||||
соединения освобождают собственные события и состояние сессии.
|
||||
- Повторы Core имеют ограниченную частоту и тот же ID; обрыв HTTP не создаёт
|
||||
новые физические воздействия и не оставляет вечное состояние отправки.
|
||||
|
||||
Это не приёмка тысячи устройств. Текущий сервис ограничивает одновременные
|
||||
соединения числом 256; новый runtime не меняет этот предел. Необходимы отдельные
|
||||
измерения на целевом сервере, пределы очередей и процедура масштабирования.
|
||||
На операторском Mac нагрузочные испытания не проводились.
|
||||
|
||||
## Телеметрия и пределы хранения
|
||||
|
||||
Приём телеметрии подтверждается после SQLite FULL commit. Сохраняются исходное
|
||||
время измерения и время приёма: выгрузка старой очереди не выдаётся за свежую
|
||||
позицию. Существующий бюджет журнала 512 МиБ и резерв диска 256 МиБ конечны;
|
||||
при исчерпании запись не подтверждается. Память B2 также конечна. Это не
|
||||
обещание отсутствия потерь при бесконечном обрыве, полном диске или гибели носителя.
|
||||
|
||||
Текущий выбор SIM1 исключительный: передача на втором слоте запрещена прежней
|
||||
настройкой. Автоматический резерв SIM этим выпуском не добавлен. Работа команды
|
||||
зависит от мобильной связи, получение новой позиции — ещё и от GNSS.
|
||||
|
||||
## Проверки и воспроизводимость
|
||||
|
||||
204 целевых backend-теста прошли, включая потерянный запрос/ответ, восстановление
|
||||
Core/VPS, неизменность ID/срока, срок неотправленной команды и отсутствие повтора
|
||||
отправленного воздействия. Также прошли Ruff, архитектура UI, TypeScript,
|
||||
1004 frontend-теста и production build. Предупреждения: существующие deprecation
|
||||
Starlette/httpx и размер JS bundle; новых ошибок не обнаружено.
|
||||
|
||||
В поставляемом `qualify_runtime.py` на VPS проверены временная изолированная
|
||||
база, восстановление чтения, дедупликация, истечение срока, отсутствие повторного
|
||||
воздействия, использование индекса и пробуждение спящего отправителя. Реальный
|
||||
трекер этим скриптом не использовался. Время — 1,144 с, это проверка поведения,
|
||||
не нагрузочный тест. Установка выполнена штатным `.pyz`, четыре файла
|
||||
идентичности/ключей сохранены, предыдущая версия и копия состояния сохранены.
|
||||
|
||||
Повторные сборки совпали побайтово. SHA-256 установщика:
|
||||
`2433f50ea14b7459f59a8fe1191ff0cb7a197e201b4e7230b651915b43661a50`.
|
||||
Этот же файл опубликован и проверен скачиванием из Core. Node 0.8.45-1 не
|
||||
обновлялся. Core работает на единственном порту 8000; очередь исходящих
|
||||
неподтверждённых HTTP-запросов после приёмки пуста.
|
||||
|
||||
[Аппаратное сравнение](INDOOR_OUTDOOR_COMPARISON_20260927.md): после возврата в
|
||||
помещение на 0.1.25 подтверждены 5/5 запросов, на 0.1.26 — 3/3. Каждый из
|
||||
последних запросов повторён на входе Core без создания новой операции; PCAP
|
||||
проверяет один прикладной кадр и ответ с правильными CRC/токеном/кодом 0.
|
||||
USB serial, настройки, выходы и restart трекера в этих сериях не использовались.
|
||||
Долговременные обрывы физического радиоканала и отказ диска не квалифицированы.
|
||||
|
||||
Следующий этап: в помещении отдельно воспроизвести длительный разрыв связи
|
||||
и возвращение B2, затем смену SIM/конфигурации с независимым чтением результата.
|
||||
Не накапливать просроченные воздействия и не превращать потерянный ответ в
|
||||
автоматический повтор. Масштабирование требует отдельной приёмки сервера.
|
||||
@@ -0,0 +1,84 @@
|
||||
# ARNavi implementation closeout — 2026-09-28
|
||||
|
||||
This checkpoint preserves the implemented B2/Core/VPS chain and its research
|
||||
history. No tracker command, firmware update, onboard installation or VPS
|
||||
deployment was required for this closeout. Canonical Core remains on port 8000.
|
||||
|
||||
## Transfer documents and Ops cards
|
||||
|
||||
- [ARNavi VPS сервер — MISSIONCOR-86](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-86):
|
||||
18 structured blocks including architecture, installer, trust, API, storage,
|
||||
command runtime, recovery, qualification and explicit remaining checks.
|
||||
[Repository handoff](ARNAVI_VPS_SERVER_20260928.md).
|
||||
- [ARNavi B2 трекер — MISSIONCOR-78](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-78):
|
||||
23 structured blocks including enrollment, configuration codec, profiles,
|
||||
multi-SIM identity/access, native internet, hot swaps, commands, firmware,
|
||||
evidence and remaining checks. [Repository handoff](ARNAVI_B2_TRACKER_20260928.md).
|
||||
|
||||
The existing B2 card was reused. Its complete September 10 research/plan was
|
||||
preserved in two dated historical comments before replacing the main blocks.
|
||||
The old ROBOT2B-7 VPS card is linked as historical infrastructure and was not
|
||||
deleted or overwritten. The new cards contain the full technical text, not just
|
||||
links to local files. Both remain In Progress because their explicit hardware,
|
||||
firmware, clean-host and scale gates are not all complete.
|
||||
|
||||
Structured-block readback matched the submitted text. Card links use the
|
||||
canonical `/nodedc/browse/…` routes. Card content points to immutable source
|
||||
snapshot `21f46ac38ad6268874b15c898b6b8b7fa6f19493`.
|
||||
|
||||
## Semantic source commits
|
||||
|
||||
| Commit | Scope |
|
||||
| --- | --- |
|
||||
| `b6efae3272d794c29e5f7669e757d7ac35e86817` | B2 protocols, USB provisioning, portable profiles and SIM evidence |
|
||||
| `d684eb7e05b6c3b4b9ca1e56c8239186db398f83` | Standalone VPS, durable runtime, reproducible installer and recovery |
|
||||
| `f3a7592d909739fe98a73c50af601b35681112ea` | Fleet/Core pairing, state, APIs, firmware archive and integration regressions |
|
||||
| `031e01a99b958095953693f35fb3f7df848f438d` | Independent equipment UI, SIM policy, commands and firmware section |
|
||||
| `67ae1f4d77a90fcc388d6529cb9ff70833c48106` | Independent tracker positions and map-layer recovery |
|
||||
| `21f46ac38ad6268874b15c898b6b8b7fa6f19493` | Current handoffs and versioned qualification/research reports |
|
||||
|
||||
Design Guideline dependency:
|
||||
`1b63366d2e7a911e18a293d30cddb0c95e0ba653` — terminal icon and trailing
|
||||
WindowFooterActions, including registry, documentation and catalog.
|
||||
Frontend uses sibling file dependencies; retain both repository revisions.
|
||||
This receipt is a final documentation commit after the implementation series.
|
||||
|
||||
## Verification at closeout
|
||||
|
||||
- 427 focused Python tests covering B2 codecs, USB, SIM, equipment, installers,
|
||||
VPS transport/receipts, durable operations and portable state passed.
|
||||
- 10 frontend-assets/plugin-boundary Python tests passed.
|
||||
- All 1016 Control Station unit tests passed, including the 32 ARNavi tests.
|
||||
- Control Station TypeScript passed. Changed ARNavi/VPS modules, scripts and
|
||||
tests passed Ruff. One late-binding callback in a watchdog test was corrected;
|
||||
all 139 cases in that file were rerun successfully (already part of the 427).
|
||||
- Design Guideline registry validation, icon contract and catalog typecheck passed.
|
||||
- Two fresh 0.1.41 builds matched the previously accepted installer exactly:
|
||||
`d63b5fd10b4dda32b6aaefa0f57ab4c71d322b2231d0c805922d0500ccd11db8`.
|
||||
Manifest: `86d8831179ff1332297ae31a12d91086c75b401d04515301c75c87ffb31edbff`.
|
||||
- `git diff --check` passed. New source/evidence summaries were inspected for
|
||||
private material. Binary firmware, live configuration, captures, databases,
|
||||
installer binaries and credentials remain outside Git in private/ignored state.
|
||||
- Core `/api/health` returned operational/ok; equipment and VPS telemetry APIs
|
||||
returned HTTP 200. Port 8000 remained the canonical listener; 8765 had none.
|
||||
|
||||
Starlette/httpx deprecation remains an existing warning. No new frontend
|
||||
production build was needed after this documentation/test-only closeout; the
|
||||
preceding native-policy build and physical UI acceptance remain the relevant
|
||||
build/hardware evidence. Other-VM clean installation is still deferred as
|
||||
requested by the owner; it is not newly claimed from synthetic tests.
|
||||
|
||||
## Git access and retained state
|
||||
|
||||
Git/Ops used the previously authorized exact-host VPN bypass. The destination
|
||||
and current Wi-Fi gateway were rechecked. A stale source-address selection
|
||||
caused local EADDRNOTAVAIL; explicitly binding the current Wi-Fi address proved
|
||||
the server reachable. The existing route was updated through the normal macOS
|
||||
administrator prompt, preserving VPN/Tailscale and default routes. Authenticated
|
||||
Git and direct Ops MCP then worked. No persistent VPN helper was installed.
|
||||
|
||||
Private evidence and runtime state are intentionally ignored, not removed to
|
||||
make a clean tree. No cleanup of unrelated worktrees, no history rewrite, no
|
||||
force push and no replacement of the existing operator services is part of
|
||||
this checkpoint. Read the two handoffs for the current functional limits;
|
||||
this closeout does not mark those remaining gates complete.
|
||||
@@ -0,0 +1,481 @@
|
||||
# ARNavi B2 трекер — руководство передачи реализации
|
||||
|
||||
Актуальный срез: 28.09.2026. Принятая аппаратная комбинация: **B2, model 231,
|
||||
firmware 0.01**, собственный VPS Host **0.1.41**, Mission Core на 8000.
|
||||
Парный документ: [ARNavi VPS сервер](ARNAVI_VPS_SERVER_20260928.md).
|
||||
Это руководство текущей реализации; датированные исследования сохраняют
|
||||
историю и не заменяют текущую матрицу возможностей.
|
||||
|
||||
## 01 · Результат и модель устройства
|
||||
|
||||
B2 — самостоятельный GNSS/GSM трекер с прошивкой, настройками, архивом измерений
|
||||
и логикой модема. Это не прозрачный USB-шлюз. Он сам измеряет положение,
|
||||
формирует точки по конфигурации, буферизует и отправляет их. После восстановления
|
||||
сети может выгружать старые измерения. GNSS и мобильный канал независимы:
|
||||
можно получать команды без нового спутникового fix и иметь fix без выхода к VPS.
|
||||
|
||||
Реализованы собственное первичное подключение по USB на Mac, переносимые
|
||||
профили, привязка к аппарату, телеметрия/карта при выключенном БК, чтение и
|
||||
поддержанная запись настроек через VPS, команды и журнал с восстановлением,
|
||||
наблюдения двух SIM, несколько режимов интернета, архив файлов прошивки.
|
||||
Рабочий контур не требует кабинетов ARNavi/Gelios. Исследовательские обращения
|
||||
к производителю были отдельными опытами, не runtime dependency.
|
||||
|
||||
У всех сетевых записей/команд firmware gate **231 / 0.01**. Другой B2 или версия
|
||||
не получает совместимость по внешнему сходству. Новую прошивку сначала
|
||||
квалифицировать; простое расширение allowlist не является приёмкой.
|
||||
|
||||
## 02 · Оборудование, профили и привязки
|
||||
|
||||
В аппарате → Оборудование верхний плюс открывает одну форму «Подключить
|
||||
независимое устройство»: БК, ARNavi B2, VPS Host ARNavi. B2 — отдельный root,
|
||||
а не дочернее устройство БК. Один ровер может иметь несколько B2; один VPS
|
||||
обслуживает несколько роверов. Выключенный БК не блокирует B2→VPS→Core.
|
||||
|
||||
Идентичность физического трекера — model + IMEI; USB tty, оператор, телефон,
|
||||
SIM-слот и имя ровера не являются этой идентичностью. Numeric device ID хранится
|
||||
отдельно и считывается, а не вычисляется из IMEI. Название — изменяемая метка.
|
||||
`vehicle_id` — изменяемая привязка к аппарату. Перенос через настройки меняет
|
||||
привязку, сохраняя экземпляр и его историю; во время pending-операции конфликтующие
|
||||
правки блокируются. Запись использует `expected_revision`.
|
||||
|
||||
Профиль — шаблон `schema_version=1`: endpoint, connectivity, scalar parameters.
|
||||
Он не содержит IMEI, ICCID/SID/IMSI, телефон, пароль устройства, private SIM
|
||||
credentials, экземпляр, историю и rover binding. «Сохранить профиль» создаёт
|
||||
шаблон; не отправляет его устройству или всему парку. Новый B2 получает свой
|
||||
прочитанный образ, поверх которого накладывается шаблон. Копировать целиком
|
||||
конфигурацию первого устройства во второе запрещено моделью реализации.
|
||||
|
||||
## 03 · Карта модулей
|
||||
|
||||
| Путь | Ответственность |
|
||||
| --- | --- |
|
||||
| `src/k1link/device_plugins/arnavi_b2/usb_protocol.py` | identity/config codec, CRC/TLV, точечный overlay |
|
||||
| `usb_read.py`, `usb_write.py`, `enrollment.py` | Mac USB discovery, bounded read/write, private evidence |
|
||||
| `profiles.py`, `connectivity.py` | модель переносимых настроек и versioned APN-кандидаты |
|
||||
| `internal.py`, `cellular.py`, `web_protocol.py` | INTERNAL, GNSS/DS2, HTTP settings framing |
|
||||
| `sim_identity.py`, `sim_observation_store.py` | пассивная модемная identity, история и private card access |
|
||||
| `sim_network.py`, `sim_access.py` | сетевой SID, свежая привязка, resolve параметров карты |
|
||||
| `configuration_audit.py`, `firmware.py` | coverage без значений секретов, каталог известных файлов |
|
||||
| `src/k1link/fleet/independent_equipment.py`, `equipment_bootstrap.py` | registry/profile/enrollment и admission до USB apply |
|
||||
| `equipment_network.py`, `equipment_configuration.py`, `equipment_connectivity.py` | desired/observed, подготовка сетевой операции и подтверждённый доступ SIM |
|
||||
| `equipment_command_{catalog,journal,runtime,reconciliation}.py`, `equipment_outbox.py`, `equipment_operations.py` | команды UI, очередь, outbox, VPS reconcile |
|
||||
| `equipment_firmware.py`, `src/k1link/web/*equipment*api.py` | private archive и локальные API |
|
||||
| `apps/control-station/src/core/fleet/{equipment,cellular,commandRuntime,firmware,vps}.ts` | контракты и чистые проекции |
|
||||
| `apps/control-station/src/workspaces/fleet/equipment/` | master, settings, SIM cards, commands/attempts, firmware, VPS UI |
|
||||
|
||||
Общие визуальные компоненты берутся из Design Guideline. Одобренный `terminal`
|
||||
(`>_`) сначала добавлен туда вместе с registry/docs/catalog, затем использован
|
||||
для команды B2. Footer actions справа — общий `WindowFooterActions`, а не
|
||||
локальный CSS. Дополнительный общий блок «Текущие данные» удалён: факты SIM
|
||||
живут в SIM1/SIM2; ниже настройки интернета, затем сервер мониторинга.
|
||||
|
||||
## 04 · Воспроизведение первичного подключения
|
||||
|
||||
1. Установить и добавить VPS по парному руководству. Убедиться в доступности
|
||||
9922/19443 из нужной сети; связать VPS с целевым аппаратом.
|
||||
2. Подключить B2 к Mac с Core по исправному USB. Рабочая SIM и питание нужны
|
||||
для дальнейшей мобильной приёмки. USB-читатель квалифицирован на macOS;
|
||||
прямое подключение через произвольный удалённый browser/Ubuntu helper не заявлено.
|
||||
3. Верхний плюс → ARNavi B2 → имя, аппарат, необязательный профиль → чтение
|
||||
подключённого устройства. Читатель проверяет model/identity, образ, CRC.
|
||||
4. Добавить конкретный candidate; проверить выбранный VPS как server 1.
|
||||
Bootstrap сначала синхронизирует admission IMEI/ID на доступный хост,
|
||||
проверяет принятую версию/свежесть, только затем разрешает USB-запись.
|
||||
5. Запись сохраняет private original/target и проверяет отдельным чтением.
|
||||
Начальная конфигурация направляет primary и recovery monitoring и web
|
||||
configuration endpoint на собственный VPS. Неизменяемые/чужие поля сохраняются;
|
||||
серверы 3/4 не очищаются произвольно. На принятом стенде они отключены.
|
||||
Bootstrap снимает только startup-check bit0 поля72: периодический опрос
|
||||
поля62 сохраняется. Значение0 поля62 как способ отключения не квалифицировано.
|
||||
6. Получить **новый реальный пакет** на VPS после настройки. USB success не равен
|
||||
cellular online, а online не равен GNSS fix. Проверить свежий timestamp/позицию
|
||||
в Центре наблюдения. Дальнейшие настройки выполняются по сети.
|
||||
|
||||
Составной путь покрыт тестами и опытами имеющегося устройства. Полная новая
|
||||
регистрация заводского пустого B2 на чистом контуре другим разработчиком ещё
|
||||
не пройдена. Повреждённый прежний USB-кабель — известное ограничение стенда;
|
||||
отказы USB нельзя автоматически приписывать runtime или прошивке.
|
||||
|
||||
## 05 · USB и точный формат конфигурации
|
||||
|
||||
Квалифицированный VID:PID **2e3c:5740**, Artery CDC ACM. Чтения:
|
||||
`>I 7\r\n` — DI/DN/MN/SID0/SID1; `>D 15;0\r\n` — `>SF="<base64>"\r\n`.
|
||||
DI содержит модель/версию, DN numeric ID, MN IMEI. SID — отчёт прошивки, не
|
||||
автоматически канонический ICCID. После JSON-string/base64 decode:
|
||||
|
||||
```text
|
||||
body_length:u16be | crc16:u16be | records
|
||||
record = 0x23 | parameter:u8 | value_length:u8 | value
|
||||
CRC-16/CCITT-FALSE(body): poly 0x1021, init 0xffff, no reflection/xorout
|
||||
```
|
||||
|
||||
Проверяются точная длина/CRC, отсутствие дублирующихся field IDs, структура и
|
||||
целостность записей. Integer config values big-endian; не переносить endian
|
||||
INTERNAL в TLV. Неизвестные поля и исходный порядок сохраняются побайтово.
|
||||
Не генерировать полный образ из публичного UI schema/defaults производителя:
|
||||
на 0.01 часть новых полей отсутствует, часть реальных полей в UI schema не описана.
|
||||
|
||||
Reader: cooperative OS lease, 2 с пассивного drain, identity → config → identity;
|
||||
совпадение устройства/USB session, 8 с на response, общий buffer ≤1 MB. Не
|
||||
меняет baud/line control и не переподключается/чинит устройство автоматически.
|
||||
Engineering `--observe-seconds` 2..180 расширяет только пассивное окно.
|
||||
|
||||
Write: `<existing six-digit password>*CONF*<base64>\r\n`; пароль из field 5.
|
||||
До отправки fsync original/target, проверка predecessor/identity/firmware/session;
|
||||
после `SR=1` — readback, затем отдельное контрольное чтение. Частичный serial
|
||||
write продвигает offset принятого префикса, не отправляет префикс снова.
|
||||
Потеря I/O → uncertain без слепого повтора. Подтверждённый другой результат
|
||||
на том же устройстве допускает один rollback сохранённого original.
|
||||
|
||||
Raw snapshots хранят credentials: каталоги 0700, файлы 0600, repr/log/API
|
||||
редактированы. В Git/Ops допускаются hashes, структуры, synthetic fixtures,
|
||||
но не реальные образы, телефоны, идентификаторы SIM или приватные пароли.
|
||||
|
||||
## 06 · Параметры и переносимые профили
|
||||
|
||||
В `profiles.py` 86 описаний scalar-параметров; в образе стенда присутствуют
|
||||
78 с принятой шириной. Это покрытие codec/editor, не 78 отдельных аппаратных
|
||||
write-tests. Основные группы: траектория, роуминг, движение, разгон, торможение,
|
||||
угловое/вертикальное ускорение, превышение скорости. Поля навигации 241..248
|
||||
на этой версии отсутствуют — их нельзя дорисовывать как нули.
|
||||
|
||||
`Policy` запрещает лишние поля; strict int, диапазоны/width, согласованность
|
||||
min/max. `portable()` извлекает только совместимые значения. `prepare()` —
|
||||
чистый offline overlay, не аппаратная запись. Отсутствующее нужное поле
|
||||
отклоняет весь target, неизвестные записи остаются прежними.
|
||||
|
||||
Server slots: 1 → fields 1/2/9; 2 → 3/4/8; 3 → 111/112/7; 4 → 113/114/6
|
||||
(host/port/protocol). INTERNAL protocol=0. Отдельные настройки доступа:
|
||||
SIM1 **67/68/69**, SIM2 **89/90/91** (APN/login/password). Field **72**, bits
|
||||
**10/20** запрещают GPRS соответствующего слота; остальные биты сохраняются.
|
||||
Field **70/71** — configuration host/port; **62** — период обращения.
|
||||
|
||||
Сохранённые настройки Core — desired intent. Фактическое прочитанное состояние,
|
||||
подготовленный target, запись и подтверждённый результат хранятся отдельно.
|
||||
Надпись «Сохранено в Core» не означает «B2 применил». При сохранении с действием
|
||||
создаётся job; окно остаётся открытым, показывает стадию/ожидание и результат,
|
||||
а не закрывается на HTTP 200. Сохранение без изменений не создаёт новый restart.
|
||||
|
||||
## 07 · Сетевая настройка через собственный VPS
|
||||
|
||||
`apply-network` передаёт проверенный intent; `inspect-network` читает полный
|
||||
образ. Длительная операция проходит fresh preflight, exact expected SHA,
|
||||
проверку recovery fields, один образ в попытке, независимый readback. Между
|
||||
полными HTTP-обменами пауза 15 с. В конце plain configure требует образ target,
|
||||
а select-sim дополнительно restart и свежий GPRS через новое соединение.
|
||||
|
||||
Потеря ответа не превращается в немедленное повторение write. Durable job после
|
||||
возврата читает устройство: target → подтвердить, predecessor → допустимая новая
|
||||
попытка, другой образ → конфликт. Восстановление знает историю попыток, а не
|
||||
создаёт новый job ID при каждом poll. Уже подтверждённый переход не требует
|
||||
ещё одного restart. Подробный runtime-контракт находится в парной карточке VPS.
|
||||
|
||||
HTTP B2 envelope: request `5b 01 LEN:u16be IMEI:u64le 0001e7020000 OP payload 5d`,
|
||||
LEN=request size−5. Reply `5b LEN:u16be 00 OP payload 5d`, LEN=reply size−4.
|
||||
Приняты op1 numeric ID, op2 download, op5 upload, op6/payload02 identify и op7
|
||||
Unix time. Для каждого проверяются форма/metadata/размер; неизвестное закрыто.
|
||||
`SERV*1.9` инициирует upload, `SERV*1.8` download. Не пытаться вложить полный
|
||||
CONF в ограниченный FC frame или маппить TLV IDs прямо в SETP.
|
||||
|
||||
Ранний endpoint-only GETP/SETP остаётся legacy contract. Текущая обычная работа
|
||||
использует полный образ; нет зависимости от кабинета производителя. Не переносить
|
||||
утверждения «удалённо только server1» из отчёта 0.1.6 на 0.1.41.
|
||||
|
||||
## 08 · SIM: наблюдение, оператор, карта и слот
|
||||
|
||||
Четыре разные сущности: физический слот; сама карта; обслуживающая сеть;
|
||||
параметры доступа APN. Они не заменяют друг друга. Тариф/MVNO/пароль нельзя
|
||||
вычислить из названия сети. На принятом B2 для GPRS выбран один слот;
|
||||
регистрация обеих SIM не означает два одновременно работающих интернет-канала.
|
||||
|
||||
DS2 сообщает выбранную SIM, состояние модема, регистрацию и сигнал по слотам.
|
||||
Типы/коды декодируются в `cellular.py`, неизвестное остаётся unknown. Название
|
||||
сети строится по валидному MCC+MNC. **250-00 не объявляется МТС**, MNC=1 без
|
||||
валидного MCC тоже недостаточен. APN `internet.mts.ru`, пользовательский номер
|
||||
или вчерашняя подпись не служат доказательством текущего оператора.
|
||||
|
||||
UI различает свежие, устаревшие, historical и invalidated наблюдения. Индикатор
|
||||
«используется для интернета» требует актуальных данных модема. Ошибка опроса
|
||||
не удаляет историю и не выдаёт её за новый факт. Возраст измерения важнее
|
||||
времени прихода пакета. По снятию/поиску/новой регистрации прежняя привязка
|
||||
инвалидируется; задержанный старый пакет не должен её воскрешать.
|
||||
|
||||
State 0 означает **B2 не обнаружил карту**, а не доказанную физическую пустоту:
|
||||
вставленная неактивная SIM иногда не сообщается, пока прошивка не попробует
|
||||
перейти на неё. Поэтому интерфейс не может обещать немедленное обнаружение
|
||||
вставки и не должен добавлять фиктивную SIM для красоты списка.
|
||||
|
||||
## 09 · Доказанная идентичность SIM
|
||||
|
||||
USB `I 7` на том же стенде давал 12 цифр для одного SID и 20 для другого;
|
||||
полный 20-значный SID мог отличаться от сырого modem CCID. Длина и название
|
||||
поля производителя не доказывают канонический ICCID. `0` — not_reported,
|
||||
короткий SID — incomplete, длинный — unverified, пока нет отдельного evidence.
|
||||
|
||||
Пассивный USB decoder принимает непрерывную последовательность собственной
|
||||
работы прошивки: `AT+CCID → ответ → OK → SIDn → AT+CIMI → ответ → OK → HCn`.
|
||||
Наш reader не посылает эти AT-команды. Slot должен совпадать, код IMSI
|
||||
согласовываться; ошибки/другие команды/обрыв не склеиваются по близости времени.
|
||||
Сырой CCID, SID, IMSI сохраняются раздельно; CCID формы 18 цифр+`ff` не
|
||||
«исправляется» до выдуманного ICCID.
|
||||
|
||||
Точная пара raw CCID+IMSI даёт стабильную случайную `card_ref` внутри трекера.
|
||||
Slot в неё не входит. Неоднозначная пара/один SID у двух карт блокирует текущую
|
||||
привязку. Журнал private
|
||||
`independent-equipment/evidence/sim-identity/observations.sqlite3`, FULL commit,
|
||||
0700/0600. USB session не объявляется boot session. Прошлые чтения сохраняются
|
||||
как `historical=true`, `current_slot_binding=false`.
|
||||
|
||||
Сетевой источник — пары INTERNAL tags **253/254 (SIM1)** и **202/203 (SIM2)**
|
||||
в одном валидированном packet. Каждая часть u32le <10^9; SID формируется
|
||||
`89` + две 9-значные части. Нулевая пара — not_reported, missing/conflicting
|
||||
пара — unresolved. Не склеивать halves из разных пакетов. Сетевой SID связывается
|
||||
с ранее доказанным USB SID↔CCID/IMSI, сам по себе не даёт IMSI или тариф.
|
||||
|
||||
Binding требует свежую регистрацию status 1/5, отсутствие invalidation/ambiguity,
|
||||
незадержанную исходную запись и окно свежести 90 с для текущего статуса.
|
||||
Исторический startup SID может оставаться binding только пока непрерывное
|
||||
состояние это допускает. После hot removal/search новое SID-свидетельство
|
||||
нужно заново; обычные пакеты B2 могут его не повторять.
|
||||
|
||||
## 10 · Интернет: действующие режимы
|
||||
|
||||
| UI/strategy | Что записывается | Что это не обещает |
|
||||
| --- | --- | --- |
|
||||
| `preserve` | Ничего в доступе SIM | Не включает резерв/автоподбор |
|
||||
| «Обе SIM — сохранить APN», `both` | Очистить только bits10/20 field72 | Не меняет специальные APN, не задаёт приоритет |
|
||||
| «Обе SIM — без заданного APN», `native` | Очистить оба access triples 67..69/89..91 и bits10/20 | Не универсальная поддержка любого тарифа |
|
||||
| «Только SIM N», `sim`+activate | Разрешить N, запретить GPRS другого слота | **Исключительный режим**, не предпочтение с резервом |
|
||||
| `sim`+automatic | Подбор для доказанной карты, затем guarded write/readback/GPRS | Не узнаёт произвольную новую SIM без identity |
|
||||
| Legacy `manual`/`operator` | Явный APN/стандартная тройка по выбранному слоту | Не автоидентификация оператора |
|
||||
|
||||
`native` включается только явным выбором или применением такого профиля.
|
||||
Неизвестный оператор, пустая telemetry и чтение устройства сами по себе
|
||||
не очищают credentials. Старый `both` не мигрируется в native, корпоративный
|
||||
APN не затирается неявно. Удаление credentials — намеренная часть native.
|
||||
|
||||
На сохранение native: явный выбор/изменение access или запретов создаёт
|
||||
`select-sim` с `sim_policy=both`. Требуются чтение, при необходимости запись,
|
||||
readback, restart и свежий GPRS любого слота. Для этого общего намерения не
|
||||
нужна устаревшая card identity. Unrelated edit при уже совпавших native fields
|
||||
не запускает SIM restart. Повтор «Сохранить» без изменений — no-op.
|
||||
|
||||
## 11 · Автоподбор APN: реализованное и незавершённое
|
||||
|
||||
Для `sim`+automatic `sim_access.resolve()` сначала проверяет актуальный network
|
||||
SID binding, затем соответствие ранее квалифицированной карте. Источник
|
||||
параметров: уже проверенная private access-тройка `card_ref`, иначе versioned
|
||||
кандидат по подтверждённой домашней сети. Сейчас каталог обычных тарифов:
|
||||
**25001 → `ru-mts-public-v1`**, **25002 → `ru-megafon-public-v1`**.
|
||||
Публичный кандидат не равен подтверждённо рабочему тарифу.
|
||||
|
||||
В запрос VPS включается `sim_guard {slot,sid}`. Перед выдачей образа guard
|
||||
проверяется; смена/неизвестность карты не допускает запись её предшественнику.
|
||||
После full readback и нового свежего GPRS выбранного слота access сохраняется
|
||||
как проверенный для карты, не навечно для номера слота. Полные identifiers и
|
||||
логин/пароль не появляются в portable profile. Resolve состояния:
|
||||
waiting_identity, unknown_card, unsupported_operator, ready.
|
||||
|
||||
Это не универсальный offline bootstrap. Пока у трекера нет ни одного рабочего
|
||||
канала, Core/VPS не может доставить по нему новый APN. Корпоративные и частные
|
||||
тарифы требуют их реальных параметров; расширение каталога/редактор операторов,
|
||||
Beeline/T2/MVNO не реализованы и не приняты. Проверенный native-режим снимает
|
||||
ручную APN-привязку для двух конкретных обычных SIM, но не доказывает наличие
|
||||
в прошивке универсальной базы операторов или её обновление через наш сервис.
|
||||
|
||||
## 12 · Матрица горячей замены без отключения питания
|
||||
|
||||
Условия последних опытов: 12 В постоянно, USB отключён, штатная 0.01, оба
|
||||
GPRS разрешены, оба APN/login/password пусты. Использованы только имеющиеся
|
||||
МТС и МегаФон, не весь рынок операторов. При физическом извлечении активной
|
||||
карты сервер не отправлял select/restart: переход выполняла прошивка.
|
||||
|
||||
| Проверенный канал после перехода | Разрыв между свежими пакетами | Контроль команды |
|
||||
| --- | ---: | --- |
|
||||
| МТС, SIM2 | 59.235 с | Position reply 1.178 с |
|
||||
| МегаФон, SIM1 | 44.108 с | Position reply 3.703 с |
|
||||
| МТС, SIM1 | 59.861 с | Total 9.262 с: queue 7.421, reply 1.842 |
|
||||
| МегаФон, SIM2 | 44.799 с | Total 10.583 с: queue 9.656, reply 0.927 |
|
||||
|
||||
Это **packet gaps**, не секундомер от точного физического извлечения. Нельзя
|
||||
объявлять их гарантированным таймером переключения, p95 или временем регистрации.
|
||||
Во всех четырёх комбинациях получены свежие пакеты и ответы; чтения последней
|
||||
матрицы сохранили 207-record образ SHA
|
||||
`624d6b44636c196079c0845d96369d74c90ca4736a75c4729c8f44482e99e383`.
|
||||
|
||||
Проверены также исчезновение всех SIM, ожидание канала runtime и возвращение
|
||||
пакетов/запроса после установки рабочей карты. Возвращение ранее вынутой
|
||||
резервной SIM при работающей другой может долго не появляться в DS2. Полное
|
||||
новое SID после hot swap не гарантировано. Поэтому восстановление GPRS и
|
||||
актуальная identity обоих слотов — разные результаты.
|
||||
|
||||
Желаемый сценарий владельца «оба разрешены, вручную предпочесть один, при
|
||||
его исчезновении перейти на другой, сохранить предпочтение при добавлении»
|
||||
**целиком не реализован**. Документированная и принятая команда предпочтения
|
||||
без запрета другого GPRS не найдена. Наш exclusive UI не выдаётся за такую
|
||||
команду. Cold boot default SIM1 после замены обеих карт также не квалифицирован.
|
||||
|
||||
## 13 · Последняя приёмка native через интерфейс
|
||||
|
||||
На уже настроенном native-образе выбран новый режим UI и нажато «Сохранить».
|
||||
Одна операция, одна попытка: VPS принял 15:09:18.307 UTC, прочёл совпадающий
|
||||
образ 15:09:21.122, отправил restart 15:09:21.134, получил новый свежий GPRS
|
||||
SIM2 15:10:08.837. **47.703 с** от restart до проверки; **50.530 с** total.
|
||||
Исход `sim_selected`, `unchanged=true`. Окно осталось открытым и разблокировалось
|
||||
после результата. Следующий снимок дал свежую позицию.
|
||||
|
||||
Это приёмка UI→job→read→restart→return, а не новая очистка образа: поля уже
|
||||
совпадали. Очистка проверена предыдущими опытами. Создан шаблон
|
||||
**«ARNavi B2 — обе SIM, без APN»**; API подтвердил отсутствие SIM identity
|
||||
в нём. Повтор сохранения без правок оставил прежний operation ID и не отправил
|
||||
restart. На окончание этой серии только МегаФон в SIM2, SIM1 пуст; это
|
||||
последний зафиксированный стендовый срез, не постоянная конфигурация продукта.
|
||||
|
||||
## 14 · Команды и уровни подтверждения
|
||||
|
||||
В root-строке B2 кнопка `>_` открывает отдельное окно команд и истории.
|
||||
Человекочитаемый preset показывает принятую firmware, обезличенное тело,
|
||||
encoding, способ подтверждения. Произвольного пользовательского raw command
|
||||
или shell нет. Preset недоступен, если модель/прошивка/режим выхода не приняты.
|
||||
|
||||
| Preset/операция | Полезная нагрузка | Результат |
|
||||
| --- | --- | --- |
|
||||
| Запросить координаты | FF binary `01 01` | Type9 с точным token и final code; новый fix зависит от GNSS |
|
||||
| Перезапустить B2 | FF binary `01 07` | ACK отдельно; новое соединение со свежей telemetry — return |
|
||||
| Прочитать/применить настройки | FC `password*SERV*1.9` / `1.8` + HTTP | Полный независимый readback |
|
||||
| PIN4..6 включить/выключить | FC `password*SERV*8.PIN.STATE` | Не доказательство положения контактов |
|
||||
| PIN4..6 импульс 1..5 с | FC `password*SERV*24.PIN.0.SECONDS`; UI preset 5 с | Нет token-коррелированного подтверждения физического действия |
|
||||
|
||||
Server frame binary: `7b len FF sum payload 7d`, payload=`ff token:u32le command`;
|
||||
для FC checksum считается по тексту. Type9 response содержит result code и
|
||||
token. **0** — финальный ответ без ошибки, **6** — принято/нужно время,
|
||||
**7** — очередь B2 заполнена; остальные ошибки сохраняются явным результатом.
|
||||
TCP ACK/запись bytes не являются ответом B2. Ответ допускается через другой
|
||||
активный мониторинговый поток того же трекера, не другой IMEI.
|
||||
|
||||
PIN5 FC pulse однажды подтверждён наблюдением LED. Ранее binary pulse не дал
|
||||
видимого эффекта. Стендовые реле неизвестно подключены; физическая автоматика,
|
||||
CAN-управление, обратная связь мотора и безопасность ограничителя скорости
|
||||
не квалифицированы. Граница текущего runtime — B2. Внешние исполнительные
|
||||
устройства требуют отдельного известного wiring/feedback контракта.
|
||||
|
||||
## 15 · Журнал, очередь и восстановление в Core
|
||||
|
||||
UI работает через durable request ID, Core SQLite journal/outbox, операции
|
||||
VPS и bounded attempts. Полутабличная история показывает created/queued/sent,
|
||||
принято B2, final result, ожидание/повтор, attempt count, timestamps, latency и
|
||||
transport evidence. История загружается/обновляется по ID, поздний poll не
|
||||
откатывает terminal state в pending. «Остановить повторы» не означает undo.
|
||||
|
||||
Потеря Core↔VPS сначала разрешается GET исходного ID, затем при необходимости
|
||||
идемпотентным POST того же тела. Потеря B2 завершает attempt, но не стирает
|
||||
maintenance job. Новая попытка ждёт канал; config сначала reconcile образа.
|
||||
FIFO по устройству, capacity32, backoff5..300с. PIN-actions не повторяются
|
||||
автоматически после неопределённого исполнения. Это различие намеренное.
|
||||
|
||||
Нельзя обещать «каждая команда исполнится ровно один раз»: аппаратная
|
||||
дедупликация отсутствует, связь/питание могут отсутствовать неограниченно.
|
||||
Можно требовать, чтобы принятые намерения/попытки/неопределённость не терялись,
|
||||
а повтор и успех имели проверяемые основания. Полный алгоритм и восстановление
|
||||
VPS описаны в парном руководстве.
|
||||
|
||||
## 16 · API локального Mission Core
|
||||
|
||||
Базовый путь `/api/v1/fleet/equipment`, local_operator guard, `Cache-Control:
|
||||
no-store`, strict request fields. Ошибка ревизии/операции — 409, некорректные
|
||||
данные — 422, недоступность USB/хранилища — 503. Секретный config не отдаётся
|
||||
как обычное тело ответа оператору.
|
||||
|
||||
| Метод/суффикс | Назначение |
|
||||
| --- | --- |
|
||||
| `GET /catalog`, `GET/POST /profiles` | Модели, переносимые шаблоны |
|
||||
| `POST /inspect` | Read candidate через USB |
|
||||
| `GET/POST /instances`, `PUT /instances/{id}` | Реестр, add candidate, name/vehicle/settings с revision |
|
||||
| `POST /instances/{id}/inspect`, `/apply` | USB read / первоначальная запись |
|
||||
| `POST /instances/{id}/inspect-network`, `/apply-network` | Read/profile write через VPS; `select_sim` явно отмечает действие |
|
||||
| `GET/POST /instances/{id}/commands` | Presets/history и постановка request ID в runtime |
|
||||
| `POST /instances/{id}/commands/{request}/cancel` | Stop дальнейших attempts |
|
||||
| `GET /instances/{id}/commands/{request}/attempts` | История attempts |
|
||||
| `POST /instances/{id}/command` | Совместимый ограниченный action endpoint |
|
||||
| `GET/POST /firmware/{model}`, `GET /firmware/{model}/{sha}/download` | Архив файлов, не flash |
|
||||
|
||||
VPS admission/settings/telemetry находятся отдельно в `/api/v1/fleet/vps-hosts`.
|
||||
Не обходить guards прямой ручной записью в SQLite. Импорт старого private
|
||||
evidence не выдавать за новое чтение оборудования.
|
||||
|
||||
## 17 · Прошивка: архив и честная граница backup
|
||||
|
||||
В settings отдельный раздел «Прошивка»: последняя прочитанная версия с датой,
|
||||
архив модели, загрузка/выбор/скачивание `.dfw`. Добавление файла не отправляет
|
||||
его B2. Archive — `fleet/firmware/archive.sqlite3`; файл ≤4 MiB, каталог ≤128 MiB,
|
||||
SHA-256 дедупликация и проверка при скачивании сервером и клиентом. Filename
|
||||
не доказывает версию/совместимость; известный digest привязан к источнику.
|
||||
|
||||
| Версия | Размер | SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| 0.05 | 155824 | `bf71fc531b02917eac076d7b718b51698f3d787562ca37c959bb1c9954fe9927` |
|
||||
| 0.06 | 157760 | `36135a214f62bfeac7f049fdedb1cb7c717b676cfe6027f7c72a026c39988625` |
|
||||
|
||||
Файлы получены из каталога/WEB-конфигуратора производителя и сохранены локально;
|
||||
не включены в Git. **Образ установленной 0.01 не получен.** Полная конфигурация
|
||||
207 записей — backup настроек, не прошивки. Выгрузка исполняемого образа,
|
||||
квалифицированный flash по USB/OTA, rollback загрузчика и кастомизация бинарника
|
||||
не реализованы. `installable/update_available=false`. Никакая прошивка в ходе
|
||||
SIM-серии не менялась. Разрешение владельца рисковать тестовой платой не
|
||||
доказывает возможность восстановить 0.01.
|
||||
|
||||
Описание 0.05/0.06 не доказывает исправление SIM. Изменения APN других моделей
|
||||
ARNavi нельзя переносить на B2. Исходники/SDK и алгоритм bootloader не получены;
|
||||
высокая энтропия `.dfw` не является достаточным основанием для патча.
|
||||
|
||||
## 18 · Карта и сравнение условий связи
|
||||
|
||||
Карта использует свежие позиции independent B2 даже при offline Node. Координата
|
||||
принимается после диапазонов/finite checks, различает GNSS/LBS/Wi-Fi; GNSS
|
||||
требует минимум 4 спутника. Возраст измерения и last-known сохранены. Пропажа
|
||||
подложки карты — отдельная доступность сервиса слоёв, не потеря GNSS-телеметрии.
|
||||
В `ObservationMap` добавлено восстановление слоя через `useMapRecovery`.
|
||||
|
||||
Короткая сопоставимая серия 27.09, VPS0.1.25: снаружи 5/5 position replies,
|
||||
0.519..1.105с, median0.604; после возврата внутрь 5/5, 1.191..2.264с,
|
||||
median1.677. Спутники снаружи14..16, внутри после возврата14..17 (исходный
|
||||
одиночный снимок внутри имел8). Доставка обычной позиции была примерно
|
||||
3.5..5.7с в обеих сериях. Это не bandwidth benchmark/p95, не доказательство
|
||||
виновности USB/оператора. Место/время/возможное питание менялись совместно.
|
||||
|
||||
Дальнейшая квалификация велась внутри. На 0.1.41 gate5с увеличивает видимое
|
||||
ожидание пригодного socket: разделять queue и reply, не выдавать total за
|
||||
чистую задержку radio. Подробные записи —
|
||||
`INDOOR_OUTDOOR_COMPARISON_20260927.md` и `TRANSPORT_EVIDENCE_20260928.md`.
|
||||
|
||||
## 19 · Что проверять дальше, не повторяя старые ошибки
|
||||
|
||||
Ближайшая открытая аппаратная задача — предпочтение SIM при сохранённом резерве
|
||||
и свежая identity резервного слота после hot insert. До найденного/принятого
|
||||
механизма сохранить честный native/both/exclusive UI; не принуждать переезды
|
||||
слота ради названия оператора. Новую SIM без доказанной identity не связывать
|
||||
со старой картой и не применять чужие credentials.
|
||||
|
||||
Остальные незакрытые границы: заводское подключение целиком, исправный USB
|
||||
при длительном чтении, любой сторонний оператор/корпоративный APN, повторяемые
|
||||
длительные radio outages, другой чистый VPS/provider, миграция literal-IP,
|
||||
масштаб1000, firmware flash/rollback, управляемая периферия. Отмечать каждую
|
||||
отдельно; успешный readback не закрывает физическое действие CAN/реле.
|
||||
|
||||
Регрессии: `test_arnavi_b2_{usb,write,configuration_audit}.py`,
|
||||
`test_b2_{web_protocol,cellular_telemetry,sim_identity,sim_network,dual_sim,
|
||||
automatic_connectivity,native_connectivity,output_telemetry}.py`,
|
||||
`test_equipment_*.py`, `test_independent_equipment.py`, `test_vps_*.py`.
|
||||
Closeout28.09: 427 targeted Python, 1016 frontend (включая 32 ARNavi),
|
||||
10 assets/plugin-boundary checks, TypeScript, Ruff; Design Guideline
|
||||
registry/icon contract/catalog typecheck. Последний production build и UI
|
||||
hardware path описаны в `NATIVE_INTERNET_POLICY_20260928.md`.
|
||||
|
||||
Источники протокола сохранены в исследованиях: [руководства B2](https://8888.arusnavi.ru/Arnavi%20B2/),
|
||||
[INTERNAL HEADER2/PACKAGE/TAG/SERVER_COM](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit),
|
||||
публичная schema model231. Статически исследован Configurator251111,
|
||||
SHA `f79af698160ce6009c58608ec5511fab1680eea472ba9d689835fb032f2fc6ec`;
|
||||
Windows executable не является runtime dependency. Карточки, эти руководства,
|
||||
codec/tests и датированные evidence-summary достаточны для повторения принятой
|
||||
реализации; неизвестные аппаратные возможности остаются обозначены явно.
|
||||
@@ -0,0 +1,371 @@
|
||||
# ARNavi VPS сервер — руководство передачи реализации
|
||||
|
||||
Актуальный срез: 28.09.2026, VPS Host **0.1.41**, B2 **231 / 0.01**.
|
||||
Документ описывает работающий код и доказанные границы. Ранние отчёты в
|
||||
`docs/vps_host/` и `docs/arnavi_b2/` сохраняют историю своих версий; при
|
||||
противоречии текущую конструкцию читать здесь и в исходниках указанного среза.
|
||||
Парный документ: [ARNavi B2 трекер](ARNAVI_B2_TRACKER_20260928.md).
|
||||
|
||||
## 01 · Назначение и границы системы
|
||||
|
||||
VPS Host ARNavi — отдельный сервер Mission Core, независимый от бортового ПК.
|
||||
Трекер сам устанавливает мобильное соединение с VPS. Mission Core сам обращается
|
||||
к VPS за телеметрией и результатами и отправляет ему задания. VPS не открывает
|
||||
соединений к Core, не требует публичного адреса Mac/борта и не использует
|
||||
обратный туннель. Остановка браузера или Core не останавливает приём на VPS.
|
||||
|
||||
Это самостоятельная реализация `apps/vps-host`, а не прежний Device Core Edge
|
||||
из ROBOT2B-7. Старые службы/порты 443/9921 не являются зависимостью новой
|
||||
схемы. Установщик сохраняет чужие службы. Не переносить старые команды
|
||||
развёртывания, service.ping, маршруты Foundry или Gelios в новый runtime.
|
||||
|
||||
Реализованы приём INTERNAL, хранение и выдача пакетов, ограниченные команды,
|
||||
полная передача конфигурации B2, долговечные задания обслуживания, учёт попыток,
|
||||
резервирование/перенос состояния. В рабочем runtime нет запросов к ARNavi/Gelios.
|
||||
Это автономия принятого набора функций, не полная совместимость со всеми
|
||||
функциями производителя, CAN, Modbus, BLE и загрузчиком прошивки.
|
||||
|
||||
## 02 · Сетевые каналы и доверие
|
||||
|
||||
| Инициатор → получатель | Канал | Назначение |
|
||||
| --- | --- | --- |
|
||||
| B2 → VPS | TCP 9922, INTERNAL | Телеметрия; команды возвращаются в открытый B2 поток |
|
||||
| B2 → VPS | Тот же TCP 9922, HTTP POST `/c/index.php` | Собственный сервис конфигурации и времени B2 |
|
||||
| Core → VPS | TLS 1.3, TCP 19443 | Pairing, admission, пакеты, команды, операции, результаты |
|
||||
| Браузер → локальный Core | Канонический `127.0.0.1:8000` | UI, локальная операторская авторизация |
|
||||
|
||||
Публичный DNS/IP и порты — параметры установки, не константы устройства.
|
||||
Для нового контура предпочтителен постоянный DNS. При переносе сервера с тем же
|
||||
DNS трекеры сохраняют адрес; сам импорт состояния DNS не меняет.
|
||||
|
||||
У VPS собственные сертификат/ключ TLS и host ID. Pairing-код включает endpoint,
|
||||
fingerprint, одноразовый secret и срок 24 часа. Core закрепляет fingerprint,
|
||||
хранит bearer credential приватно. До запроса pairing сохраняются ожидающие
|
||||
учётные данные: потерянный HTTP-ответ допускает продолжение той же регистрации.
|
||||
Другой Core/token не может повторно использовать ключ. У хоста один Core-владелец.
|
||||
|
||||
Приёмник принимает только зарегистрированные IMEI и отдельно известный numeric
|
||||
device ID. IMEI из открытого протокола — адресация, не криптографическая
|
||||
аутентификация оборудования. INTERNAL/HTTP B2 не становятся TLS от наличия
|
||||
TLS API управления. Конфигурационный HTTP дополнительно сопоставляется с
|
||||
допущенным устройством и текущим modem peer; это не аппаратный сертификат.
|
||||
|
||||
## 03 · Модель данных и размещение кода
|
||||
|
||||
| Модуль | Ответственность |
|
||||
| --- | --- |
|
||||
| `apps/vps-host/ndc_vps/service.py` | asyncio TCP/TLS серверы, parsing/dispatch, пробуждение очередей |
|
||||
| `store.py` | private state, pairing/admission, SQLite, пакетный курсор и ACK |
|
||||
| `commands.py`, `actions.py` | ограниченная попытка, кадровые команды, токены и ответы |
|
||||
| `operations.py` | долговечный intent, FIFO по устройству, попытки, reconcile, stop |
|
||||
| `full_configuration.py`, `configuration.py`, `sim_selection.py`, `sim_guard.py` | preflight/образ/readback, SIM и новое подключение |
|
||||
| `delivery.py`, `transport_evidence.py` | очередь TCP/asyncio, срок доставки, сохранение наблюдений |
|
||||
| `observation.py` | отдельная ограниченная инженерная запись протокола |
|
||||
| `install.py`, `owner_entry.py`, `firewall.py`, `portable_state.py` | установка, план/применение, firewall, восстановление/перенос |
|
||||
| `scripts/build_vps_host.py` | воспроизводимый tar + автономный `.pyz` |
|
||||
|
||||
Билдер копирует из B2 plugin `internal.py` как `ndc_vps/arnavi.py`, а также
|
||||
`usb_protocol.py`, `web_protocol.py`, `sim_network.py`. На VPS нет импортов
|
||||
остального Mission Core, FastAPI или обязательного pip-окружения.
|
||||
|
||||
Состояние `/var/lib/ndc-mission-vps/journal.sqlite3`: `state`, `devices`,
|
||||
`device_ids`, `packages`, `receipts`, `commands`, `operations`,
|
||||
`operation_attempts`, `operation_modem`, `operation_stops`, транспортные
|
||||
наблюдения. Код находится в `/opt/nodedc-mission-vps/current`; unit —
|
||||
`ndc-mission-vps.service`; процесс работает как `ndc-mission-vps`.
|
||||
|
||||
Core хранит хосты, курсоры, пакеты и проекции в `fleet/vps-hosts/hosts.sqlite3`.
|
||||
Реестр оборудования, профили, журнал и outbox — в
|
||||
`fleet/independent-equipment/registry.sqlite3`; исходные образы — в его private
|
||||
`evidence`. Это разные хранилища с разной ответственностью, оба входят в backup.
|
||||
|
||||
## 04 · Установка с исходников и подключение в UI
|
||||
|
||||
Поддерживаемый профиль: **Ubuntu Server 24.04 amd64, Python 3.12, OpenSSL 3,
|
||||
systemd**. Не объявлены поддержанными Debian, другая Ubuntu/архитектура или
|
||||
минимальный образ без этих возможностей. Установщик проверяет предпосылки;
|
||||
Docker, Node.js, GUI, compiler и pip ему не нужны.
|
||||
|
||||
Сборка из корня Mission Core:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/build_vps_host.py --output /tmp/vps-host-0.1.41.tar
|
||||
```
|
||||
|
||||
Результат — tar для инженерной работы, `.pyz` для пользователя и digest manifest.
|
||||
Размеры/хеши проверяются перед публикацией:
|
||||
|
||||
```sh
|
||||
.venv/bin/python scripts/publish_fleet_installer.py \
|
||||
--fleet-root /path/to/operator/fleet --kind vps-arnavi \
|
||||
--file /tmp/vps-host-0.1.41.pyz --version 0.1.41 --sha256 ACCEPTED_SHA256
|
||||
```
|
||||
|
||||
На VPS скопировать скачанный из Mission Core файл и запустить:
|
||||
|
||||
```sh
|
||||
sudo python3 vps-host-0.1.41.pyz --host trackers.example.org
|
||||
```
|
||||
|
||||
Без `--host` установщик запрашивает адрес. Wrapper вызывает тот же механизм
|
||||
preflight → exact plan digest → apply. Создаются account, private state, TLS,
|
||||
immutable release, unit, pairing key; выполняется health-check. Неподдержанный
|
||||
OS, занятые порты или чужая установка отклоняются, а не чинятся неявно.
|
||||
|
||||
Ключ находится в **`/opt/nodedc-mission-vps/connect.key`** (ссылка на защищённое
|
||||
состояние). В Core: аппарат → Оборудование → верхний плюс → VPS Host ARNavi →
|
||||
название, ключ, обслуживаемые аппараты. Один хост может быть связан с несколькими
|
||||
роверами; добавление к следующему использует существующий хост. Это один общий
|
||||
объект, не несколько копий сервера. Установщик Node доступен в том же мастере
|
||||
при выборе БК; публикация архива не запускает обновление борта.
|
||||
|
||||
## 05 · Firewall, обновления и воспроизводимость
|
||||
|
||||
Нужно внешнее прохождение **TCP 9922 и 19443**. Для распознанной прежней
|
||||
NODE.DC nftables policy `nodedc_b2_vps` установщик добавляет два собственных
|
||||
правила с комментариями и постоянный include, проверяет исходные хеши и
|
||||
сохраняет rollback. Он не очищает таблицы. Неизвестный локальный firewall и
|
||||
security group/cloud firewall провайдера автоматически не настраиваются.
|
||||
Доступный локальный listener не доказывает доступность из мобильной сети.
|
||||
|
||||
Обновление штатным `.pyz` сохраняет identity, pairing и journal, создаёт backup
|
||||
SQLite и меняет release/unit с health-check. Повтор той же версии — проверяемый
|
||||
no-op. Неуспех возвращает предыдущую версию/unit. Нельзя ремонтировать VPS
|
||||
ручным копированием модулей и считать это воспроизводимой поставкой.
|
||||
|
||||
Принятый 0.1.41 и две повторные сборки 28.09 совпали:
|
||||
|
||||
- `.pyz`: `d63b5fd10b4dda32b6aaefa0f57ab4c71d322b2231d0c805922d0500ccd11db8`;
|
||||
- manifest: `86d8831179ff1332297ae31a12d91086c75b401d04515301c75c87ffb31edbff`;
|
||||
- tar: `ea717c2295c02dee51fe47ec572e627bbedf90491a4499329572c58780a123d6`.
|
||||
|
||||
Не менять файлы внутри `apps/vps-host` после такой фиксации без нового digest
|
||||
артефакта. Публикация установщика, его установка и аппаратная приёмка — три
|
||||
разных события. Полная проверка на другом чистом VPS/Ubuntu отложена владельцем;
|
||||
исторические проверки userspace и рабочего VPS не подменяют её.
|
||||
|
||||
## 06 · Приём телеметрии и гарантия ACK
|
||||
|
||||
Соединение B2 начинается с 10-байтного INTERNAL header `ff 23` и IMEI. Есть
|
||||
ограничения входного header/пакета и 10-секундный срок handshake. Неполный,
|
||||
невалидный или не допущенный поток не получает фиктивного успеха. Приёмник
|
||||
различает INTERNAL и конфигурационный HTTP на одном порту.
|
||||
|
||||
После проверки структуры и checksum один SQLite `BEGIN IMMEDIATE`/FULL commit
|
||||
атомарно сохраняет пакет, command receipt и наблюдение модема. Только после
|
||||
commit отправляется ACK B2. Core не может получить пакет раньше сохранения
|
||||
его влияния на командный runtime. Повтор уже принятого пакета дедуплицируется.
|
||||
Ошибка записи/полный диск не выдаётся за принятый пакет.
|
||||
|
||||
Core читает `GET /v1/packets?after=cursor`, сохраняет пакет и проекции, затем
|
||||
отправляет `POST /v1/ack` с `through`. Курсор устойчив к перезапуску. Это
|
||||
прикладная доставка с подтверждением хранения; она не спасает от уничтожения
|
||||
диска или бесконечного отсутствия связи.
|
||||
|
||||
Время измерения устройства, время приёма VPS и время синхронизации Core
|
||||
раздельны. Архив B2 может прийти после реконнекта: свежий TCP-пакет не делает
|
||||
старую координату текущей. Старые точки не заменяют новую позицию. Последняя
|
||||
известная позиция сохраняется с временем и отображается как устаревшая.
|
||||
Обычная телеметрия поступает по настройкам B2 без ручного запроса координат.
|
||||
|
||||
## 07 · API Core ↔ VPS
|
||||
|
||||
| Метод/путь | Контракт |
|
||||
| --- | --- |
|
||||
| `GET /health` | Минимальная проверка сервиса, не доказательство B2 online |
|
||||
| `POST /v1/pair` | Одноразовая привязка с согласованными credentials |
|
||||
| `GET /v1/status` | Версия/capabilities, адрес приёма и состояние |
|
||||
| `PUT /v1/devices` | Разрешённые IMEI, instance ID и numeric ID |
|
||||
| `GET /v1/packets?after=…` / `POST /v1/ack` | Курсорная выдача и подтверждение Core |
|
||||
| `POST /v1/operations` / `GET /v1/operations/{id}` | Долговечная операция и её результат |
|
||||
| `GET /v1/operations/{id}/attempts?before=…` | Страничная история попыток |
|
||||
| `POST /v1/operations/{id}/cancel` | Остановить будущие попытки, не отменить уже исполненное |
|
||||
| `POST /v1/commands` / `GET /v1/commands/{id}` | Ограниченная отдельная попытка/legacy actions |
|
||||
| `/v1/configuration-observations` | Отдельные аутентифицированные ограниченные инженерные leases |
|
||||
|
||||
Кроме health/pair требуется bearer с TLS pin. API JSON, body ≤1 MiB, запрос
|
||||
ограничен 15 секундами; не поддерживает произвольный shell или raw-команды.
|
||||
HTTP-результат приёма задания не является результатом устройства.
|
||||
|
||||
Core исполняет `fleet/vps_hosts.py`: admission → packets/ingest/ack → status;
|
||||
`equipment_network.py` и `equipment_outbox.py` ведут команды и reconcile.
|
||||
Цикл спит на событии с периодом 1 с при pending, 5 с без pending, интервалы
|
||||
sync ограничиваются отдельно. Это опрос VPS, а не принудительный GNSS-запрос
|
||||
каждую секунду. На macOS выбранный физический интерфейс привязывается только
|
||||
к VPS socket; UI не изменяет системный VPN/маршруты.
|
||||
|
||||
## 08 · Долговечное задание, попытки и последовательность
|
||||
|
||||
При пользовательском действии Core сначала фиксирует immutable ID, payload,
|
||||
guards и outbox в SQLite. Если HTTP POST/ответ потерян, сначала запрашивает
|
||||
этот ID на VPS. Только неразрешённая доставка повторяет **тот же ID и тело**.
|
||||
Одинаковый ID с другим digest отклоняется. Повтор клика/сети не создаёт вторую
|
||||
операцию с новым смыслом.
|
||||
|
||||
VPS хранит отдельный job (`operations`) и отдельные transport attempts
|
||||
(`operation_attempts`/`commands`). Перезапуск Core/VPS или expiry попытки не
|
||||
стирает job. Очередь FIFO по IMEI, до 32 незавершённых jobs на устройство;
|
||||
отказ одного трекера не блокирует другие. Повторные попытки ждут свежий канал,
|
||||
backoff растёт от 5 до 300 секунд. Idle sender просыпается от события; runtime
|
||||
не перечитывает всю завершённую историю на каждый пакет.
|
||||
|
||||
Durable kinds: `request-position`, `restart`, `read-configuration`,
|
||||
`configure-all`, `select-sim`. Старые VPS используют согласованный bounded
|
||||
контракт; capability/version нельзя молча считать совместимой. До dispatch
|
||||
проверяются identity, firmware и актуальная привязка. Изменение ревизии/аппарата
|
||||
не должно отправить старое намерение новому устройству.
|
||||
|
||||
Состояние transport attempt и runtime phase задания различны: waiting-link,
|
||||
ожидание следующей попытки, исполнение, reconciliation, stopped и terminal
|
||||
outcome. `expired/unconfirmed/uncertain` попытки не равны удалению намерения.
|
||||
Неразрешённый исход остаётся честным фактом до последующего наблюдения.
|
||||
|
||||
## 09 · Повторы, readback и остановка
|
||||
|
||||
| Операция | Правило восстановления |
|
||||
| --- | --- |
|
||||
| Координаты / чтение | Новая попытка после восстановления связи; старый токен не завершает новую |
|
||||
| Настройки | Сначала полный readback: target → успех, predecessor → новый preflight/допустимый повтор, иной образ → конфликт |
|
||||
| SIM | Помимо образа нужен свежий GPRS нужной SIM/любой разрешённой SIM; подтверждённый переход не перезапускается заново |
|
||||
| Restart | Известный final code 0 без return фиксируется как `accepted`; при неизвестном результате maintenance intent может повториться после восстановления |
|
||||
| PIN/импульс | Не входят в durable maintenance: автоматического повторения физического воздействия нет |
|
||||
|
||||
Трекер не имеет доказанной постоянной дедупликации по нашему job ID. Если действие
|
||||
и потерянный ответ произошли перед обрывом, невозможно обещать exactly-once
|
||||
физическое исполнение. Runtime обеспечивает сохранение намерения, фактов,
|
||||
проверяемое восстановление и явный исход, а не выдумывает ACK.
|
||||
|
||||
Stop сохраняется и в Core, и на VPS. Если POST ещё не пришёл, VPS создаёт
|
||||
tombstone: поздний запрос не оживляет job. Уже переданная попытка может
|
||||
завершиться. Остановка повторов не откатывает настройку и не отменяет команду,
|
||||
уже принятую B2. Очередь выходов не превращается в отложенное воздействие
|
||||
после долгого офлайна.
|
||||
|
||||
## 10 · Транспорт и уровни подтверждения
|
||||
|
||||
У 0.1.41 команда ждёт входных данных **на выбранном socket не старше 5 секунд**
|
||||
и пустых очередей asyncio/kernel. Среди пригодных потоков используется свежий.
|
||||
Старая half-open сессия не должна перехватывать команду у новой. Допуск durable
|
||||
попытки отдельно использует окно свежести 30 секунд; это не отменяет 5-секундный
|
||||
dispatch gate.
|
||||
|
||||
`delivery.py` отслеживает границу переданных байтов. Watchdog ограничивает
|
||||
доставку минимумом срока операции и 30 секунд после dispatch; HTTP-ответ
|
||||
настройки — 12 секунд. Учитываются monotonic time, kernel queue и asyncio
|
||||
queue, abortive close не оставляет просроченные байты висеть бесконечно.
|
||||
Это меры Linux transport, не ограничение времени исполнения в прошивке B2.
|
||||
|
||||
Журнал различает `prepared`, `written`, `tcp_acknowledged`, `unconfirmed` и
|
||||
причину. Наблюдение сохраняется и при закрытии sender, позднем ACK или restart.
|
||||
Необработанная запись после старта процесса становится unconfirmed/host_restarted.
|
||||
|
||||
Далее отдельно: token reply B2, intermediate code 6, final code 0/error,
|
||||
независимый readback, новое соединение/DS2. TCP ACK не завершает команду.
|
||||
Бинарный type-9 reply может прийти через любой действующий допущенный поток
|
||||
**того же IMEI**; проверяются token, срок, устройство и admission. Reply с иной
|
||||
карты/устройства/старой попытки не засчитывается. FC text не наследует token.
|
||||
|
||||
## 11 · Собственный сервис конфигурации
|
||||
|
||||
B2 обращается к конфигурационным host/port в полях 70/71. Это отдельный
|
||||
прикладной обмен поверх HTTP, даже если используется тот же 9922. Мониторинговая
|
||||
телеметрия сама по себе не доказывает работоспособность этой ветки.
|
||||
|
||||
`SERV*1.9` просит B2 выгрузить настройки; `SERV*1.8` — запросить образ с
|
||||
собственного endpoint. Полный CONF не влезает в короткий FC frame: нельзя
|
||||
разрезать его на придуманные команды. Точный бинарный framing находится в
|
||||
`web_protocol.py`, CRC/TLV — в `usb_protocol.py`.
|
||||
|
||||
Операция читает свежий образ, сравнивает ожидаемый SHA и порядок записей,
|
||||
сохраняет recovery fields **3,4,5,8,70,71**, выдаёт целевой образ однократно
|
||||
на попытку и независимо читает обратно. Факт выдачи записан до HTTP write.
|
||||
Между этапами полного обмена выдерживаются 15 секунд: ранние опыты без пауз
|
||||
теряли следующий запрос. Обычные запросы позиции этих пауз не имеют.
|
||||
|
||||
Сервис отвечает на квалифицированные identification/settings диалоги и opcode 7
|
||||
временем Unix UTC u32be собственного VPS. Numeric ID берётся из enrollment,
|
||||
не угадывается по IMEI. Пустой settings response из раннего эксперимента
|
||||
0.1.22 отозван: образ выдаётся только явной операции. Корректные часы VPS
|
||||
обязательны. Runtime не проксирует запросы на сервер производителя.
|
||||
|
||||
## 12 · Backup, fresh install и перенос
|
||||
|
||||
`--fresh` заменяет только этот продукт и создаёт новую identity после остановки
|
||||
unit и private backup в `/var/backups/ndc-mission-vps/`. Это не переустановка ОС.
|
||||
В Core надо явно выбрать заменяемую запись и новый ключ. `--restore BACKUP`
|
||||
восстанавливает соответствующую резервную копию; после нового pairing требуется
|
||||
согласованное восстановление состояния Core, а не ручная подмена tokens.
|
||||
|
||||
Плановый перенос с **тем же exact installer**:
|
||||
|
||||
```sh
|
||||
# Source: останавливает сервис и ставит сохраняемый migration fence.
|
||||
sudo python3 vps-host-0.1.41.pyz --export-state /root/vps-state.tar.gz
|
||||
# Target: пустой поддержанный VPS; digest берётся из результата export.
|
||||
sudo python3 vps-host-0.1.41.pyz --import-state /root/vps-state.tar.gz --sha256 ARCHIVE_SHA256
|
||||
# Отмена: сначала остановить target, затем на source:
|
||||
sudo python3 vps-host-0.1.41.pyz --resume-source
|
||||
```
|
||||
|
||||
Архив включает TLS/owner/device registrations, journal/jobs/attempts/stops,
|
||||
исключает код, unit/firewall и живые TCP-сессии. Импорт проверяет фиксированный
|
||||
набор, хеши, exact installer, TLS-пару, SQLite integrity, запрещает traversal,
|
||||
links/лишние/повторные members и публикует всё одной same-filesystem rename.
|
||||
Лимит архива 2 GiB; нужно 2.25 GiB staging. Source остаётся fenced после
|
||||
reboot и не запускается сам. Не запускать обе копии одной identity одновременно.
|
||||
|
||||
Сохраняется endpoint: нужен DNS move либо перенос прежнего IP. Literal-IP
|
||||
смена адреса требует отдельной проверенной миграции Core/трекеров, импорт её
|
||||
не выполняет. Recovery snapshot не содержит jobs, созданные после snapshot.
|
||||
Это плановое восстановление, не replication/HA. Архив с ключами — секретный,
|
||||
0600, передавать через разрешённый канал, не в Git/карточку.
|
||||
|
||||
## 13 · Ограничения ресурсов и эксплуатации
|
||||
|
||||
Сейчас admission TCP ограничен **256 соединениями**, не 256/1000 трекерами:
|
||||
одно устройство может держать несколько мониторинговых и HTTP-соединений.
|
||||
Idle read timeout — 180 секунд. Журнал приёма ограничен 512 MiB, резерв диска
|
||||
256 MiB; при исчерпании запись не подтверждается. B2 также имеет конечный архив.
|
||||
Не заявлять безусловную доставку при бесконечном офлайне, полном диске или
|
||||
неисправном носителе. Тысяча реальных устройств/нагрузка не квалифицированы.
|
||||
|
||||
На стенде наблюдались активный uplink при неподтверждённом downlink, сбросы TCP
|
||||
и длительные провалы. Очереди/свежесть/транспорт улучшены, но причина каждого
|
||||
радиосбоя не установлена; гарантии p95/p99 и постоянного восстановления нет.
|
||||
GNSS fix, доступ в мобильную сеть, соединение VPS и delivery команды — разные
|
||||
метрики. Плохая спутниковая видимость не доказывает отсутствие GPRS.
|
||||
|
||||
До полевой эксплуатации нужны метрики disk/backlog, квоты/retention по jobs,
|
||||
нагрузочные проверки на целевом сервере, допустимые сроки обслуживания и
|
||||
процедура действий при конфликте. На операторском Mac нагрузку не проводить.
|
||||
|
||||
## 14 · Проверки и диагностика без повторного R&D
|
||||
|
||||
При проблеме идти по цепочке: версия и health VPS → внешний путь к обоим
|
||||
портам → admission точного instance → последнее измерение/приём B2 → текущий
|
||||
job ID → attempts → transport facts → B2 receipt → readback/DS2. Не создавать
|
||||
новые команды до выяснения результата старой. Не лечить radio outage стиранием
|
||||
очереди. Для partial image сначала независимое чтение; неизвестный образ —
|
||||
конфликт, не приглашение перезаписать всё старым профилем.
|
||||
|
||||
В этом closeout прошли **427** целевых Python-проверок ARNavi/equipment/VPS,
|
||||
1016 frontend-проверок (включая 32 проверки ARNavi), 10 проверок assets/plugin
|
||||
boundaries, TypeScript и Ruff. Единственная правка при closeout —
|
||||
явная привязка переменной цикла в callback теста watchdog. Проверена повторная
|
||||
сборка exact 0.1.41. Предыдущие аппаратные прогоны/production build сохранены
|
||||
в датированных отчётах; новые hardware-команды или установка в closeout не нужны.
|
||||
|
||||
Основные тесты: `tests/test_vps_{host,operations,command_receipts,packet_commit,
|
||||
portable_state,installer_permissions}.py`, `test_equipment_{command_runtime,
|
||||
command_reconciliation,operations,network,bootstrap}.py`, `test_b2_web_protocol.py`.
|
||||
Поставляемые bounded harness: `qualify_delivery.py`, `qualify_receipts.py`,
|
||||
`qualify_runtime.py`, `qualify_faults.py`, `qualify_operations.py`,
|
||||
`qualify_configuration.py`, `qualify_recovery.py`. Они используют временное
|
||||
синтетическое состояние; результаты не называть аппаратной приёмкой.
|
||||
|
||||
Подробное evidence: `PACKET_COMMIT_20260927.md`,
|
||||
`DURABLE_MAINTENANCE_20260927.md`, `TRANSPORT_EVIDENCE_20260928.md`,
|
||||
`TRACKER_CONFIRMATIONS_20260927.md`, `PORTABLE_STATE_20260927.md`.
|
||||
Новые тесты чистого чужого Ubuntu, заводского B2, смены literal-IP и масштаба
|
||||
остаются отдельными незакрытыми проверками. Старые отчёты не переписываются
|
||||
задним числом в успешные.
|
||||
@@ -309,3 +309,26 @@ app-Lo_50rZQ.js, DG registry validation и catalog build. Live QA: форма и
|
||||
DOM18:59:15Z: обе камеры ready4/unpaused, media50.057s/50.081s, dragging0.
|
||||
K1 обнаружен, три его viewport доступны, acquisition не запускался этой
|
||||
правкой. Runtime БК, SDK, запись и capture policy не менялись.
|
||||
|
||||
## Map transport outage — 27.09.2026
|
||||
|
||||
Current canonical Core still uses the qualified existing loopback SSH link to the
|
||||
NAS Map Gateway. This outage is not missing tracker coordinates: B2 has fresh
|
||||
GNSS position and 17 satellites, while gateway health and both checked provider
|
||||
endpoints return HTTP 502 `map_gateway_unavailable`. The existing LaunchAgent is
|
||||
loaded; its SSH log shows connection timeouts. Tailscale reports the configured
|
||||
NAS peer offline, last seen 2026-09-27 00:13:19Z (03:13 Moscow); one bounded peer
|
||||
ping timed out. No route, VPN, NAS sshd policy, credentials or gateway deployment
|
||||
was changed. The owner was asked to check NAS power/connectivity.
|
||||
|
||||
ObservationMap now retains the coordinate label in its unavailable notice and
|
||||
checks its own same-origin gateway health every 30 seconds while unavailable.
|
||||
It recreates the renderer only when that gateway reports `ok=true`, retaining
|
||||
manual retry. The poll aborts on unmount and has a 10-second request bound. It
|
||||
does not substitute public tile providers or claim loaded imagery from fresh
|
||||
GNSS telemetry. All disabled map layers are a valid ready state, not an error.
|
||||
Actual recovered imagery remains unverified until the NAS returns online.
|
||||
|
||||
Owner confirmed the external server lacks Internet pending payment and explicitly
|
||||
deferred map work. No further map connectivity changes or recovery tests were
|
||||
performed after that request; imagery acceptance remains deferred.
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# Clean Ubuntu installation and recovery — VPS Host 0.1.33
|
||||
|
||||
> Subsequent release 0.1.35 adds [qualified portable state transfer](PORTABLE_STATE_20260927.md).
|
||||
> The results and remaining gates below describe the earlier 0.1.33 acceptance.
|
||||
|
||||
Owner objective: a downloadable installer must provision the declared bare OS,
|
||||
generate a pairing key, run the receiver and retain durable state through
|
||||
recovery. Updating the previously prepared production VPS is a separate check.
|
||||
|
||||
## Artifact and environment
|
||||
|
||||
- Installer version: **0.1.33**.
|
||||
- Installer SHA-256: `994a6b011bb51feaff8daa97d1854f0f2e1928f8472883d3b910f3cc8b43bb5e`.
|
||||
- Payload manifest SHA-256: `798375cdbee0de2ab78b23bc2380e8139039e7b7c2deb50f43d7d725ed620a40`.
|
||||
- Two source builds produced identical `.tar` and `.pyz` artifacts.
|
||||
- Official [Ubuntu Noble release image](https://cloud-images.ubuntu.com/releases/noble/release/):
|
||||
`ubuntu-24.04-server-cloudimg-amd64-root.tar.xz`, checked against the published
|
||||
SHA256SUMS. Image SHA-256:
|
||||
`820311e238ea34d76a8ca2643d6c01065212e9417109e7397d70472a236df261`.
|
||||
- Guest reports Ubuntu 24.04.5 LTS, amd64, Python 3.12. The accepted product
|
||||
environment remains Ubuntu Server 24.04 amd64, not arbitrary Linux.
|
||||
|
||||
The clean image ran on the owned VPS in separate mount, PID, network, UTS, IPC
|
||||
and cgroup namespaces, using the host kernel. It had only loopback networking,
|
||||
256 MiB memory and a 35% CPU limit. The production service, network and state
|
||||
were not mounted into the guest. No package installation, copied dependency,
|
||||
pre-existing product account, product state or prepared application environment
|
||||
was supplied. This is clean-userspace dependency closure, not a second VM,
|
||||
different-kernel or cloud-provider firewall test.
|
||||
|
||||
`scripts/qualify_vps_clean_host.py` owns the temporary substrate and cleanup.
|
||||
`scripts/qualify_vps_clean_client.py` pairs a synthetic Core through the actual
|
||||
TLS API and submits one operation for one synthetic offline tracker. These
|
||||
engineering scripts are not included in the shipped product payload.
|
||||
|
||||
## Failure found and correction
|
||||
|
||||
The old installer relied on the caller's umask when creating its public code
|
||||
directories. With root's umask 0077, the service account could not traverse
|
||||
`/opt/nodedc-mission-vps` and `releases`; first installation failed while
|
||||
generating the invitation. Version 0.1.33 explicitly sets those two owned code
|
||||
directories to 0755. Credentials, state and private evidence remain restricted.
|
||||
A regression checks service-code traversal and secret permissions under 0077.
|
||||
|
||||
Earlier failed test-substrate starts are retained: the namespace guest needed
|
||||
`pivot_root`, a traversable guest root, and time to finish its stock first-boot
|
||||
network wait before measuring product installation. No product OS repair was
|
||||
performed manually. The final run used a freshly extracted image and the
|
||||
unchanged accepted 0.1.33 installer.
|
||||
|
||||
## Passed acceptance
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| First installation on clean image | Service active and enabled; key generated |
|
||||
| Listeners | TCP 19443 and 9922 listening |
|
||||
| Key admission | Synthetic Core paired through TLS API; device registered |
|
||||
| Repeated installer | `already_current`; four identity/key files unchanged |
|
||||
| Service restart | Same owner authenticates; original queued operation retained |
|
||||
| `--fresh` | Private backup created; replacement obtains a new TLS identity |
|
||||
| `--restore` | Original four identity/key files restored byte for byte |
|
||||
| Restored API/runtime | Same owner token, device registration and pending job usable |
|
||||
| Production upgrade 0.1.32 → 0.1.33 | SQLite backup; four identity files preserved; active service |
|
||||
| Installed payload | All 27 files match accepted manifest |
|
||||
| Mission Core download | Exact accepted 0.1.33 checksum; Node remains 0.8.45-1 |
|
||||
| Actual B2 after upgrade | Position command token-confirmed, code 0, one attempt, 0.637 s |
|
||||
|
||||
The first Core command admission after the host upgrade was rejected before
|
||||
creating a job because of a stale release allowlist. The Core and frontend
|
||||
admission lists were updated together; runtime acceptance now runs against both
|
||||
0.1.32 and the actual current source release. The canonical Core was restarted
|
||||
through its managed installer after SQLite backups and passed health acceptance.
|
||||
|
||||
Temporary systemd units were verified inactive; all test root filesystems and
|
||||
image copies were removed. Approximately 4.3 GB of disk remained free. Private
|
||||
evidence was downloaded, hashed and retained under session
|
||||
`acceptance-e7e12e66a51b4510a2fd5b1a7cc3a93d`. Archive SHA-256:
|
||||
`8e324d80dcbb275e40f855158e20a37d7834eebe9329079429a97ce1ec8ad7e0`.
|
||||
|
||||
## Limits and next gates
|
||||
|
||||
- The tested clean Ubuntu has no blocking local firewall policy. The installer
|
||||
also handles the existing named NODE.DC nftables policy. It does not rewrite
|
||||
arbitrary foreign firewall rules or a provider's external security group.
|
||||
Public reachability of both ports still needs verification on a new provider.
|
||||
- Recovery here is from `--fresh`'s backup in the same OS environment. A portable
|
||||
export/import onto another bare VPS, with a missing service account or changed
|
||||
endpoint, is **not yet qualified**. A fresh installation creates a new server
|
||||
identity; it does not automatically recreate an old paired server.
|
||||
- Keep a stable DNS endpoint for migration where available. Endpoint migration
|
||||
remains explicitly rejected by the current installer rather than silently
|
||||
leaving trackers or the paired Core pointing at the old server.
|
||||
- This is not a thousand-device capacity result. The available Worker 006 was
|
||||
unreachable; no load test ran on the Mac or the production VPS.
|
||||
- [Physical SIM and settings results](../arnavi_b2/SIM_INTENT_AND_CONFIGURATION_CYCLE_20260927.md)
|
||||
separately record the failed SIM-2 return and successful owner-approved USB
|
||||
recovery. They do not establish automatic SIM fallback or full vendor parity.
|
||||
@@ -0,0 +1,208 @@
|
||||
# VPS Host admission and tracker map
|
||||
|
||||
> Historical implementation ledger. For the current 0.1.41 architecture,
|
||||
> installation, runtime/recovery and accepted limits, start with
|
||||
> [the VPS handoff](../handoff/ARNAVI_VPS_SERVER_20260928.md) and
|
||||
> [the B2 handoff](../handoff/ARNAVI_B2_TRACKER_20260928.md).
|
||||
> Release statements below retain their original qualification date.
|
||||
|
||||
[Подтверждения B2 и граница рантайма, Host 0.1.31](../arnavi_b2/TRACKER_CONFIRMATIONS_20260927.md)
|
||||
|
||||
Historical incremental release: **0.1.38**, adding card-bound configuration guards
|
||||
and verified per-card access in Core. See
|
||||
[physical acceptance and remaining limits](../arnavi_b2/CARD_ACCESS_APPLICATION_20260928.md).
|
||||
|
||||
Release **0.1.37** added explicit permission for both SIMs
|
||||
with full readback and fresh GPRS after restart. Atomic packet/receipt persistence
|
||||
from 0.1.36 is retained. See [both-SIM policy](../arnavi_b2/BOTH_SIM_POLICY_20260927.md).
|
||||
The exact published installer SHA-256 is
|
||||
`140a54c608a6e9c71663cc9435c7ffab12bba6c5277fc78c6d9daa59da19e002`.
|
||||
See [packet and command-result durability](../arnavi_b2/PACKET_COMMIT_20260927.md),
|
||||
[portable transfer acceptance and limits](PORTABLE_STATE_20260927.md),
|
||||
[prior clean installation](CLEAN_INSTALLATION_20260927.md),
|
||||
[durable maintenance](../arnavi_b2/DURABLE_MAINTENANCE_20260927.md), and
|
||||
[physical settings/SIM results](../arnavi_b2/SIM_INTENT_AND_CONFIGURATION_CYCLE_20260927.md).
|
||||
Historical release acceptance below retains its original scope. Complete vendor
|
||||
parity, remote SIM fallback, provider/DNS changes and a real literal-IP endpoint
|
||||
migration are not claimed.
|
||||
|
||||
Owner surface decision: extend the existing apparatus Equipment top-level plus.
|
||||
Options are onboard computer, ARNavi B2 and VPS Host. A VPS is shared across
|
||||
apparatuses and is not a child of an onboard PC. The existing Node enrollment
|
||||
remains private-LAN only. A dedicated VPS workspace/new navigation root is not
|
||||
needed: host admission/settings fit the existing equipment form and settings
|
||||
window. No new shared visual primitive was introduced.
|
||||
|
||||
The root plus now renders the selected type's fields in one dialog. Both Node
|
||||
and VPS sections provide the locally published installer, accepted version and
|
||||
exact OS profile before the pairing field. Shared Window footer actions align
|
||||
to the trailing edge. The role is labelled VPS Host ARNavi; macOS interface names
|
||||
are exposed as hardware labels only inside optional VPN connection settings.
|
||||
|
||||
## Owned modules
|
||||
|
||||
- `apps/vps-host/`: headless standard-library runtime and exact-plan installer.
|
||||
- `scripts/build_vps_host.py`: deterministic payload; exact vendor decoder is
|
||||
bundled from `src/k1link/device_plugins/arnavi_b2/internal.py`.
|
||||
- `fleet/vps_transport.py`: public endpoint validation, TLS pin and local network
|
||||
interface selection. macOS IP_BOUND_IF scopes a physical-interface choice to
|
||||
the single VPS socket; it changes no OS routes or VPN configuration. Other OS
|
||||
profiles use their system routing.
|
||||
- `fleet/vps_hosts.py`: shared identity/assignments, private token, durable cursor
|
||||
and tracker positions. Tracker ownership remains in EquipmentStore.
|
||||
- `web/vps_host_api.py`: loopback operator admission, host settings and telemetry.
|
||||
- `core/fleet/vps.ts`: browser contract and bounded polling lifecycle.
|
||||
- `workspaces/fleet/equipment/VPSHostSettings.tsx`: key/host selector, name,
|
||||
current connection, shared vehicle assignments, real sync status.
|
||||
- `workspaces/fleet/observation/ObservationMap.tsx`: real source projections in
|
||||
the existing Cesium renderer, no simulated movement or fabricated location.
|
||||
|
||||
## State and authority
|
||||
|
||||
New key → pending durable Core credentials → pinned TLS pairing → paired.
|
||||
A network failure after remote consumption can retry with the same persisted
|
||||
credentials. Another Core/token cannot reuse the invitation. Each VPS accepts
|
||||
one Core owner. TLS identity and private journal survive code update/rollback.
|
||||
|
||||
Core periodically synchronizes registered B2 identities whose selected server
|
||||
matches that VPS and whose vehicle is assigned to it. The receiver rejects
|
||||
unknown identities. A policy save is not a device apply. USB apply uses existing
|
||||
qualified transaction/readback. First packet proves uplink; GNSS data proves a
|
||||
position; each has an independent age. Old replay never replaces a newer fix.
|
||||
The source's last known position is retained with its time when offline.
|
||||
|
||||
A VPS can serve multiple vehicles; a vehicle can own multiple independent
|
||||
trackers. Reassignment modifies registry ownership, not tracker identity, SIM
|
||||
or firmware. Host settings are one shared record with optimistic revision.
|
||||
|
||||
## Reproduction and limits
|
||||
|
||||
Installation, key path, backups, rollback, queue limits and the supported OS
|
||||
profile are documented in [`apps/vps-host/README.md`](../../apps/vps-host/README.md).
|
||||
The source tree contains no deployed address, real IMEI, SIM phone number, key,
|
||||
GPS coordinates or private capture. Those live in operator state/evidence.
|
||||
|
||||
The available Ubuntu VPS qualified first installation, upgrade, real rollback,
|
||||
reapplication, no-op reapplication, systemd health and independent TLS connection.
|
||||
The actual USB B2 with an MTS SIM qualified writing a second INTERNAL server,
|
||||
independent readback, receiving real telemetry and showing GNSS on the rover
|
||||
observation map while the onboard PC is offline. UI qualification includes the
|
||||
root chooser, host key form, host settings, normal/expanded map and Escape.
|
||||
Private deployment ledger records exact artifacts, times and device receipts.
|
||||
|
||||
Version 0.1.3 additionally qualified the actual Core download checksum, clean
|
||||
product replacement with backup, automatic restoration after installation
|
||||
failure, explicit old-record replacement using the new key through the UI,
|
||||
fresh B2 telemetry and no-op reapplication. The existing Node 0.8.45-1 installer
|
||||
was copied from its accepted build host and published without updating the board.
|
||||
|
||||
Not claimed: clean-image/other-distribution qualification, thousand-device load,
|
||||
cryptographic device authentication, arbitrary remote B2 configuration, or
|
||||
removal of the existing vendor configuration channel. Existing Gelios server
|
||||
was retained in slot 1 during acceptance; own VPS was added in slot 2.
|
||||
|
||||
## Network endpoint control — Host 0.1.6
|
||||
|
||||
The subsequent qualification replaced the primary Gelios endpoint with the
|
||||
owner's VPS from Core's settings window. The old secondary owner channel remains
|
||||
configured. Saving the endpoint starts a durable bounded operation; fresh GETP,
|
||||
one SETP #1 and an independent readback distinguish intent from confirmation.
|
||||
Core also exposes read-only endpoint inspection through VPS. Reconnection and
|
||||
missing write acknowledgement do not cause a second write. The real reversal
|
||||
experiment restored the entire initial configuration byte for byte.
|
||||
|
||||
Admission now includes observed/confirmed prior endpoints, so saving a desired
|
||||
address cannot remove the old uplink prematurely. Remote scope is only primary
|
||||
host/port on the qualified B2 firmware. Full-profile support, vendor-channel
|
||||
removal and fleet-scale qualification remain open. See
|
||||
[network configuration](../arnavi_b2/NETWORK_CONFIGURATION.md).
|
||||
|
||||
|
||||
## Accepted network settings and restart increment — Host 0.1.23
|
||||
|
||||
The 0.1.6 limitations above describe that release's acceptance, not the current
|
||||
runtime. Both monitoring destinations and the B2 configuration endpoint now use
|
||||
the owned VPS. Host 0.1.23 supports full configuration reads, reviewed profile
|
||||
writes with independent readback, position/output commands and bounded remote
|
||||
restart observation, with no runtime vendor API calls. Core synchronizes the
|
||||
numeric device ID already read during enrollment; conflicting identity changes
|
||||
are rejected and there is no vendor registration dependency.
|
||||
|
||||
The initial bootstrap clears only the documented startup-check bit. On the bench
|
||||
this allowed a full 207-record read after a remote restart, byte-identical to the
|
||||
new target. Existing periodic polling is preserved; background no-update behavior
|
||||
is not yet qualified. See [autonomy acceptance](../arnavi_b2/AUTONOMY_AND_COMMANDS.md)
|
||||
for the exact physical results and remaining scope. Do not interpret complete
|
||||
image transport as proof of all CAN/peripheral/firmware operations.
|
||||
|
||||
The operator download is the exact qualified immutable 0.1.23 `.pyz`, SHA-256
|
||||
`97abb7a869f86debe885e5130dd14791ac7ed0dfea99f9ee75c64bfb229559d0`.
|
||||
Repeated source build matched the installed artifact and manifest; existing host
|
||||
identity, credentials and journal were retained. The onboard Node installer was
|
||||
not changed and no onboard update was performed in this increment.
|
||||
|
||||
### 0.1.24: exclusive B2 SIM selection
|
||||
|
||||
The same downloadable headless installer now carries durable `select-sim`:
|
||||
configuration preflight/write/readback, one restart and measured DS2 return on
|
||||
the requested SIM. No new port, vendor dependency, system package, identity or
|
||||
permission is introduced. The existing Ubuntu Server 24.04 amd64 installation
|
||||
is upgraded in place; paired identity/state and rollback release are preserved.
|
||||
The mode disables data on the other SIM, and the operator is told this before
|
||||
saving. A failed/uncertain operation is never silently retried.
|
||||
|
||||
### 0.1.25: bound Linux TCP delivery, preserve uncertain outcomes
|
||||
|
||||
`ndc_vps/delivery.py` tracks byte frontiers for every guarded stream write and
|
||||
releases a command's deadline only when the kernel and asyncio queues establish
|
||||
TCP acknowledgement. Monotonic timers abort queued delivery at the earlier of
|
||||
operation expiry and 30 seconds after dispatch (12 seconds for HTTP replies).
|
||||
Per-socket zero linger prevents queued data surviving handler close; user timeout
|
||||
provides an additional Linux bound. No global sysctl/firewall changes. The service
|
||||
keeps separate application confirmation and never replays a dispatched action.
|
||||
|
||||
The shipped `qualify_delivery.py` uses two bounded loopback connections and no
|
||||
tracker or service changes. On Linux 6.8.0-137-generic its blocked receiver reset
|
||||
at 0.751091 seconds for a 0.750-second deadline; healthy acknowledged data did not
|
||||
close the stream. Physical B2 qualification demonstrated the real 30-second
|
||||
failure cutoff without USB; no successful execution is claimed for that sample.
|
||||
See `docs/arnavi_b2/COMMUNICATION_LIMITS.md` for evidence and limitations.
|
||||
|
||||
Session: `delivery-a8d26be666ec4dd182f46a4db8d0c566`. Repeated builds matched:
|
||||
installer SHA-256 `c4af2b646cd4463490a329b10abcb09828a97aea2c688cd76dee2fe105d45ee1`,
|
||||
manifest SHA-256 `68365a1ea42b09dafe353c030a79fb7669fb7631c728ff45e5dc23b15307aad8`.
|
||||
Applied through the existing `.pyz` installer, preserving all four identity/key
|
||||
files and the durable journal. The same artifact is published for download in
|
||||
Core. 154 targeted backend cases, 1004 frontend cases, architecture, typecheck and
|
||||
production build passed. This is an update on the existing supported VPS, not a
|
||||
new clean-OS acceptance or proof of deterministic actuator latency.
|
||||
|
||||
### 0.1.26: durable Core delivery and idle runtime
|
||||
|
||||
Core now persists a private transactional outbox before submitting to this host
|
||||
version. Ambiguous HTTP completion first resolves the original ID; unresolved
|
||||
submission retries the identical body/ID/absolute deadline with bounded backoff.
|
||||
VPS deduplicates the ID and admits expired requests as terminal records without
|
||||
dispatch. A never-dispatched position request may survive VPS restart and await
|
||||
reconnection within its original 30-second lifetime. Dispatched actions still
|
||||
never replay, and effectful operations retain live-session admission.
|
||||
|
||||
The host indexes unfinished commands rather than reading complete history in
|
||||
packet/sender hot paths. Idle senders wait for events; active staged operations
|
||||
retain bounded timers. This is not fleet-scale qualification: the existing
|
||||
256-connection limit and finite receiver storage remain unchanged.
|
||||
|
||||
The shipped `qualify_runtime.py` passed on the existing Ubuntu VPS in 1.144 s
|
||||
using synthetic state only. 204 focused backend and 1004 frontend cases passed,
|
||||
as did lint, architecture, typecheck and build. Three indoor real B2 requests
|
||||
were confirmed in 0.887–2.224 s. Each repeated Core submission retained the same
|
||||
operation; capture proves one application frame per operation, including one
|
||||
TCP retransmission. No tracker settings, outputs, restart or USB serial use.
|
||||
|
||||
Session `runtime-b54eb15f6b1e48d09c687801f7347617`; identical repeated builds and
|
||||
downloaded installer SHA-256:
|
||||
`2433f50ea14b7459f59a8fe1191ff0cb7a197e201b4e7230b651915b43661a50`.
|
||||
Installed with the product installer, all four identity/key files preserved,
|
||||
service active and Core UI accepts 0.1.26. Node installer remains 0.8.45-1.
|
||||
See [runtime contract](../arnavi_b2/WEAK_LINK_RUNTIME.md) and
|
||||
[indoor/outdoor evidence](../arnavi_b2/INDOOR_OUTDOOR_COMPARISON_20260927.md).
|
||||
@@ -0,0 +1,139 @@
|
||||
# Portable VPS state — installer 0.1.35
|
||||
|
||||
The transfer unit is one VPS identity and its entire private journal. It includes
|
||||
TLS identity, Core ownership, registered devices, telemetry/receipt sequencing,
|
||||
maintenance intents, attempt history and stop markers. It excludes executable
|
||||
code, system accounts, unit files, firewall configuration and live TCP sessions.
|
||||
|
||||
## Operator procedure
|
||||
|
||||
Use the exact same qualified `.pyz` on the source and target. First upgrade the
|
||||
source through that installer. On the source:
|
||||
|
||||
```sh
|
||||
sudo python3 mission-core-vps-install.pyz --export-state /root/mission-vps-state.tar.gz
|
||||
```
|
||||
|
||||
Export stops this service and writes a persistent migration fence before taking
|
||||
a consistent SQLite snapshot. It prints the archive's SHA-256. The archive is
|
||||
private mode 0600 and contains keys/tokens; transfer it through the owner's SSH
|
||||
channel, together with the installer. A failure after fencing does not silently
|
||||
restart the source. Its original state remains available.
|
||||
|
||||
On an empty Ubuntu Server 24.04 amd64 installation:
|
||||
|
||||
```sh
|
||||
sudo python3 mission-core-vps-install.pyz --import-state /root/mission-vps-state.tar.gz --sha256 ARCHIVE_SHA256
|
||||
```
|
||||
|
||||
Import checks the complete fixed file set, exact archive and installer digests,
|
||||
TLS key/certificate identity and SQLite integrity before publishing state. It
|
||||
rejects links, path traversal, extra/duplicate/missing members and foreign product
|
||||
paths. A same-filesystem rename exposes the complete state atomically, avoiding
|
||||
a second full-size journal copy. The installer creates code, the system account
|
||||
and the service itself, then checks health. No operator-written service file,
|
||||
chmod, copied runtime or package installation is required on the qualified image.
|
||||
|
||||
Keep the original endpoint and ports. For a DNS endpoint, arrange the DNS move
|
||||
and test public reachability of both ports. Import preserves the TLS identity,
|
||||
so the existing Core credentials continue to work. A literal-IP endpoint needs
|
||||
that IP reassigned or a separate, verified Core/tracker endpoint change; state
|
||||
transfer does not rewrite remote trackers. The current physical test contour
|
||||
uses a literal IP, so an actual address migration has not been performed.
|
||||
|
||||
To cancel migration, stop the target first, then run on the source:
|
||||
|
||||
```sh
|
||||
sudo python3 mission-core-vps-install.pyz --resume-source
|
||||
```
|
||||
|
||||
The source cannot independently prove that a disconnected target is stopped.
|
||||
Do not run both copies simultaneously. A previously exported archive also cannot
|
||||
contain operations accepted after its snapshot. Retain the archive and its exact
|
||||
installer as a pair, along with the corresponding Mission Core fleet state.
|
||||
|
||||
## Recovery semantics
|
||||
|
||||
- The queued operation keeps its ID, desired parameters, ordering and history.
|
||||
- A dispatched attempt without a confirmed result is reconciled by the existing
|
||||
runtime. It is not relabelled as successful because an archive was restored.
|
||||
- A retry uses the original intent and a new attempt; terminal results and stop
|
||||
markers remain in the journal. Original deadlines are not extended by copying.
|
||||
- Live TCP sessions and their liveness are never restored; new tracker input is
|
||||
required by the existing dispatch policy.
|
||||
- Only the source snapshot is authoritative during transfer. This is planned
|
||||
migration/recovery, not automatic multi-host failover or synchronous replication.
|
||||
|
||||
## Reproducible artifact
|
||||
|
||||
- Final installer: `vps-host-0.1.35.pyz`.
|
||||
- SHA-256: `3ed73ffe6b015cc1c39fa5dbcaeb869b8df832ceed2f764fafd06d11de9426ea`.
|
||||
- Payload manifest: `7ff98f60b943b81703873d09ef79cda65be2b4f94872dfbf6b7ac44570ffb78e`.
|
||||
- Tar SHA-256: `e6bc8c19d005355edae6469bb24717a98d921254ea19b25040c6ee064b700c76`.
|
||||
- Two independent source builds produced identical archives.
|
||||
- Candidate 0.1.34 is retained separately; it was never published or installed
|
||||
on the working VPS. Version 0.1.35 additionally makes state publication atomic.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Final 0.1.35 passed both clean-image runs and the working-host upgrade.
|
||||
Private evidence session:
|
||||
`vps-portable-b9714da04a334ceea0f335cb8b31caf1`.
|
||||
|
||||
Unit checks exercise preservation of a dispatched attempt, a queued successor,
|
||||
a stopped-before-submit marker and full database contents. Restoring the runtime
|
||||
retains one interrupted attempt, leaves its parent intent queued, preserves the
|
||||
stopped marker and has no copied live sessions. Failure before state publication
|
||||
leaves no target identity; failure during service installation leaves a complete
|
||||
verified state that the same installer can resume without generating new keys.
|
||||
|
||||
The clean-image substrate uses the official Ubuntu 24.04.5 amd64 root image,
|
||||
SHA-256 `820311e238ea34d76a8ca2643d6c01065212e9417109e7397d70472a236df261`.
|
||||
Each guest has separate mount, PID, network, UTS, IPC and cgroup namespaces,
|
||||
loopback only, 256 MiB memory and 35% CPU. Guests run sequentially. This qualifies
|
||||
clean userspace and service-account creation with the actual installer. It does
|
||||
not qualify another kernel/hypervisor, provider security groups or public DNS.
|
||||
|
||||
Portable state is limited to 2 GiB; import requires 2.25 GiB free staging space.
|
||||
Unknown firewall policies and provider rules remain external. Physical SIM
|
||||
fallback, a blank B2 enrollment using a sound USB cable, and Worker 006 scale
|
||||
tests remain separate gates.
|
||||
|
||||
### Observed results
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Clean source installation | Active/enabled service, generated key, ports 19443/9922 |
|
||||
| Synthetic Core admission | Prior token authenticates; device registered; one offline intent queued |
|
||||
| Repeated install, restart, fresh/restore | Identity and pending job retained where expected |
|
||||
| Export fencing | Service start and ordinary installer cannot bypass the fence |
|
||||
| Explicit abort | Source resumes with same credentials; a new export can be produced |
|
||||
| Empty second Ubuntu import | Service user created by installer; prior four key/identity files exact |
|
||||
| Restored API and restart | Same owner, registered device and queued operation, attempt count zero |
|
||||
| Working VPS 0.1.33 → 0.1.35 | Backup before upgrade; four identity files unchanged; service healthy |
|
||||
| Installed manifest | All 28 files match accepted release |
|
||||
| Real-state export/resume | 658,955-byte private archive; source resumed; total 0.990 s |
|
||||
| Real B2 after resume | Request-position confirmed, code 0, one attempt, 0.831750 s |
|
||||
| Core journal | Same confirmation visible; zero pending operations |
|
||||
| Download from Core | Exact accepted installer hash; UI shows 0.1.35 |
|
||||
| Local validation | 108 distinct focused Python tests, 24 frontend tests, production build passed |
|
||||
|
||||
The reference to 108 Python cases includes the additional archive-size guard
|
||||
test and the two publication-failure cases; repeat runs are not counted twice.
|
||||
The frontend retains its existing large-chunk warning; no map/renderer work is
|
||||
included. The onboard installer remains 0.8.45-1 and no board update ran.
|
||||
|
||||
The actual private recovery files are retained on the owner's VPS under `/root`:
|
||||
`ndc-mission-vps-recovery-0.1.35.pyz` and the session-named `*-state.tar.gz`.
|
||||
The archive is also saved in the private local evidence session as
|
||||
`production-state.private.tar.gz`, SHA-256
|
||||
`1c0b4e2a6abe95d8b26c691b1a788dd08e38e5866ac361d3d8349766b762e162`.
|
||||
This is a snapshot; the source has been explicitly resumed. Stop the source
|
||||
before restoring it elsewhere, and prefer a fresh export for a planned move.
|
||||
|
||||
All four temporary guest units (candidate 0.1.34 and final 0.1.35, source/target)
|
||||
were verified stopped. Their root filesystems and Ubuntu image copies were
|
||||
removed after archiving evidence; approximately 4.32 GB remained free. Private
|
||||
qualification archive SHA-256:
|
||||
`cbf876da07cb987115d88ef93d19232232445ac32d1b1cc1160e2b01d9325571`.
|
||||
The actual production service and canonical Core on 127.0.0.1:8000 remain active.
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a dependency-free, content-addressed VPS release; no private state."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def build(output):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
release = Path(directory) / "ndc-mission-vps"
|
||||
shutil.copytree(
|
||||
ROOT / "apps/vps-host", release, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")
|
||||
)
|
||||
shutil.copyfile(
|
||||
ROOT / "src/k1link/device_plugins/arnavi_b2/internal.py", release / "ndc_vps/arnavi.py"
|
||||
)
|
||||
for name in ("usb_protocol.py", "web_protocol.py", "sim_network.py"):
|
||||
shutil.copyfile(
|
||||
ROOT / "src/k1link/device_plugins/arnavi_b2" / name, release / "ndc_vps" / name
|
||||
)
|
||||
files = {
|
||||
str(p.relative_to(release)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in sorted(release.rglob("*"))
|
||||
if p.is_file()
|
||||
}
|
||||
(release / "manifest.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schema": "missioncore.vps-release/v1",
|
||||
"environment": "ubuntu-24.04-amd64",
|
||||
"files": files,
|
||||
},
|
||||
sort_keys=True,
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
output = Path(output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(output, "w") as archive:
|
||||
for file in sorted(release.rglob("*")):
|
||||
info = archive.gettarinfo(
|
||||
file, arcname="ndc-mission-vps/" + str(file.relative_to(release))
|
||||
)
|
||||
info.uid = info.gid = info.mtime = 0
|
||||
info.uname = info.gname = ""
|
||||
info.mode = 0o755 if file.is_dir() else 0o644
|
||||
if file.is_file():
|
||||
with file.open("rb") as stream:
|
||||
archive.addfile(info, stream)
|
||||
else:
|
||||
archive.addfile(info)
|
||||
installer = output.with_suffix(".pyz")
|
||||
with zipfile.ZipFile(installer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
content = {"__main__.py": (release / "owner_entry.py").read_bytes()}
|
||||
content.update(
|
||||
{
|
||||
"payload/" + str(p.relative_to(release)): p.read_bytes()
|
||||
for p in sorted(release.rglob("*"))
|
||||
if p.is_file()
|
||||
}
|
||||
)
|
||||
for name, value in sorted(content.items()):
|
||||
info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.external_attr = 0o100644 << 16
|
||||
archive.writestr(info, value)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"artifact": str(output),
|
||||
"installer": str(installer),
|
||||
"installer_sha256": hashlib.sha256(installer.read_bytes()).hexdigest(),
|
||||
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
"manifest_sha256": hashlib.sha256(
|
||||
(release / "manifest.json").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", required=True)
|
||||
build(parser.parse_args().output)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Archive a local firmware file without contacting or flashing any device."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.device_plugins.arnavi_b2.firmware import KNOWN_IMAGES
|
||||
from k1link.fleet.equipment_firmware import FirmwareArchive
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--fleet-root", required=True, type=Path)
|
||||
parser.add_argument("--file", required=True, type=Path)
|
||||
parser.add_argument("--filename")
|
||||
args = parser.parse_args()
|
||||
store = FirmwareArchive(args.fleet_root, {"arnavi-b2": KNOWN_IMAGES})
|
||||
item = store.add("arnavi-b2", args.filename or args.file.name, args.file.read_bytes())
|
||||
print(json.dumps(item, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish an externally qualified installer with an explicit accepted checksum."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--fleet-root", type=Path, required=True)
|
||||
parser.add_argument("--file", type=Path, required=True)
|
||||
parser.add_argument("--sha256", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--kind", choices=("node", "vps-arnavi"), required=True)
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9]+)?", args.version):
|
||||
raise ValueError("Invalid release version")
|
||||
with args.file.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != args.sha256 or args.file.suffix != ".pyz":
|
||||
raise ValueError("Qualified installer checksum mismatch")
|
||||
root = args.fleet_root / "installers"
|
||||
root.mkdir(mode=0o700, exist_ok=True)
|
||||
name = f"{args.kind}-{args.version}-{digest[:12]}.pyz"
|
||||
target = root / name
|
||||
temporary = root / (name + ".new")
|
||||
shutil.copyfile(args.file, temporary)
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, target)
|
||||
vps = args.kind == "vps-arnavi"
|
||||
value = {
|
||||
"id": args.kind,
|
||||
"filename": name,
|
||||
"version": args.version,
|
||||
"label": "VPS Host ARNavi" if vps else "Бортовой компьютер",
|
||||
"os": "Ubuntu Server 24.04 LTS · x86-64" if vps else "Ubuntu 24.04 LTS · x86-64 · GNOME",
|
||||
"bytes": target.stat().st_size,
|
||||
"sha256": digest,
|
||||
"instructions": [
|
||||
"Скопируйте файл на VPS. Запустите: sudo python3 mission-core-vps-install.pyz"
|
||||
if vps
|
||||
else "Перенесите файл на бортовой ПК. Откройте окно установки: "
|
||||
"python3 mission-core-node-install.pyz --launch",
|
||||
"Укажите публичный адрес сервера; дождитесь завершения установки."
|
||||
if vps
|
||||
else "Завершите установку и откройте Node.",
|
||||
"Скопируйте ключ подключения VPS в поле ниже."
|
||||
if vps
|
||||
else "Создайте в Node код приглашения и вставьте его в поле ниже.",
|
||||
],
|
||||
}
|
||||
temporary = root / (args.kind + ".json.new")
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, root / (args.kind + ".json"))
|
||||
print(json.dumps({"published": args.kind, "version": args.version, "sha256": digest}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user