/** Bounded, local-only CSV analysis. Formats follow pinned Tool 7.00 * VescInterface::openRtLogFile and PageLogAnalysis::openLog/saveCsv. */ export const LOG_MAX_BYTES=4*1024*1024,LOG_MAX_ROWS=20000,LOG_MAX_COLUMNS=96; export interface LogColumn {key:string;label:string;unit:string} export interface LogPoint {at:number;values:Record;gap:boolean} export interface VescLog {format:string;columns:LogColumn[];points:LogPoint[];duration:number;uuid:string|null;hardware:string|null;firmware:string|null} const raw:Record={input_voltage:['Напряжение питания','В'],temp_mos_max:['Температура контроллера','°C'],temp_motor:['Температура мотора','°C'],current_motor:['Ток мотора','А'],current_in:['Ток питания','А'],erpm:['Электрические обороты','ERPM'],duty_cycle:['Заполнение PWM','%'],d_axis_current:['Ток FOC d','А'],q_axis_current:['Ток FOC q','А'],d_axis_voltage:['Напряжение FOC d','В'],q_axis_voltage:['Напряжение FOC q','В'],amp_hours_used:['Расход заряда','А·ч'],amp_hours_charged:['Возвращённый заряд','А·ч'],watt_hours_used:['Расход энергии','Вт·ч'],watt_hours_charged:['Возвращённая энергия','Вт·ч'],encoder_position:['Положение ротора','°'],fault_code:['Код ошибки','']}; const fail=(message:string):never=>{throw new Error(message);}; export function csvRecords(text:string,delimiter:string):string[][] { const records:string[][]=[];let row:string[]=[],cell='',quoted=false,closed=false; function field(){row.push(cell);cell='';closed=false;if(row.length>LOG_MAX_COLUMNS)fail('Слишком много колонок журнала.');} function record(){field();if(row.some(v=>v!==''))records.push(row);row=[];if(records.length>LOG_MAX_ROWS+1)fail('Журнал превышает 20 000 строк.');} for(let i=0;i4096)fail('Поле журнала слишком длинное.'); } if(quoted)fail('Незакрытые кавычки CSV.'); if(cell||row.length||closed)record();return records; } const numeric=(text:string,line:number):number|null=>{ if(text.trim()==='')return null; if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text.trim()))return fail(`Нечисловое значение в строке ${line}.`); const n=Number(text);if(!Number.isFinite(n)||Math.abs(n)>1e15)fail(`Значение вне диапазона в строке ${line}.`);return n; }; export function parseVescLog(source:string):VescLog { if(source.length>LOG_MAX_BYTES||new TextEncoder().encode(source).length>LOG_MAX_BYTES)fail('Максимальный размер CSV — 4 МиБ.'); const text=source.replace(/^\uFEFF/,''); const first=text.split(/\r?\n/,1)[0]; const delimiter=first.includes(';')?';':','; const records=csvRecords(text,delimiter); if(records.length<2)fail('В журнале нет измерений.'); // Native Tool logs terminate every row with a semicolon. if(records.every(row=>row.at(-1)===''))records.forEach(row=>row.pop()); const header=records[0];if(new Set(header).size!==header.length||header.some(h=>!h))fail('Пустые или повторяющиеся заголовки CSV.'); if(header[0]==='T')return parseSampleCsv(records); const core=header[0]==='plot_elapsed_s',rt=header[0]==='ms_today',rich=!core&&!rt&&header[0].includes(':'); if(!core&&!rt&&!rich)fail('Поддерживаются CSV Mission Core и журналы VESC Tool.'); const meta=header.map(h=>h.split(':')); const time=core||rt?0:meta.findIndex(h=>h[0]==='t_day'); const timeIndex=time>=0?time:meta.findIndex(h=>h[5]==='1'); if(timeIndex<0)fail('В журнале не указана временная колонка.'); if(rich&&!['s','ms','сек','с',''].includes(meta[timeIndex][2]??''))fail('Единица временной колонки должна быть s или ms.'); const timeScale=rt||(rich&&meta[timeIndex][2]==='ms')?1:1000; const index=(key:string)=>header.indexOf(key); const stateIndex=index('state'),sessionIndex=index('usb_session'),sourceIndex=index('source_instance'),uuidIndex=index('uuid'); if(core&&[stateIndex,sessionIndex,sourceIndex,uuidIndex,index('sample_utc')].some(v=>v<0))fail('В CSV Mission Core отсутствуют сведения об источнике.'); const columns:LogColumn[]=[],indices:number[]=[]; header.forEach((h,i)=>{ if(i===timeIndex||core&&!h.includes(' ['))return; const parts=meta[i],key=rich?parts[0]:h; if(rich&&parts[5]==='1')return; const match=core?/^(.*) \[(.*)\]$/.exec(h):null; columns.push({key,label:rich?parts[1]||key:match?.[1]??raw[key]?.[0]??key,unit:rich?parts[2]??'':match?.[2]??raw[key]?.[1]??''});indices.push(i); }); if(!columns.length||new Set(columns.map(c=>c.key)).size!==columns.length)fail('Журнал не содержит однозначных числовых колонок.'); const identities=new Set(),canIds=new Set();let session='',previous=-Infinity,offset=0,start:number|undefined; const points:LogPoint[]=[]; for(let i=1;i=86400000)fail('Время ms_today выходит за пределы суток.'); let at=clock!*timeScale+offset,rollover=false; if(at18*3600000&&clock!<6*3600000){offset+=86400000;at+=86400000;rollover=true;}else fail(`Время идёт назад в строке ${i+1}.`);} if(start===undefined)start=at; const identity=core?row[uuidIndex]:'';if(identity)identities.add(identity.toLowerCase()); const canIndex=index('vesc_id');if(rt&&canIndex>=0)canIds.add(row[canIndex]); if(identities.size>1||canIds.size>1)fail('Журнал содержит разные контроллеры. Выберите журнал одного VESC.'); const nextSession=core?row[sourceIndex]+'/'+row[sessionIndex]:''; if(core&&!['sample','gap'].includes(row[stateIndex]))fail(`Неизвестное состояние строки ${i+1}.`); const gap=core&&row[stateIndex]==='gap'; if(rollover||(session&&session!==nextSession))points.push({at:at-start!,values:{},gap:true}); const values:Record={}; columns.forEach((column,c)=>{let value=numeric(row[indices[c]],i+1);if(rt&&column.key==='duty_cycle'&&value!==null)value*=100;values[column.key]=gap?null:value;}); points.push({at:at-start!,values,gap});session=nextSession;previous=at; } if(!points.some(p=>Object.values(p.values).some(v=>v!==null)))fail('В журнале нет числовых измерений.'); const unique=(key:string)=>{const n=index(key);if(n<0)return null;const values=new Set(records.slice(1).map(row=>row[n]).filter(Boolean));return values.size===1?[...values][0]:null;}; return {format:core?'Mission Core':rt?'VESC Tool · RT':'VESC Tool · Log Analysis',columns,points,duration:points.at(-1)!.at,uuid:unique('uuid'),hardware:unique('hardware'),firmware:unique('firmware')}; } function parseSampleCsv(records:string[][]):VescLog { const expected=['T','I1','I2','I3','V1','V2','V3','I_tot','V_zero','Phase']; const header=records[0];if(expected.some((key,i)=>header[i]!==key)||header.slice(10).some(key=>!['Hall','Commutation','F_sw'].includes(key)))fail('Неизвестные колонки Sample Data.'); if(records.length>2001)fail('Sample Data превышает 2000 отсчётов.'); const labels:Record={I1:['Ток фазы 1','А'],I2:['Ток фазы 2','А'],I3:['Ток фазы 3','А'],V1:['Напряжение фазы 1','В'],V2:['Напряжение фазы 2','В'],V3:['Напряжение фазы 3','В'],I_tot:['Ток мотора','А'],V_zero:['Нулевая точка','В'],Phase:['Угол фазы (электрический)','°'],Hall:['Состояние Холла',''],Commutation:['Шаг коммутации',''],F_sw:['Частота до делителя','Гц']}; const columns=header.slice(1).map(key=>({key,label:labels[key][0],unit:labels[key][1]})); let previous=-1,start:number|undefined; const points=records.slice(1).map((row,i)=>{ // Tool 7.00 adds a trailing delimiter to data rows, but not the header. if(row.length===header.length+1&&row.at(-1)==='')row=row.slice(0,-1); if(row.length!==header.length)fail(`Число колонок изменилось в строке ${i+2}.`); const seconds=numeric(row[0],i+2);if(seconds===null||seconds<0||seconds<=previous)return fail('Неверное время Sample Data.'); start??=seconds;previous=seconds; return {at:(seconds-start)*1000,values:Object.fromEntries(columns.map((c,j)=>[c.key,numeric(row[j+1],i+2)])),gap:false}; }); return {format:'VESC Tool · Sample Data',columns,points,duration:points.at(-1)!.at,uuid:null,hardware:null,firmware:null}; } export function spectrum(points:readonly LogPoint[],key:string,from:number,to:number){ const selected=points.filter(p=>p.at>=from&&p.at<=to); if(selected.length<32)fail('Для спектра нужно не менее 32 измерений.'); const n=2**Math.floor(Math.log2(Math.min(selected.length,4096))),data=selected.slice(-n); if(data.some(p=>p.gap||p.values[key]===null||p.values[key]===undefined))fail('В выбранном участке есть пропуски. Выберите непрерывный интервал.'); const dt=(data.at(-1)!.at-data[0].at)/(n-1); if(!(dt>0)||data.some((p,i)=>i>0&&Math.abs(p.at-data[i-1].at-dt)>dt*.01))fail('Шаг времени неравномерен. Спектр требует равномерных измерений (допуск 1%).'); const real=new Float64Array(n),imag=new Float64Array(n); const mean=data.reduce((sum,p)=>sum+p.values[key]!/n,0);let gain=0; for(let i=0;i>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i({hz:i*rate/n,amplitude:Math.hypot(real[i],imag[i])*(i===0||i===n/2?1:2)/gain})); const peak=bins.slice(1).reduce((best,v)=>v.amplitude>best.amplitude?v:best,bins[1]); return {bins,rate,n,from:data[0].at,to:data.at(-1)!.at,peak}; }