Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
62 lines
5.0 KiB
TypeScript
62 lines
5.0 KiB
TypeScript
/** Projection of the original terminal reports. Never guesses missing fields. */
|
|
export interface DiagnosticRead {
|
|
device_id:string; identity:{uuid:string;version:string;hardware:string}; observed_at:string;
|
|
usb:Record<string,string|null>; reports:Record<string,{command:string;text:string;completion:string}>;
|
|
}
|
|
export interface FaultEntry {code:string;fields:Record<string,string>}
|
|
export interface DiagnosticSnapshot {
|
|
read:DiagnosticRead; session:string; received:number; monotonic:number;
|
|
configEvents:number|null; writeTimeouts:number|null; offsets:number[]|null;
|
|
faults:{state:'none'|'reported'|'unknown';entries:FaultEntry[]}; identityMatches:boolean;
|
|
}
|
|
const LIMIT=64*1024;
|
|
const MAX_AGE=300000;
|
|
function unique(text:string,label:string):string|null {
|
|
const values=text.split(/\r?\n/).map(line=>line.match(/^\s*([^:]+?)\s*:\s*(.*?)\s*$/)).filter(row=>row?.[1]===label);
|
|
return values.length===1?values[0]![2]:null;
|
|
}
|
|
function counter(text:string,label:string):number|null {
|
|
const v=unique(text,label);if(v===null||!/^\d{1,10}$/.test(v))return null;
|
|
const n=Number(v);return n<=0xffffffff?n:null;
|
|
}
|
|
export function parseFaults(text:string):DiagnosticSnapshot['faults'] {
|
|
if(text.length>LIMIT)return {state:'unknown',entries:[]};
|
|
const entries:FaultEntry[]=[];let current:FaultEntry|null=null;
|
|
for(const line of text.split(/\r?\n/)){
|
|
const match=line.match(/^\s*([^:]+?)\s*:\s*(.*?)\s*$/);if(!match)continue;
|
|
const [,key,value]=match;
|
|
if(key==='Fault'){
|
|
if(!/^FAULT_CODE_[A-Z0-9_]{1,80}$/.test(value)||entries.length>=64)return {state:'unknown',entries:[]};
|
|
current={code:value,fields:Object.create(null) as Record<string,string>};entries.push(current);
|
|
}else if(current&&key.length<=80&&value.length<=256){current.fields[key]=value;}
|
|
}
|
|
const none=text.trim()==='No faults registered since startup';
|
|
return {state:entries.length?'reported':none?'none':'unknown',entries};
|
|
}
|
|
export function diagnosticSnapshot(read:DiagnosticRead,session:string,received=Date.now(),monotonic=performance.now()):DiagnosticSnapshot {
|
|
if(!read||typeof read.observed_at!=='string'||!Number.isFinite(Date.parse(read.observed_at))||!read.identity||!read.device_id||!session||!read.usb||!read.reports)throw new Error('Неполный ответ диагностики.');
|
|
for(const name of ['hw_status','faults']){
|
|
const report=read.reports[name];if(!report||report.command!==name||typeof report.text!=='string'||report.text.length>LIMIT)throw new Error('Неполный или слишком большой ответ диагностики.');
|
|
}
|
|
const text=read.reports.hw_status.text,uuid=unique(text,'UUID')?.replace(/\s/g,'').toLowerCase();
|
|
const identityMatches=!!uuid&&/^[0-9a-f]{24}$/.test(uuid)&&uuid===read.identity.uuid.toLowerCase();
|
|
const rawOffsets=unique(text,'FOC Current Offsets');
|
|
const offsets=rawOffsets&&/^\d{1,6}\s+\d{1,6}\s+\d{1,6}$/.test(rawOffsets)?rawOffsets.split(/\s+/).map(Number):null;
|
|
return {read,session,received,monotonic,identityMatches,configEvents:counter(text,'USB config events'),writeTimeouts:counter(text,'USB write timeouts'),offsets,faults:parseFaults(read.reports.faults.text)};
|
|
}
|
|
export function diagnosticExpired(snapshot:DiagnosticSnapshot,wall=Date.now(),mono=performance.now()):boolean {
|
|
return wall<snapshot.received||mono<snapshot.monotonic||mono-snapshot.monotonic>=MAX_AGE||wall-snapshot.received>=MAX_AGE||new Date(wall).toISOString().slice(0,10)!==new Date(snapshot.received).toISOString().slice(0,10);
|
|
}
|
|
export function compareDiagnostics(before:DiagnosticSnapshot,after:DiagnosticSnapshot):{reason:string|null;configEvents:number|null;writeTimeouts:number|null} {
|
|
let reason:string|null=null;
|
|
if(!before.identityMatches||!after.identityMatches)reason='UUID в ответе hw_status не подтверждён.';
|
|
else if(before.read.device_id!==after.read.device_id||before.read.identity.uuid.toLowerCase()!==after.read.identity.uuid.toLowerCase())reason='Выбраны разные контроллеры.';
|
|
else if(before.session!==after.session)reason='USB-сеанс изменился.';
|
|
else if(before.read.identity.version!==after.read.identity.version||before.read.identity.hardware!==after.read.identity.hardware)reason='Изменилась прошивка или аппаратный профиль.';
|
|
else if(after.monotonic<=before.monotonic||Date.parse(after.read.observed_at)<=Date.parse(before.read.observed_at))reason='Нужен более поздний снимок.';
|
|
else if(diagnosticExpired(before,after.received,after.monotonic))reason='Срок сравнения истёк.';
|
|
else if(([['configEvents'],['writeTimeouts']] as const).some(([key])=>before[key]!==null&&after[key]!==null&&after[key]!<before[key]!))reason='Счётчик уменьшился: возможен сброс или переполнение. Разность не вычисляется.';
|
|
const delta=(key:'configEvents'|'writeTimeouts')=>reason||before[key]===null||after[key]===null?null:after[key]!-before[key]!;
|
|
return {reason,configEvents:delta('configEvents'),writeTimeouts:delta('writeTimeouts')};
|
|
}
|