feat(vesc): extend motor diagnostics, configuration and transport recovery

Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent 115476d2e6
commit f32c7b400b
186 changed files with 21197 additions and 339 deletions
@@ -0,0 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/bmsView.ts',import.meta.url),'utf8');
const {bmsCellSummary,bmsCells,bmsTemperature,bmsCanOptions,bmsNumber}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('BMS cell spread preserves missing values and actual balancing state',()=>{
assert.equal(bmsCellSummary({v_cells:[]}),null);
assert.equal(bmsCellSummary({v_cells:[3.7,null]}),null);
const summary=bmsCellSummary({v_cells:[3.7,3.8,3.75]});assert.ok(Math.abs(summary.spreadMv-100)<1e-8);
assert.deepEqual(bmsCells({v_cells:[3.7,NaN],is_balancing:[true]}),[{index:0,voltage:3.7,balancing:true},{index:1,voltage:null,balancing:null}]);
assert.equal(bmsCells({v_cells:Array(200).fill(3.7)}).length,96);
});
test('BMS does not turn missing readings or temperature sentinels into zero',()=>{
assert.equal(bmsNumber(undefined),'Не сообщается');assert.equal(bmsNumber(NaN),'Не сообщается');assert.equal(bmsNumber(0),'0');
assert.equal(bmsTemperature(-280),'Не сообщается');assert.equal(bmsTemperature(-300),'Не сообщается');assert.notEqual(bmsTemperature(0),'Не сообщается');
});
test('BMS CAN target selection cannot broadcast and stays unique',()=>{
assert.deepEqual(bmsCanOptions([253,0,0,255,254,-1,NaN,'12',true,1.5]),[{value:'0',label:'CAN 0'},{value:'253',label:'CAN 253'}]);
});
@@ -0,0 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/editorFiles.ts',import.meta.url),'utf8');
const {validateProject,bytesBase64}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('Lisp project export preserves binary imports and UTF-8 source',()=>{
const input={kind:'lisp',source:'(print "проверка")',imports:{'data.bin':bytesBase64(Uint8Array.from([0,255,1]))},fullscreen:false};
assert.deepEqual(validateProject(JSON.parse(JSON.stringify(input)),'lisp'),input);
assert.equal(atob(input.imports['data.bin']).charCodeAt(1),255);
});
test('code import rejects wrong kind, oversized source and unsafe attachment names',()=>{
const p={kind:'lisp',source:'(+ 1 2)',imports:{},fullscreen:false};
for(const value of [{...p,kind:'qml'},{...p,source:'x'.repeat(122881)},{...p,source:'x\0y'}, {...p,imports:{'../secret':'YQ=='}},{...p,imports:{'/secret':'YQ=='}},{...p,imports:{'a.bin':'!'}},{...p,imports:Array(2)}]) assert.throws(()=>validateProject(value,'lisp'));
assert.throws(()=>validateProject({...p,kind:'qml',imports:{'a.bin':'YQ=='}},'qml'));
});
@@ -0,0 +1,63 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const bundled=await build({stdin:{contents:`export {useVescRead} from '../../plugins/vesc/frontend/src/useVescRead';
export {useVescEditor} from '../../plugins/vesc/frontend/src/useVescEditor';`,resolveDir:process.cwd(),loader:'ts'},
bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'react-fixture',setup(b){
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});
export const useEffect=f=>f();export const useState=v=>{const i=globalThis.vescFixture.index++;
return [i===0&&globalThis.vescFixture.preview?globalThis.vescFixture.preview:v,
next=>globalThis.vescFixture.writes.push(next)];};`}));
}}]});
const {useVescRead,useVescEditor}=await import('data:text/javascript;base64,'+Buffer.from(bundled.outputFiles[0].contents).toString('base64'));
async function fixture(run,{delay=45000,outcome='complete',preview=null}={}){
const oldNow=Date.now,oldTimeout=globalThis.setTimeout,oldFixture=globalThis.vescFixture;
let now=1000000;Date.now=()=>now;globalThis.setTimeout=f=>{now+=1000;queueMicrotask(f);return 0;};
const state={index:0,writes:[],preview};globalThis.vescFixture=state;
const submitted=[],polled=[],errors=[],result={verified:true,preview_id:'cfg_synthetic'};
const props={enabled:true,blocked:false,onBusyChange:()=>{},failure:e=>{if(e)errors.push(e);},refresh:async()=>{},
device:{id:'synthetic',online:true,verified:true,snapshot:{context:{session_id:'attachment'}},
vesc_status:{readable:true,configuration_edit_supported:true}},
transport:{submit:async c=>{submitted.push(c);now+=delay;return {state:'queued'};},
operation:async id=>{polled.push(id);return {state:outcome,result};}}};
try{await run({props,submitted,polled,errors,state,result});}
finally{Date.now=oldNow;globalThis.setTimeout=oldTimeout;
if(oldFixture===undefined)delete globalThis.vescFixture;else globalThis.vescFixture=oldFixture;}
}
test('configuration read survives a paced delivery longer than the former 30 second budget',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.configuration.read').read();
assert.deepEqual(f.errors,[]);assert.ok(f.state.writes.includes(f.result));
assert.equal(f.submitted.length,1);assert.deepEqual(f.polled,[f.submitted[0].operation_id]);
assert.equal(Date.parse(f.submitted[0].deadline_at)-Date.parse(f.submitted[0].requested_at),180000);
}));
test('ordinary telemetry reads retain their short budget',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.telemetry.read').read();
assert.equal(f.submitted.length,1);assert.equal(f.errors.length,1);assert.deepEqual(f.polled,[]);
assert.equal(Date.parse(f.submitted[0].deadline_at)-Date.parse(f.submitted[0].requested_at),30000);
}));
test('preview and reconciliation use the configuration delivery budget',async()=>{
for(const method of ['prepare','reconcile'])await fixture(async f=>{
await useVescEditor(f.props)[method]({kind:'motor',changes:{l_current_max:100}});
assert.deepEqual(f.errors,[]);assert.equal(f.submitted.length,1);assert.ok(f.state.writes.includes(f.result));
});
});
test('apply waits for its own late receipt without resending a write',async()=>fixture(async f=>{
await useVescEditor(f.props).apply();
assert.deepEqual(f.errors,[]);assert.equal(f.submitted.length,1);
assert.equal(f.submitted[0].action_id,'vesc.configuration.apply');
assert.deepEqual(f.submitted[0].parameters,{preview_id:'cfg_synthetic',rig_clear:true,inputs_isolated:true});
assert.deepEqual(f.polled,[f.submitted[0].operation_id]);assert.ok(f.state.writes.includes(f.result));
},{delay:75000,preview:{preview_id:'cfg_synthetic'}}));
test('unknown apply result stays unconfirmed and never resubmits the write',async()=>fixture(async f=>{
await useVescEditor(f.props).apply();
assert.equal(f.errors.length,1);assert.equal(f.submitted.length,1);
assert.equal(f.state.writes.includes(f.result),false);
},{outcome:'unknown',preview:{preview_id:'cfg_synthetic'}}));
test('configuration wait is bounded',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.configuration.read').read();
assert.equal(f.errors.length,1);assert.equal(f.submitted.length,1);assert.deepEqual(f.polled,[]);
},{delay:191000}));
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/controlTransport.ts',import.meta.url),'utf8');
const {routeError,transportMode}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
const drive={layout:'1x1',revision:1,bindings:{'left.1':{device_id:'left',uuid:'1'.repeat(24)},'right.1':{device_id:'right',uuid:'2'.repeat(24)}}};
const usb={left:{kind:'usb',uuid:'1'.repeat(24)},right:{kind:'usb',uuid:'2'.repeat(24)}};
const can={...usb,left:{...usb.left,kind:'can',adapter_id:'usbcan_'+'a'.repeat(32),channel:0,can_id:74,bitrate:500000}};
test('selection distinguishes uniform and mixed transport',()=>{
assert.equal(transportMode(usb),'usb');assert.equal(transportMode(can),'mixed');assert.equal(routeError(can,drive),null);
});
test('CAN requires an explicit address and binding',()=>{
assert.ok(routeError({...can,left:{...can.left,can_id:-1}},drive));
assert.ok(routeError({...can,left:{...can.left,can_id:255}},drive));
assert.ok(routeError({...can,left:{...can.left,uuid:'3'.repeat(24)}},drive));
});
test('same address is permitted only on independent channels',()=>{
const both={...can,right:{...can.left,uuid:usb.right.uuid}};
assert.ok(routeError(both,drive));both.right.channel=1;assert.equal(routeError(both,drive),null);assert.equal(transportMode(both),'can');
});
test('one physical CAN bus cannot have two bitrates',()=>{
assert.ok(routeError({...can,right:{...can.left,uuid:usb.right.uuid,can_id:111,bitrate:250000}},drive));
});
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,diagnostics;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});diagnostics=await server.ssrLoadModule('../../plugins/vesc/frontend/src/diagnosticReview.ts');});
after(async()=>{await server?.close();});
const uuid='00112233445566778899aabb';
const report=(events=1,timeouts=0)=>({device_id:'synthetic-controller',identity:{uuid,version:'5.02',hardware:'SYNTHETIC'},observed_at:'2026-10-18T10:00:00Z',usb:{port:'1-2',serial:'not-unique'},reports:{hw_status:{command:'hw_status',completion:'200ms-print-quiescence',text:`Firmware: 5.2\nHardware: SYNTHETIC\nUUID: 00 11 22 33 44 55 66 77 88 99 AA BB\nFOC Current Offsets: 2048 2049 2050\nUSB config events: ${events}\nUSB write timeouts: ${timeouts}\n `},faults:{command:'faults',completion:'200ms-print-quiescence',text:'No faults registered since startup\n'}}});
const time=Date.parse('2026-10-18T10:00:00Z');
const snap=(r=report(),offset=0,session='usb-1')=>{r.observed_at=new Date(time+offset).toISOString();return diagnostics.diagnosticSnapshot(r,session,time+offset,1000+offset);};
test('native hw_status grammar preserves UUID, counter zero and current offsets',()=>{const s=snap();assert.equal(s.identityMatches,true);assert.equal(s.configEvents,1);assert.equal(s.writeTimeouts,0);assert.deepEqual(s.offsets,[2048,2049,2050]);assert.equal(s.faults.state,'none');});
test('missing, duplicate, signed, overflowing and malformed counters never become zero',()=>{
for(const value of ['', '-1', 'NaN', '1.5', '4294967296', '1 extra']){const r=report(value);assert.equal(snap(r).configEvents,null);}
const r=report();r.reports.hw_status.text+='\nUSB config events: 1';assert.equal(snap(r).configEvents,null);
r.reports.hw_status.text='partial';const s=snap(r);assert.equal(s.configEvents,null);assert.equal(s.writeTimeouts,null);assert.equal(s.offsets,null);assert.equal(s.identityMatches,false);
});
test('comparison uses only matching controller identity, firmware and USB session',()=>{
const a=snap(),b=snap(report(3,2),10000);assert.deepEqual(diagnostics.compareDiagnostics(a,b),{reason:null,configEvents:2,writeTimeouts:2});
for(const mutate of [b=>b.session='usb-2',b=>b.read.device_id='other',b=>b.read.identity.uuid='ff'.repeat(12),b=>b.read.identity.version='6.00',b=>b.read.identity.hardware='other',b=>b.identityMatches=false]){const b=snap(report(3,2),10000);mutate(b);const d=diagnostics.compareDiagnostics(a,b);assert.ok(d.reason);assert.equal(d.configEvents,null);assert.equal(d.writeTimeouts,null);}
});
test('counter decrease invalidates all deltas and never proves a reboot',()=>{const a=snap(report(4,3)),b=snap(report(1,5),10000),d=diagnostics.compareDiagnostics(a,b);assert.match(d.reason,/возможен/);assert.equal(d.configEvents,null);assert.equal(d.writeTimeouts,null);});
test('no subtraction across unordered, expired or next-day snapshots',()=>{
const a=snap();for(const b of [snap(),snap(report(),-1),snap(report(),300000)])assert.ok(diagnostics.compareDiagnostics(a,b).reason);
const r=report();r.observed_at='2026-10-18T23:59:59Z';const a2=diagnostics.diagnosticSnapshot(r,'usb-1',Date.parse(r.observed_at),100);r.observed_at='2026-10-19T00:00:01Z';const b2=diagnostics.diagnosticSnapshot(r,'usb-1',Date.parse(r.observed_at),2100);assert.ok(diagnostics.compareDiagnostics(a2,b2).reason);
});
test('expiry uses both monotonic and wall clocks, UTC day and backward jumps',()=>{const s=snap();assert.equal(diagnostics.diagnosticExpired(s,time+299999,300999),false);for(const [wall,mono] of [[time+300000,301000],[time+1,301000],[time-1,1001],[time+1,999],[time+86400000,1001]])assert.equal(diagnostics.diagnosticExpired(s,wall,mono),true);});
test('fault log keeps separate repeated fault entries and unknown fields, not a current fault',()=>{
const f=diagnostics.parseFaults('The following faults were registered since start:\nFault : FAULT_CODE_ABS_OVER_CURRENT\nMotor : 1\nCurrent : 82.3\nRPM : 140\nFuture field : unknown\n\nFault : FAULT_CODE_ABS_OVER_CURRENT\nCurrent : 90.1\n');
assert.equal(f.state,'reported');assert.equal(f.entries.length,2);assert.equal(f.entries[0].fields.Current,'82.3');assert.equal(f.entries[1].fields.Current,'90.1');assert.equal(f.entries[0].fields['Future field'],'unknown');
});
test('empty, truncated or unknown faults are not a clean bill of health',()=>{for(const text of ['','No faults','Fault : bad','Firmware failure','x'.repeat(65537),'Fault : FAULT_CODE_X\n'.repeat(65)])assert.equal(diagnostics.parseFaults(text).state,'unknown');});
test('bad report envelopes and oversized input are rejected',()=>{
for(const mutate of [r=>delete r.reports.hw_status,r=>r.reports.hw_status.command='faults',r=>r.reports.faults.text='x'.repeat(65537),r=>r.observed_at='bad']){const r=report();mutate(r);assert.throws(()=>diagnostics.diagnosticSnapshot(r,'usb-1'));}
});
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/firmwareFiles.ts',import.meta.url),'utf8');
const {firmwareFileError}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('older engines do not offer HEX; supported files stay bounded before browser allocation',()=>{
assert.ok(firmwareFileError({name:'firmware.hex',size:1000},'firmware',['bin']));
assert.equal(firmwareFileError({name:'firmware.HEX',size:8*1024*1024},'firmware',['bin','hex']),null);
assert.ok(firmwareFileError({name:'firmware.hex',size:8*1024*1024+1},'firmware',['bin','hex']));
assert.ok(firmwareFileError({name:'firmware.zip',size:1000},'firmware',['bin','hex']));
assert.ok(firmwareFileError({name:'boot.bin',size:65537},'bootloader',['bin','hex']));
assert.equal(firmwareFileError({name:'boot.hex',size:100000},'bootloader',['bin','hex']),null);
assert.ok(firmwareFileError({name:'empty.bin',size:0},'firmware',['bin','hex']));
});
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,h;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});h=await server.ssrLoadModule('../../plugins/vesc/frontend/src/hallInputs.ts');});
after(async()=>{await server?.close();});
const config=(values)=>({configuration:{motor:{parameters:Object.entries(values).map(([name,value])=>({name,value,type:'integer',editor_scale:1}))}}});
test('Hall selected in FOC is configuration intent, never sensor presence or zero edges',()=>{
const v=h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:0,foc_sensor_mode:2}));
assert.equal(v.use,'Холлы выбраны в настройках FOC');assert.deepEqual(v.inputs,[null,null,null]);assert.deepEqual(v.transitions,[null,null,null]);
});
test('Sensorless and a repaired contact cannot imply either disconnected or working',()=>{
const v=h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:0,foc_sensor_mode:0}));
assert.equal(v.use,'Холлы не выбраны в настройках FOC');assert.deepEqual(v.inputs,[null,null,null]);
});
test('missing config or a different motor/port never confirms Hall use',()=>{
assert.equal(h.hallConfiguration(null).use,'Не прочитано');
assert.equal(h.hallConfiguration(config({motor_type:0,m_sensor_port_mode:0,foc_sensor_mode:2})).use,'См. параметры выбранного типа мотора');
assert.equal(h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:1,foc_sensor_mode:2})).use,'Холлы не выбраны в настройках FOC');
});
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,log,trends,plot,telemetry;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');trends=await server.ssrLoadModule('../../plugins/vesc/frontend/src/trends.ts');plot=await server.ssrLoadModule('../../plugins/vesc/frontend/src/SignalPlot.tsx');telemetry=await server.ssrLoadModule('./src/components/rover/RoverTelemetry.tsx');});
after(async()=>{await server?.close();});
const rt=(rows)=>'ms_today;input_voltage;current_motor;duty_cycle;vesc_id;\n'+rows.map(r=>r.join(';')+';').join('\n');
test('original RT CSV preserves measured zero/missing values and converts PWM only once',()=>{
const v=log.parseVescLog(rt([[100,48,0,.5,1],[200,47,'',0,1]]));
assert.equal(v.format,'VESC Tool · RT');assert.equal(v.duration,100);assert.equal(v.points[0].values.duty_cycle,50);assert.equal(v.points[1].values.current_motor,null);
assert.equal(v.uuid,null);assert.equal(v.columns[0].unit,'В');
});
test('original rich Log Analysis headers retain arbitrary columns, units and missing cells',()=>{
const v=log.parseVescLog('t_day:Time:s:3:1:1;custom:Signal:A:2:0:0\n2;1\n2.1;\n2.2;3\n');
assert.equal(v.columns[0].label,'Signal');assert.equal(v.columns[0].unit,'A');assert.equal(v.points[1].values.custom,null);assert.ok(Math.abs(v.duration-200)<1e-8);
});
test('Mission Core exported CSV round-trips measured units, metadata, escaped CSV and session gaps',()=>{
const p=[{at:10,source:'a',session:'one',sample:1,utc:'2026-10-18T01:00:00Z',values:{duty:20,input_voltage_v:48}},{at:20,source:'a',session:'one',sample:2,utc:'',values:null},{at:30,source:'b',session:'two',sample:3,utc:'2026-10-18T01:00:01Z',values:{duty:30}}];
const v=log.parseVescLog(trends.traceCsv(p,{uuid:'abc123',hardware:'board,"quoted"',version:'5.02'}));
assert.equal(v.uuid,'abc123');assert.equal(v.hardware,'board,"quoted"');assert.equal(v.points[0].values['duty [%]'],20);assert.equal(v.points.at(-1).values['duty [%]'],30);assert.ok(v.points.some(p=>p.gap));
});
test('time wraps at midnight with explicit gap, regressions and mixed controllers are rejected',()=>{
const v=log.parseVescLog(rt([[86399900,48,0,0,1],[100,48,0,0,1]]));assert.equal(v.duration,200);assert.equal(v.points[1].gap,true);
assert.throws(()=>log.parseVescLog(rt([[200,48,0,0,1],[100,48,0,0,1]])),/назад/);
assert.throws(()=>log.parseVescLog(rt([[100,48,0,0,1],[200,48,0,0,2]])),/разные контроллеры/);
});
test('parser rejects malformed widths, duplicate keys, formula, nonfinite and oversized input',()=>{
for(const value of ['ms_today;x;x\n1;2;3','ms_today;x\n1;2;3','ms_today;x\n1;=2+2','ms_today;x\n1;NaN','ms_today;x\n1;Infinity','ms_today;x\n1;"broken','ms_today;x\n-1;2','unknown;x\n1;2'])assert.throws(()=>log.parseVescLog(value));
assert.throws(()=>log.parseVescLog('x'.repeat(log.LOG_MAX_BYTES+1)),/размер/);
assert.throws(()=>log.parseVescLog('ms_today;x\n'+Array.from({length:20001},(_,i)=>`${i};1`).join('\n')),/20 000/);
});
test('Hann FFT finds known frequency/amplitude and removes DC without changing source',()=>{
const points=Array.from({length:1024},(_,i)=>({at:i*10,values:{x:5+3*Math.sin(2*Math.PI*12.5*i/100)},gap:false}));
const result=log.spectrum(points,'x',0,10240);assert.equal(result.n,1024);assert.equal(result.rate,100);assert.equal(result.peak.hz,12.5);assert.ok(Math.abs(result.peak.amplitude-3)<.001);assert.ok(result.bins[0].amplitude<.001);assert.equal(points[0].values.x,5);
});
test('FFT refuses gaps, duplicate time, irregular samples, missing values and short intervals',()=>{
const base=Array.from({length:64},(_,i)=>({at:i*10,values:{x:i},gap:false}));
for(const data of [base.slice(0,31),base.map((p,i)=>i===30?{...p,gap:true}:p),base.map((p,i)=>i===30?{...p,at:p.at-10}:p),base.map((p,i)=>i===30?{...p,values:{x:null}}:p)])assert.throws(()=>log.spectrum(data,'x',0,1000));
assert.throws(()=>log.spectrum(base.map((p,i)=>({...p,at:p.at+(i===1?2:0)})),'x',0,1000),/неравномерен/);
});
test('plot reduction retains a one-sample peak and does not join a gap',()=>{
const points=Array.from({length:10000},(_,i)=>({at:i,value:i===5000?100:i===6000?null:0}));
const v=plot.signalView(points,0,10000);assert.equal(v.max,100);assert.equal(v.count,9999);assert.equal(v.segments.length,2);assert.ok(v.segments.flat().length<3000);assert.ok(v.segments[0].some(p=>p.y<40));
});
test('telemetry uses identity columns and never treats stale, wrong UUID, NaN or negative age as live',()=>{
const d=(n,age=20)=>({id:'d'+n,uuid:'uuid'+n,label:'device'+n,age_ms:age,values:{motor_current_a:0,fault_code:0}});
for(const count of [1,2,3,4]){const v=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:Array.from({length:count},(_,i)=>d(i))}});assert.equal(v.columns.length,count);assert.ok(v.rows.every(row=>row.cells.length===count));}
for(const age of [1000,-1,NaN]){const v=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:[d(1,age)]}});assert.equal(v.rows.find(r=>r.id==='motor_current_a').cells[0],'—');assert.equal(v.rows.find(r=>r.id==='fault').cells[0],'—');}
const stale=telemetry.roverTelemetryTable({fresh:false,snapshot:{devices:[d(1)]}});assert.equal(stale.columns.length,1);assert.equal(stale.rows.find(r=>r.id==='fault').cells[0],'—');
const mismatch=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:[d(1)],profile:{bindings:{left:{device_id:'d1',uuid:'other'}}}}});assert.equal(mismatch.columns.length,2);assert.equal(mismatch.rows.find(r=>r.id==='status').cells[0],'Нет связи');
});
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,m,parse;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});m=await server.ssrLoadModule('../../plugins/vesc/frontend/src/rotorHallReview.ts');parse=(await server.ssrLoadModule('../../plugins/vesc/frontend/src/sampleReview.ts')).parseSampleRecord;});
after(async()=>{await server?.close();});
const points=(states)=>states.map((h,i)=>({at:i,values:{hall:h,phase_deg:(358+i)%360,current:i%2?-3:2},gap:false}));
const review=(p,from=0,to=2000)=>m.reviewRotorHall(p,from,to);
test('six-state sequence and reverse direction are not a winding-order diagnosis',()=>{for(const s of [[1,3,2,6,4,5,1],[1,5,4,6,2,3,1]]){const r=review(points(s));assert.equal(r.transitions,6);assert.equal(r.events.filter(e=>e.kind==='change').length,6);assert.equal(r.counts.slice(1,7).filter(Boolean).length,6);}});
test('repeated state reports observed span, never stall or complete sector dwell',()=>{const r=review(points([1,1,1,1]));assert.equal(r.longest[1],3);assert.equal(r.transitions,0);assert.equal(r.events.length,0);assert.equal(r.peakCurrent,3);});
test('0 and 7 remain separate runs; unknown Hall is not silently zero',()=>{const r=review(points([0,0,7,null,2.5,NaN,8,1]));assert.deepEqual(r.counts,[2,1,0,0,0,0,0,1]);assert.equal(r.missing,4);assert.deepEqual(r.events.filter(e=>e.kind!=='change').map(e=>[e.kind,e.first,e.last]),[['code',0,1],['code',2,2],['missing',3,6]]);});
test('mapped commutation codes never become raw-input edges or a sensor diagnosis',()=>{const r=review(points([1,2,5]));assert.equal(r.transitions,2);assert.equal(r.multi,undefined);assert.equal(r.single,undefined);assert.deepEqual(r.events.map(e=>e.label),['Код Hall: 1 → 2','Код Hall: 2 → 5']);});
test('do not bridge a gap, missing state, missing phase or interval boundary',()=>{
const p=points([1,6,2,5]);p[1].gap=true;const r=review(p);assert.equal(r.transitions,1);assert.equal(r.missing,1);assert.equal(r.phaseCount,3);
assert.equal(review(points([1,2]),1,1).transitions,0);
const q=points([1,null,2]);q[1].values.phase_deg=null;assert.equal(review(q).transitions,0);assert.equal(review(q).phaseStep,null);
});
test('phase wraps across 0 without reporting a 359 degree jump; half turn ambiguous',()=>{assert.equal(m.wrappedPhaseStep(359,1),2);assert.equal(m.wrappedPhaseStep(1,359),-2);const p=points([1,1,1]);p[0].values.phase_deg=0;p[1].values.phase_deg=180;p[2].values.phase_deg=360;const r=review(p);assert.equal(r.halfTurns,2);assert.equal(r.phaseStep,180);});
test('missing and out-of-range phase does not become measured mechanical angle',()=>{const p=points([1,1,1,1]);for(const [i,v] of [null,-1,361,Infinity].entries())p[i].values.phase_deg=v;assert.equal(review(p).phaseCount,0);assert.equal(review(p).phaseStep,null);});
test('event navigation keeps original indices and cursor times with bounded context',()=>{const p=points(Array(20).fill(1));p[12].values.hall=2;const r=review(p,10,15);const w=m.hallEventWindow(p,r.events[0]);assert.deepEqual(w,{from:6,to:17,first:11,second:12});});
test('empty interval and one sample never fabricate movement',()=>{const p=points([1]);assert.equal(review(p,2,3).count,0);const r=review(p);assert.equal(r.phaseStep,null);assert.equal(r.longest[1],0);assert.equal(r.transitions,0);});
test('bounded inputs and ordered finite clock enforced',()=>{for(const p of [Array.from({length:2001},(_,i)=>({...points([1])[0],at:i})),points([1,1]).map(p=>({...p,at:0})),[{at:NaN,values:{},gap:false}]])assert.throws(()=>review(p));assert.throws(()=>review(points([1]),2,1));});
test('old VESC CSV without Hall preserves unavailable channel; no fault claim',()=>{const csv='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase\n0;0;0;0;0;0;0;0;0;10\n0.01;0;0;0;0;0;0;0;0;20';const r=parse(csv,'synthetic.csv');assert.equal(r.complete,null);const a=review(r.points);assert.equal(a.missing,2);assert.equal(a.counts[0],0);assert.equal(a.transitions,0);});
test('review never mutates source or interpolates skipped transitions',()=>{const p=points([1,6,1]),before=structuredClone(p);const r=review(p);assert.deepEqual(p,before);assert.equal(r.transitions,2);assert.equal(r.count,3);});
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,review,samples,plot,log;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});review=await server.ssrLoadModule('../../plugins/vesc/frontend/src/sampleReview.ts');samples=await server.ssrLoadModule('../../plugins/vesc/frontend/src/samples.ts');plot=await server.ssrLoadModule('../../plugins/vesc/frontend/src/SignalPlot.tsx');log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');});
after(async()=>{await server?.close();});
const row=i=>({index:i,i1:Math.sin(2*Math.PI*125*i/2000),i2:0,i3:0,v1:1,v2:2,v3:3,v0:4,current:0,switching_hz:20000,commutation:2,hall:3,phase_deg:180,dt_s:.0005,indexed:false,third_current_measured:false});
const passport=()=>({schema:'missioncore.vesc.sample-data/v1',identity:{uuid:'00112233445566778899AABB',hardware:'SYNTHETIC',version:'5.02'},session:'synthetic-usb-1',state:{capture_id:'synthetic-1',state:'complete',received:128,expected:128,mode:1,count:128,decimation:10,malformed:0},rows:Array.from({length:128},(_,i)=>row(i))});
const parse=v=>review.parseSampleRecord(JSON.stringify(v),'fixture.json');
const filter=extra=>({...review.defaultSampleFilter,...extra});
test('passport preserves source identity, approximate cadence and calculated-current provenance',()=>{const p=parse(passport());assert.equal(p.uuid,'00112233445566778899AABB');assert.equal(p.firmware,'5.02');assert.equal(p.points[1].at,.5);assert.equal(p.complete,true);assert.equal(p.thirdMeasured,false);assert.equal(p.capture,'synthetic-1');});
test('partial/unverified passports cannot be mistaken for full captures',()=>{for(const state of ['incomplete','unverified','timeout','cancelled']){const v=passport();v.state.state=state;v.state.expected=2000;assert.equal(parse(v).complete,false);}});
test('damaged, oversized or contradictory passports fail closed',()=>{
for(const change of [v=>v.schema='other',v=>v.rows[1].index=4,v=>v.rows[1].i1='3',v=>v.rows[1].i1=null,v=>v.rows[1].dt_s=-1,v=>v.rows[1].dt_s=2,v=>v.rows[1].hall=8,v=>v.state.received=100,v=>v.state.expected=2000,v=>v.state.malformed=1,v=>v.identity.uuid='wrong',v=>v.rows=[],v=>v.rows=Array.from({length:2001},(_,i)=>row(i)),v=>v.state.state='constructor']){const v=passport();change(v);assert.throws(()=>parse(v));}
assert.throws(()=>review.parseSampleRecord(' '.repeat(4*1024*1024+1),'huge'));assert.throws(()=>review.parseSampleRecord('{','bad'));
});
test('legacy CSV never borrows connected-controller identity; missing signals stay absent',()=>{
const csv='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase\n0;1;2;-3;4;5;6;7;8;180;\n0.0001;2;3;-5;4;5;6;7;8;181;';
const p=review.parseSampleRecord(csv,'old.csv');assert.equal(p.uuid,null);assert.equal(p.complete,null);assert.equal(p.thirdMeasured,null);assert.equal(p.points[1].at,.1);assert.equal(p.points[1].values.hall,undefined);assert.equal(p.points[0].values.i3,-3);
assert.equal(review.parseSampleRecord(samples.sampleCsv([row(0),row(1)]),'own.csv').points[1].values.hall,3);
});
test('FIR matches Tool frequency-bin inverse transform and Hamming window',()=>{
const expected=[0,.03661165235168156,.125,.21338834764831843,.25,.21338834764831843,.125,.03661165235168156];
const actual=review.filterCoefficients(filter({kind:'fir',bits:3,cutoff:.125,hamming:false}));actual.forEach((v,i)=>assert.ok(Math.abs(v-expected[i])<1e-12,`${i}: ${v}`));
const windowed=review.filterCoefficients(filter({kind:'fir',bits:3,cutoff:.125,hamming:true}));windowed.forEach((v,i)=>assert.ok(Math.abs(v-expected[i]*(.54-.46*Math.cos(2*Math.PI*i/7)))<1e-12));
assert.deepEqual(review.filterCoefficients(filter({kind:'mean',bits:2})),[.25,.25,.25,.25]);
for(const extra of [{bits:0},{bits:11},{cutoff:NaN},{cutoff:.6}])assert.throws(()=>review.filterCoefficients(filter({kind:'fir',...extra})));
});
test('Tool convolution and delay preserve unsupported edges as gaps, never zeros',()=>{
const points=Array.from({length:12},(_,i)=>({at:i,values:{i1:i,hall:i%8},gap:false}));
const centered=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}));assert.equal(centered[0].value,null);assert.equal(centered[1].value,null);assert.equal(centered[2].value,1.5);assert.equal(centered[9].value,8.5);assert.equal(centered[10].value,null);
const delayed=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2,compensate:false}));assert.equal(delayed[3].value,null);assert.equal(delayed[4].value,1.5);assert.equal(delayed[11].value,8.5);
assert.equal(review.filteredSamplePoints(points,'hall',filter({kind:'mean',bits:2}))[0].value,0);
const absent=review.filteredSamplePoints(points.slice(0,4),'i1',filter({kind:'mean',bits:2}));assert.ok(absent.every(p=>p.value===null));
points[3].values.i1=null;assert.equal(review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}))[2].value,null);
points[3].values.i1=3;points[3].at=3.2;assert.equal(review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}))[2].value,null);
});
test('cursors use nearest real sample, keep holes and outside-record requests empty',()=>{
const points=[{at:0,value:1},{at:.1,value:null},{at:.2,value:3}];let m=review.sampleMeasurement(points,0,.2,.01,.19);assert.equal(m.first.at,0);assert.equal(m.second.at,.2);assert.equal(m.delta,2);assert.equal(m.dt,.2);assert.equal(m.count,2);assert.equal(m.rms,Math.sqrt(5));
m=review.sampleMeasurement(points,0,1,.1,.8);assert.equal(m.first,null);assert.equal(m.second,null);assert.equal(m.delta,null);
});
test('submillisecond samples occupy full plot width instead of collapsing to the left',()=>{const view=plot.signalView([{at:0,value:1},{at:.01,value:2}],0,.01);assert.equal(view.segments[0][0].x,64);assert.equal(view.segments[0][1].x,780);});
test('filtering keeps frequency and rejects FFT over missing edges',()=>{
const points=samples.samplePoints(Array.from({length:1024},(_,i)=>row(i))),filtered=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:3}));
const mapped=filtered.map(p=>({at:p.at,values:{i1:p.value},gap:p.value===null}));assert.throws(()=>log.spectrum(mapped,'i1',0,512));const fft=log.spectrum(mapped,'i1',4,500);assert.ok(Math.abs(fft.peak.hz-125)<1e-8);
});
test('responsive plot uses the measured viewport width without shrinking axis type',()=>{const points=[{at:0,value:1},{at:1,value:2}];for(const width of [320,480,960]){const v=plot.signalView(points,0,1,160,width);assert.equal(v.segments[0][0].x,64);assert.equal(v.segments[0][1].x,width-20);}});
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,samples,log;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});samples=await server.ssrLoadModule('../../plugins/vesc/frontend/src/samples.ts');log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');});
after(async()=>{await server?.close();});
const row=i=>({index:i,i1:Math.sin(2*Math.PI*125*i/2000),i2:0,i3:0,v1:1,v2:2,v3:3,v0:4,current:0,switching_hz:20000,commutation:2,hall:3,phase_deg:180,dt_s:.0005,indexed:false,third_current_measured:false});
test('sample time uses decimated cadence and FFT resolves high frequency',()=>{
const points=samples.samplePoints(Array.from({length:1024},(_,i)=>row(i)));
assert.ok(Math.abs(points[1].at-.5)<1e-9);
const fft=log.spectrum(points,'i1',0,512);assert.ok(Math.abs(fft.peak.hz-125)<1e-8);
const csv=samples.sampleCsv([row(0),row(1)]);assert.ok(csv.startsWith('T;I1;I2;I3;'));assert.ok(csv.split('\n')[2].startsWith('0.0005;'));
assert.ok(csv.split('\n')[0].includes('Hall;Commutation;F_sw'));
});
test('malformed samples cannot become false zero traces',()=>{
for(const rows of [[{...row(0),i1:NaN}],[{...row(0),dt_s:0}],[row(1)],Array.from({length:2001},(_,i)=>row(i))])assert.throws(()=>samples.samplePoints(rows));
});
test('native Sample Data CSV imports the original asymmetric trailing delimiter',()=>{
const header='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase';
const original=header+'\n0;1;2;-3;4;5;6;7;8;180;\n0.0001;2;3;-5;4;5;6;7;8;181;';
const parsed=log.parseVescLog(original);assert.equal(parsed.format,'VESC Tool · Sample Data');assert.equal(parsed.duration,.1);assert.equal(parsed.points[1].values.I3,-5);assert.equal(parsed.uuid,null);
const current=log.parseVescLog(samples.sampleCsv([row(0),row(1)]));assert.equal(current.points[1].values.Hall,3);assert.equal(current.duration,.5);
assert.throws(()=>log.parseVescLog(header+'\n0;1;2;3;4;5;6;7;8;9\n0;1;2;3;4;5;6;7;8;9'));
});
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,config,editor;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
config=await server.ssrLoadModule('../../plugins/vesc/frontend/src/configuration.ts');
editor=await server.ssrLoadModule('../../plugins/vesc/frontend/src/VescParameterEditor.tsx');
});
after(async()=>{await server?.close();});
const parameter={name:'current_max',title:'Motor current',type:'number',value:0.35,editor_scale:100,decimals:1,suffix:'%',transmittable:true};
test('native editor scale and units display without changing stored values',()=>{
assert.equal(config.parameterValue(parameter),'35 %');assert.equal(parameter.value,0.35);
assert.equal(config.parameterValue({...parameter,type:'enum',value:1,options:['Disabled','FOC']}),'FOC');
assert.equal(config.parameterValue({...parameter,type:'boolean',value:false}),'Выключено');
});
test('search reaches native names across groups and ignores separator pseudo parameters',()=>{
const other={...parameter,name:'app_mode',title:'Application mode'};
const schema={parameters:[parameter,other],groups:[{name:'general',subgroups:[{name:'limits',parameters:['::sep::Motor','current_max']}]}]};
assert.deepEqual(config.groupedParameters(schema,'general',''),[parameter]);
assert.deepEqual(config.groupedParameters(schema,'general','app_mode'),[other]);
assert.deepEqual(config.groupedParameters(schema,'all','missing'),[]);
});
test('unknown upstream groups remain accessible after an engine update',()=>{
assert.equal(config.groupLabel('foc'),'FOC');assert.equal(config.groupLabel('future_device'),'future_device');
});
test('subgroups preserve upstream order and hide unrelated fields by default',()=>{
const first={...parameter,name:'first'},second={...parameter,name:'second'};
const schema={parameters:[first,second],groups:[{name:'general',subgroups:[{name:'current',parameters:['::sep::Current','second','first']},{name:'voltage',parameters:['first']}]}]};
assert.deepEqual(config.groupedParameters(schema,'general','','current'),[second,first]);
assert.deepEqual(config.groupedParameters(schema,'general','','voltage'),[first]);
});
test('typed editor converts display units back to firmware values and rejects invalid input',()=>{
const p={...parameter,min:0,max:1};
assert.equal(editor.initialDraft(p),'35');
assert.deepEqual(editor.parseDraft(p,'42,5'),{value:0.425,error:null});
for(const value of ['', 'Infinity', 'NaN', '101', '-1'])assert.ok(editor.parseDraft(p,value).error);
assert.ok(editor.parseDraft({...p,type:'integer',min:0,max:100},'1.2').error);
assert.ok(editor.parseDraft({...p,type:'enum',options:['a','b']},'2').error);
assert.ok(editor.parseDraft({...p,type:'bitfield'},'256').error);
assert.equal(editor.parseDraft({...p,type:'boolean'},false).value,false);
assert.ok(editor.parseDraft({...p,type:'string',max_length:4},'longer').error);
});
@@ -0,0 +1,79 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const load=async name=>{
const source=readFileSync(new URL(`../../../plugins/vesc/frontend/src/${name}.ts`,import.meta.url),'utf8');
return import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
};
const {VescTrace,traceView,traceCsv,TRACE_LIMIT}=await load('trends');
const {TraceObserver}=await load('traceObserver');
const frame=(sample=1000,extra={})=>({fresh:true,instance:'source',devices:[{id:'device',uuid:'ABC',session_id:'session',sample_time_ms:sample,observed_at:'2026-10-18T10:00:00Z',age_ms:0,values:{input_voltage_v:48,input_current_a:2,duty:.25,erpm:0},...extra}]});
test('native values retain units; missing/non-finite measurements never become zero',()=>{
const t=new VescTrace();assert.equal(t.accept(frame(), 'device','abc',1000,0),true);
assert.equal(t.points[0].values.duty,25);assert.equal(t.points[0].values.input_power_w,96);
assert.equal(t.points[0].values.motor_temperature_c,undefined);
const v=traceView(t.points,'motor_temperature_c',0,2000);assert.equal(v.count,0);assert.equal(v.min,null);
t.accept(frame(1100,{values:{input_voltage_v:NaN,erpm:Infinity,duty:false}}),'device','abc',1100,0);
assert.equal(t.points.at(-1).values,null);
});
test('duplicate/reordered samples do not extend freshness or add fake flat-line points',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);
t.accept(frame(),'device','abc',1700,0);t.accept(frame(900),'device','abc',1800,0);
assert.equal(t.points.length,1);assert.equal(t.freshUntil,2500);
t.accept(frame(),'device','abc',2501,0);assert.equal(t.points.at(-1).values,null);
for(let i=0;i<10;i++)t.gap(2600+i);assert.equal(t.points.length,2);
});
test('USB sessions, service restarts and missing frames cannot join plot segments',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.accept(frame(1300),'device','abc',1300,0);
t.accept(frame(1600,{session_id:'new-session'}),'device','abc',1600,0);
t.accept({...frame(1,{session_id:'new-session'}),instance:'restarted'},'device','abc',1900,0);
t.gap(2100);t.accept(frame(400,{session_id:'new-session'}),'device','abc',2200,0);
const v=traceView(t.points,'erpm',0,3000);assert.equal(v.segments.length,4);
assert.equal(t.points.filter(p=>p.values===null).length,3);
});
test('identity ambiguity, stale transport, missing timestamps and slow HTTP fail closed',()=>{
const invalid=[{...frame(),fresh:false},{...frame(),instance:''},{...frame(),devices:frame().devices.concat(frame().devices)},
frame(1000,{uuid:'other'}),frame(1000,{session_id:''}),frame(1000,{age_ms:1600}),frame(1000,{age_ms:-1}),
frame(undefined,{sample_time_ms:undefined}),frame(1000,{observed_at:'broken'})];
for(const f of invalid){const t=new VescTrace();assert.equal(t.accept(f,'device','abc',1000,0),false);assert.equal(t.points.length,0);}
const t=new VescTrace();assert.equal(t.accept(frame(),'device','abc',1000,1500),false);
});
test('timestamp gap creates a break even when no explicit disconnect arrived',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.accept(frame(3100),'device','abc',3100,0);
assert.equal(traceView(t.points,'erpm',0,4000).segments.length,2);
});
test('rolling trace is bounded by count, time and UTC day; clear resets sample identity',()=>{
const t=new VescTrace();for(let i=0;i<2500;i++)t.accept(frame(i),'device','abc',i,0);
assert.equal(t.points.length,TRACE_LIMIT);t.prune(400000);assert.equal(t.points.length,0);
t.accept(frame(400001),'device','abc',400001,0);t.prune(400002,'2099-01-01');assert.equal(t.points.length,0);
t.accept(frame(400003),'device','abc',400003,0);t.clear();assert.equal(t.accept(frame(1),'device','abc',1,0),true);
});
test('CSV records gaps, session provenance, empty absent fields and escaped spreadsheet text',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.gap(2000);
const csv=traceCsv(t.points,{uuid:'abc',hardware:'=cmd,"bad"',version:'5.02'});
assert.match(csv,/duty \[%\]/);assert.match(csv,/"gap"/);assert.match(csv,/"session"/);assert.match(csv,/"'=cmd,""bad"""/);
assert.equal(csv.split('\r\n').length,4);assert.doesNotMatch(csv,/undefined|NaN|Infinity/);
});
test('observer is single-flight, suppresses late results after close and aborts owned read',async t=>{
t.mock.timers.enable({apis:['setInterval','setTimeout']});
let resolve,calls=0,signal;const received=[];
const observer=new TraceObserver(s=>{calls++;signal=s;return new Promise(r=>resolve=r);},v=>received.push(v),()=>{},()=>true,()=>1000);
await Promise.resolve();t.mock.timers.tick(1000);assert.equal(calls,1);
observer.close();assert.equal(signal.aborted,true);resolve(frame());await Promise.resolve();await Promise.resolve();assert.equal(received.length,0);
t.mock.timers.tick(5000);assert.equal(calls,1);
});
test('hidden view starts no requests; aborted/expired read never delivers a stale frame',async t=>{
t.mock.timers.enable({apis:['setInterval','setTimeout']});
let visible=false,calls=0,resolve,signal;const received=[];
const observer=new TraceObserver(s=>{calls++;signal=s;return new Promise(r=>resolve=r);},v=>received.push(v),()=>{},()=>visible,()=>1000);
await Promise.resolve();assert.equal(calls,0);visible=true;t.mock.timers.tick(500);await Promise.resolve();assert.equal(calls,1);
t.mock.timers.tick(1201);assert.equal(signal.aborted,true);resolve(frame());await Promise.resolve();await Promise.resolve();
assert.equal(received.filter(Boolean).length,0);observer.close();
});
test('pause retains the last numeric value as historical and expanded plot uses full height',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.gap(1400);
const a=traceView(t.points,'input_voltage_v',0,2000,180),b=traceView(t.points,'input_voltage_v',0,2000,384);
assert.equal(a.last,48);assert.equal(t.freshUntil,-Infinity);assert.ok(b.segments[0][0].y>a.segments[0][0].y);
});
File diff suppressed because it is too large Load Diff
+401
View File
@@ -0,0 +1,401 @@
# VESC Tool engine upgrades and operator surface
Owner direction, 2026-10-17: Mission Core should ultimately expose the full
VESC Tool feature set, including firmware and universal tools, in its shared
Node/Core settings modal. This is the target scope, not a claim of delivered
parity. No motor, configuration-write or firmware-upload hardware acceptance
is authorized in the present implementation session. Fresh-Ubuntu acceptance
is deferred by the owner.
## Release boundary
The official `vedderb/vesc_tool` repository is the original Tool source. The
adapter links its original objects and resources, replacing only `main.o`.
`VescInterface`, `Commands`, `ConfigParams` and `Utility` own vendor semantics.
Mission Core owns sessions, exclusive USB ownership, transactions, UI and the
bounded private JSON process contract. Do not fork upstream algorithms into
the frontend or Python to make an upgrade appear compatible.
`plugins/vesc/packaging/engine-profile.json` is the single reviewed source pin:
upstream commit, archive SHA-256, expected Tool version, environment, RPC major,
admitted firmware identities and implemented native methods. Its canonical
hash is embedded in the generated C++ header and exported by the engine.
Configuration groups, parameter order, types, ranges, units, enumeration
options and descriptions are read from the selected upstream schema; UI code
does not own an electrical-parameter catalog.
There are three different versions: upstream Tool, Mission Core adapter/plugin,
and the controller firmware. Updating Tool or Node never flashes a controller.
An upstream schema's existence is not hardware qualification. Current native
release admission remains stable FW 5.02, VESC type, no custom configuration.
Current physical evidence is the rover's 75_300_R2 controllers; this does not
qualify other boards, manufacturers, IMUs, BMSs or developer operations.
## Upgrade procedure
1. Review an exact upstream commit and source archive, including compatibility
handling, config signatures, firmware resources, native API changes and
dependency changes. Update the profile with both commit and archive hash.
Never build production from a moving branch or a `latest` download.
2. Build original Tool in the bounded artifact-owned Ubuntu staging profile.
Keep source, dependency and binary provenance. Preserve original objects.
The existing `tool_build.py` consumes the profile beside it; any standalone
build distribution must include `engine_profile.py` and the profile JSON.
3. Build `build_native_probe.py` and run that immutable job against the attested
original build. It embeds the profile, adapter source and generated header.
Test native binary/XML round trips for every retained firmware archive;
corrupt, truncated and mismatched-signature inputs must fail. Native offline
mode must deny all hardware operations. Check method inventory and RPC hash.
4. A new supported firmware or hardware family requires its own evidence and
operation-specific acceptance. Keep earlier profiles and fixtures unless
support is intentionally withdrawn. Unknown devices get an explicit
unsupported capability state; do not silently select the newest schema.
5. Create the native runtime bundle with its actual ELF dependency closure and
licenses. `payload.py` refuses a stale bundle after the profile changes.
Installer acceptance compares the offline engine handshake to the bundle's
version, commit and contract. Runtime verifies that handshake again before
admitting a USB owner. A mismatched native process is closed.
6. Build and qualify the standard Node release, including both shared UI
consumers. Install through the versioned owner installer; preserve the
qualified predecessor. Verify read-only identities, current telemetry,
reconnect/session behavior and modal operations through Core.
The previous qualified application package and native bundle are retained.
The current owner installer deliberately refuses an implicit package downgrade;
automatic/one-click rollback has not been implemented or accepted. Any rollback
must be a reviewed versioned installer operation restoring the prior qualified
binary and adapter. It does not undo a controller firmware update. Firmware rollback is a separate
device operation that requires a compatible image and its own verification.
Do not auto-flash, auto-migrate configuration or replay uncertain writes after
an application or USB reconnect. No unattended upstream update job is enabled.
## Current surface and remaining parity work
The modal uses canonical FeatureSettingsWindow above equipment inventory.
Native schema browsing/export, fixed read-only hardware diagnostics, PPM/CAN
inspection, existing backups, calibration and raised-rig controls share the
existing exclusive device owner. Snapshot results are bounded and separate
from durable backups. Session replacement invalidates mounted forms and
confirmations. The original Tool desktop UI is not shipped as the product UI.
VESC0.9.0 adds transactional typed configuration editing, XML import and
restore with preview/readback. Parameters remain native-schema driven; previews
are UUID/session/baseline-bound, expire after five minutes and never write.
Apply saves the original durably, consumes its preview once, compares exact
readback and retains a persistent interlock after an uncertain result.
Reconciliation reads only. Motor-control admission rejects pending config
writes. Synthetic fault injection and native offline qualification cover writes;
real-board acceptance currently covers reading and preview only. Actual config
writes remain unqualified on physical hardware in this session.
VESC0.10.0 adds a bounded raw-BIN firmware/bootloader transaction. Two RAM
staging slots hold at most 2 MiB each (bootloader at most 64 KiB), expire after
ten minutes and bind to UUID plus the current USB session. Ordered chunks,
length, SHA-256 and STM32 vectors are checked before an explicit apply. These
checks do not authenticate the image or discover its board compatibility.
Target application versions remain limited to the admitted engine profile.
Original VescInterface::fwUpload owns USB upload, compression and acknowledgments;
Mission Core owns durable pre-write backup, one-time intent, status, cancellation
and an uncertainty interlock. A reconnect never replays an upload. After native
confirmation, fresh UUID/HW/version can reconcile the workflow; it does not
constitute binary readback. Lost acknowledgments remain uncertain. Pending
firmware writes block motor/configuration changes. Companion telemetry can
continue while the other native owner uploads. These physical write/cancel/
recovery paths have synthetic coverage but no real-flash acceptance in this
session. Real-board acceptance covers reads and volatile image preparation only.
Original Commands also supplies ADC/Nunchuk/IMU/BMS snapshots and the bounded
read-only diagnostic terminal. Empty/zero peripheral responses do not establish
physical module presence. Custom hardware remains outside the admitted profile.
The original desktop UI is not installed as an interactive product dependency.
The remaining full-Tool work after the extended-image/BMS increment below includes
CAN/SWD workflows, PAS/custom-device/configuration capabilities, Lisp/QML and other
advanced terminal/developer tools, high-frequency acquisition and multiple live traces,
and additional motor wizards. These need actual native/API implementations,
applicability rules and acceptance; absent operations must not be represented
as working buttons. Full original Tool parity is not yet delivered.
## Live trends and CSV — 2026-10-18
The operator compares native GET_VALUES measurements inside the approved VESC
FeatureSettingsWindow. This is class A content in its existing device navigation.
A separate application workspace was rejected because the selected controller,
identity and diagnostic job already belong to this modal. SettingsCard, Select,
Button, IconButton, StatusBadge and ResourceRow own all controls; the SVG is a
VESC-specific numerical renderer, not a shared visual primitive.
The pinned Tool PageRtData groups currents/duty, ERPM, FOC, temperatures and
position. These same native measurements feed a selectable single-unit plot,
with interval, expand/restore, pause, minimum/maximum/sample mean and CSV export.
Input power is explicitly derived from input voltage/current; duty is percent.
Missing quantities stay absent. Sensor validity is not inferred from a numeric
temperature. This does not implement high-frequency sampled-data/FFT, original
Tool log import, multi-series axes or every upstream analysis tool.
One request in flight, 500 ms display cadence, 1200 ms cancellation, 1500 ms
freshness bound including response latency. No new USB owner/thread or operation
journal is used: Core reads its existing rover projection; Node has an authenticated
GET-only endpoint that renews the existing observer's two-second watch without
changing relay or input lease. Source monotonic sample time, USB session, instance
and onboard UTC are propagated. Repeats/reordering never add samples or renew
freshness; reconnects, source restarts, stalls and missing values break the line.
The modal retains at most 1200 records / five minutes in RAM with UTC daily reset,
expiry while paused and cleanup on close/session replacement. No disk history,
localStorage or replay publisher exists. Only explicit CSV export creates a file;
metadata is escaped against spreadsheet formula evaluation. Normal/empty/stale/
paused/unavailable states are distinct. Hidden tabs stop read interest. Acceptance
requires synthetic lifecycle tests, shared builds, an installed owner artifact
and real Core/UI readings without motor commands or controller writes.
Accepted release: Node0.8.49-18 / VESC0.11.0, owner
a24b9fa34097b3adaf6a9a9c, original Tool7.00 engine unchanged.19 Linux jobs
(including223 VESC runtime tests),1172 frontend tests, shared typecheck/build,
6 Core read operations and114/114 paired fresh snapshots over60.245s passed.
Both physical controllers render a visible graph in Core; CSV contains110
unique source measurements plus a pause gap. Configurations and drive assignment
remain unchanged. Real controller writes, physical port swapping and clean-OS
acceptance remain deferred. Installation and evidence hashes are in document17
and outputs/vesc-trends-20261018/release-proof.json.
## Extended image preparation and addressable BMS — 2026-10-18
Operator jobs: choose a compatible recovery image, inspect exactly the bytes
that would be written, and inspect/control an identified battery through CAN.
Class A content extends the existing VESC FeatureSettingsWindow: firmware stays
under configurations; BMS has its own tools section. A new application root or
separate raw vendor desktop was rejected because device identity, transport and
operator lifecycle already belong to this modal. Existing SettingsCard, Select,
Checker, Button and ResourceList/Row supply every control. Descriptive text keeps
the accepted Inter12px/muted48%/400/16.8px style. Empty, reading, received,
unsupported, expired and unconfirmed-command states have distinct copy.
HEX source is bounded to8MiB and normalized output to2MiB (bootloader64KiB).
A strict container/address/checksum/overlap gate precedes original HexFile parsing.
Only the STM32 application base0x08000000 or bootloader base0x080E0000 is admitted;
gaps become0xFF. Both original and normalized hashes are retained, and apply
uses the normalized digest. Native temporary files use the owned writable runtime
directory under the installed systemd sandbox. File staging remains volatile.
The installer carries41 immutable upstream5.02 image entries from
vedderb/vesc_fw_archive@0030cfa9d6250331436b31a01f006fe0546bf6a6. Selection filters
exact hardware name plus admitted firmware versions. Source generator and
payload verify pinned image hashes; fetch_firmware_catalog.py restores identical
inputs, checking both Git blob IDs and SHA-256. No runtime network download.
Images without hardware limits require a separate explicit acknowledgement.
These are upstream archive binaries, not a claim of reproducible compilation
or a way to infer a clone board's manufacturer.
VESC5.02 BMS proxy reads omit source CAN ID and source age. Decoder defaults for
absent fields are removed, empty cell sets do not establish BMS presence, and
cached values are never described as current battery connectivity.
Addressed BMS reading uses original canTmpOverride/getFwVersionBlocking and
Commands::bmsGetValues, preserving/restoring the local USB identity and schema.
The UUID/type is read before and after the measurement. Addresses0..253 are
allowed; broadcast is excluded. A timeout retires the native owner rather than
leaving a late CAN reply on a reusable stream.
The seven original PageBms buttons (charge on/off, balance on/off, reset Ah/Wh,
zero current) use original Commands with a reviewed BMS6.00 protocol profile:
vedderb/vesc_bms_fw@591d57dadb14d4392d4cf859a5187264a8aafed8. Each command needs a
60-second UUID/CAN/session-bound preview and explicit confirmation. Idle/input
checks, fresh BMS identity/read and durable intent precede a single consumed
send; reconnect never retries it. Zero-current calibration additionally requires
both reported currents below0.1A and the operator's isolated-load confirmation.
These commands have no completion ACK. The result is sent_unconfirmed or unknown,
never a fabricated successful readback. CAN serialisation and failure lifecycle
have synthetic/offline coverage; no physical BMS writes are part of acceptance.
Per-cell override needs a verified hardware cell-offset mapping and is excluded.
BMS custom configuration, BMS firmware update, direct USB BMS and hardware-specific
BMS tools are separate from these addressable command/read capabilities.
Full original Tool parity remains open: CAN/SWD flashing, additional admitted
firmware/hardware families, BMS/custom configuration and cell mapping, Lisp/QML,
high-frequency samples/FFT, log import, multiple traces and further motor wizards.
Real flashing, battery writes, motor movement and clean-Ubuntu validation are
not performed in this increment. Acceptance evidence is appended after install.
Acceptance: Node0.8.49-19 / VESC0.12.0, ownerbcda6616e335273a33c317d8,
passed112 native jobs/39 checks,19 Linux jobs with249 VESC tests,1176 frontend
tests and shared architecture/typecheck/build. Installed Core acceptance passed
24 read/staging operations on both controllers and116/116 paired fresh samples
over60.378s. Actual UI covered archive/HEX preparation, no-limits confirmation,
BMS proxy/CAN-empty states and Escape. Configurations unchanged; no motors,
flashing or BMS writes. CAN discovery returned no targets, so physical BMS-control
qualification is unavailable. Installer/catalog hashes, lifecycle and precise
limitations are recorded in17 and outputs/vesc-advanced-20261018/release-proof.json.
## Operator composition extension · 2026-10-18
Owner requested one VESC gear, generic settings first, a horizontal telemetry
comparison and independent modal scrollports. The job is to identify/configure
one controller or compare live drive readings without leaving the device modal.
Keep the existing FeatureSettingsWindow; moving to a new page would split the
same controller lifecycle. Generic device settings are a shared Sensor UI slot;
the plugin declares settingsInDetail instead of the host branching on VESC.
Prepared/unprepared, online/stale, request pending/error and empty readings keep
the same layout and authority. Generic Description, ComparisonTable, scroll
containment and aggregate initial LoadingRegion belong to Design Guideline.
The comparison preserves UUID assignments and stale identities but never shows
expired readings as current. No controller write is needed for visual acceptance.
## CSV and signal analysis adapter · 2026-10-18
The original Tool7.00 source remains pinned to01d5f10901116c311e3fb84d5a1541f663d3ce20.
The CSV adapter was checked against `VescInterface::openRtLogFile` /
`loadRtLogFile` and `PageLogAnalysis::openLog` / `saveCsv` at that revision:
RT semicolon/comma fields, trailing delimiter, milliseconds since midnight,
PWM fraction; Log Analysis key:name:unit:precision:relative:timestamp metadata.
Mission Core exported CSV is also accepted with source/session/UUID and gaps.
Unlike the original forward-fill reader, empty numeric fields remain missing.
That difference is explicit in the UI; no invented zero or held-current data.
Mixed RT CAN IDs / Core UUIDs, backward timestamps, nonfinite/formula values,
ambiguous columns and malformed CSV are refused. Midnight rollover creates a gap.
Files are bounded to4MiB/20,000 rows/96 columns and remain only in window RAM.
Manual imported evidence never enters live telemetry, a server or controller API.
One to four separate signals share the selected time interval and preserve each
signal's units. Pixel-bucket extrema reduction retains short peaks and gap
boundaries. FFT uses32–4096 contiguous samples, radix2, mean removal, a Hann
window with coherent-gain amplitude correction and one-sided Nyquist handling.
Uniform timestamps within1% are required. The interval, rate and frequency
resolution are shown. This is analysis of the imported sampling rate, not a
new high-frequency capture capability; a2Hz log cannot diagnose fast motor
phenomena. Synthetic sinusoid, missing/time/order/size cases qualify the math.
This increment does not claim full original Tool parity. CAN/SWD flashing,
additional firmware families, BMS/custom configuration/direct BMS USB, PAS,
Lisp/QML, high-frequency acquisition and remaining motor wizards stay open.
Acceptance: Node0.8.49-20 / VESC0.12.1, ownerff890b6d7fa6777743ae1094,
passed20 Linux jobs with249 VESC tests,1185 frontend tests,8 DG tests and shared
architecture/typecheck/build. Core acceptance passed6 read operations and117/117
paired fresh snapshots over60.480s. Both configuration hashes unchanged; no motor,
configuration, firmware or BMS writes. UI verified actual installed controller
identity/table/session replacement and synthetic CSV/FFT analysis. Full original
Tool parity and hardware-write qualification remain open as listed above.
Precise provenance/lifecycle:17 and outputs/vesc-ui-analysis-20261018/release-proof.json.
## CAN/SWD firmware and compact observation — 2026-10-18 candidate
The existing firmware card selects USB, one addressed CAN VESC, or an external
SWD target. This remains domain content in the admitted settings modal; a new
application workspace is unnecessary. Select/TextField/Checker/SettingsCard,
ProgressBar and Description remain shared Design Guideline controls.
CAN stages bind the gateway session plus target CAN address, UUID, hardware and
admitted firmware. Native temporary routing restores on success/failure; remote
configuration reads preserve the local schema and baselines. Before upload both
gateway and target must pass the existing idle guard. The immutable backup uses
the target UUID, with an authenticated download tied to the firmware operation.
Original fwUpload uses unicast routing and fwdCan=false: no broadcast firmware.
Lost ACKs remain uncertain and reconnect never replays the write.
SWD uses the original BM pin mapping/connect/erase/upload/reboot calls. Staging
BIN/strict Intel HEX never connects the debugger. Apply requires explicit target,
pins, main-flash address/span and physical compatibility confirmation. The native
MCU family response must match; image endpoints must be readable before erase.
The declared span is an operator declaration for STM32 families, not automatic
flash-capacity discovery. No option-byte, peripheral or UICR image is admitted.
Erasing clears the full target main flash, not merely the selected write span.
Every written chunk is read back; unsupported readback is rejected before SWD
connect. Cancellation/timeout never silently becomes success; the durable
firmware interlock remains until a confirmed result or a new explicit repair.
Readback and reboot ACK do not prove the target application booted. BM family
codes are not a board model or UUID. Direct USB BMS, broadcast CAN, arbitrary
memory/debug access and peripheral provisioning remain outside this increment.
The reviewed Tool pin is unchanged. Native offline qualification covers strict
SWD image bounds and unicast routing restoration; real CAN/SWD writes are not
part of current acceptance. No motor operation or new-Ubuntu test is performed.
Observation defaults use preferred initial pane sizes; persisted user geometry
is retained. Shared recursive minimum sizes clamp every ancestor split; when a
viewport is smaller than the complete layout, its canvas scrolls. Compact
ComparisonTable rows use 3px vertical padding and 1.25 line height: about 21px
per row instead of 31px. Label width120px, each VESC at least88px; two-controller
telemetry pane minimum320x280. Larger fleets increase the minimum width.
Observation saves serialize across remounts. On a failed ACK the client reads
the authoritative revision: identical content settles without replay; disjoint
fields merge once; competing edits keep a recoverable local draft and require
an explicit operator choice. Old drafts without a base are retained separately
instead of repeatedly submitting a stale revision. No forced board overwrite.
A CAN target already present through USB must be flashed from its own USB card.
During an addressed upload, observer polling also excludes any USB alias which
appears later with the same target UUID. A pending/uncertain CAN result follows
that UUID across transports; complete recovery in the originating gateway card.
Reconnecting the target over USB cannot bypass the firmware interlock.
### Accepted CAN/SWD increment
Node0.8.49-21 / VESC0.13.0 is installed and published through the standard owner
release. The candidate design above is delivered; physical writes are not part
of this acceptance.51 native checks,269 runtime tests,1190 frontend tests and21
Ubuntu jobs passed. SWD BIN/HEX preparation/discard passed through Core; CAN
scans had no responders. See document17 and outputs/vesc-can-swd-20261018.
Full Tool parity remains open for additional admitted firmware/hardware families,
BMS/custom configuration and direct USB BMS/firmware, PAS/custom devices, Lisp/QML,
advanced developer tools, high-frequency acquisition, multiple live traces and
remaining motor wizards. CAN/SWD implementation is no longer in that missing
feature list; real physical flashing and recovery still require separate hardware
qualification. No fresh Ubuntu qualification was performed, per owner scope.
### BMS configuration and programming increment (candidate 2026-10-18)
The existing VESC settings modal gains the complete custom-configuration schema
of an addressed CAN BMS (reviewed BMS6.00), including groups, typed fields, native
XML, default-value comparison, UUID/index/schema-bound previews and a durable
backup/readback barrier. A changed CAN address can be reconciled by UUID at its
new address. This does not introduce direct USB BMS or cell-mapping writes.
LispBM and QML are domain sections inside the same FeatureSettingsWindow, using
canonical SettingsCard/Description/TextAreaField/Checker/Button controls. This
keeps programming within the selected controller/session instead of a separate
application window. No new workspace or shared visual primitive is introduced.
CodeLoader from the pinned Tool owns imports, compression, flags and CRC format.
Only explicitly attached flat import files are staged in a private temporary
directory; package imports, arbitrary host paths and automatic QML execution are
excluded. Projects transfer in bounded chunks. Native Commands handles USB code
read/erase/write, exact-offset ACKs and readback, with no write retry. Upload and
Lisp start/stop/REPL are separate confirmed actions. Unknown writes and execution
persist as interlocks; stopping Lisp remains possible after an uncertain write.
Code operations have a separate reviewed FW6.00 USB profile; they do not admit
motor/configuration commands for that firmware. Current rover FW5.02 cannot run
these tools and is never upgraded implicitly.
The original protocol reference is vedderb/bldc tag6.00, comm/commands.c,
lispBM/lispif.c and flash_helper.c. The custom BMS schema fixture is taken from
the already pinned BMS protocol source. Native offline checks exercise the real
schema and CodeLoader; simulated transport faults do not qualify a physical BMS,
FW6.00 flashing or code execution. QML runtime rendering inside the browser,
package-store installation, direct USB BMS and additional firmware profiles remain
open. The installed status and acceptance are recorded in document17.
### Accepted BMS and code increment
Node0.8.49-22 / VESC0.14.0 is installed and published. The candidate workflows
above passed71 native checks,278 runtime tests,1192 frontend tests and21 Ubuntu
jobs. Existing5.02 controllers were read only; unsupported code operations were
correctly rejected. No QML browser renderer or full Tool parity is claimed.
See document17 and outputs/vesc-bms-code-20261018/release-proof.json.
## Extensions increment — 2026-10-18
Node0.8.49-24 / VESC0.15.0 delivers the package catalogue, imports, compatibility,
transactional replacement/recovery and stored library imports described in
[document28](28_VESC_PACKAGES.md). The package-store gap above is closed at the
implementation/synthetic level; FW5.02 catalogue workflows are accepted on both
physical controllers. Physical writes require the explicit6.00 profile and remain
unqualified. QtQuick rendering and the other outstanding tools remain open.
+64
View File
@@ -0,0 +1,64 @@
# VESC extensions
The shared Core/Node VESC settings window owns an Extensions section built from
Design Guideline FeatureSettingsWindow, SettingsCard, ResourceList/ResourceRow,
Description, Select, TextField, TextAreaField, Checker and Button. This is domain
content inside the existing modal, not a new workspace or navigation root.
The operator selects a package, reads its author documentation and compatibility,
then previews a complete Lisp/QML replacement before confirming the write.
Libraries remain separate from installable applications. Search/filter, empty,
loading, unavailable, unsupported, rejected and uncertain-write states are explicit.
The installer carries a hash-pinned RCC catalogue with 41 packages. Reproduce it
with packaging/fetch_package_catalog.py: changed upstream bytes fail verification.
The immutable qualified Node release also retains the exact catalogue. Runtime
refresh is explicit, targets the same fixed public URL as upstream VESC Tool and
changes only the catalogue. The publisher serves it over HTTP; the UI states this.
There are no payment, account or purchase flows. The Node host downloads a bounded
8 MiB response without redirects, cookies, credentials or proxy-environment use.
The USB service retains PrivateNetwork and receives bounded checked chunks.
Failed download, invalid archive or interrupted import preserves the previous
catalogue. Imported catalogues use one atomic replacement; individual imports
are limited to 16 packages / 8 MiB. Publication preserves at least 8 MiB
of the service JSON budget for journals and recovery. Catalogue import does not run application QML or Lisp. Compatibility uses the
isolated predicate described below. Explicit QML preview uses the separate
disconnected renderer described in document 29; Lisp is never run by preview.
Qt RCC v3 and VESC Packet containers are bounded before decoding. The original
pinned Tool CodeLoader unpacks packages and compresses QML. Lisp payload bytes,
embedded native libraries and alignment are retained. The descriptor compatibility
function runs in a bare QJSEngine with a 250 ms interrupt deadline and plain identity
data only; no Qt/QObject/USB/network/filesystem/application bridge is exposed.
The QML component itself and Component.onCompleted are never instantiated.
False compatibility rejects installation. Unknown compatibility requires an
explicit documentation-based confirmation; it never silently becomes true.
Existing firmware profile and flash bounds are additional independent checks.
Lisp editor pkg@ and pkg:: resource imports resolve only against the stored
catalogue. Original CodeLoader extracts the source or named attachment; the editor
packs a self-contained project with flat attachments. Host paths and network URL
fallback remain forbidden. Readback normalizes original package import paths into
attached files so an installed package remains editable without host-path access.
Install, update and removal replace both Lisp and application QML, including an
empty component. Before any write, a durable exact-byte recovery snapshot is saved
for the controller identity. Confirmation binds UUID, firmware, USB session, current
code hashes/flags and a five-minute lifetime. Both components are read back before
success. Lisp is stopped with acknowledgement but never started by installation.
Firmware boot behavior is separate and disclosed; no promise of disabled autostart
after power cycling is made. Original upstream installVescPackage is deliberately
not called because it starts Lisp immediately.
A timeout or lost ACK preserves a durable interlock and never retries the write.
Reconcile compares both components. Partial content stays blocked; recovery writes
the exact original snapshot after a new preview. A failed recovery never replaces
the original backup with partial contents. Installed package names are shown only
after identity and both code hashes match, not merely from a historical receipt.
Current physical rover controllers remain firmware 5.02. Catalogue browsing, import,
refresh, compatibility inspection and package download work on this profile. Code
writes require the explicit VESC 6.00 profile and remain physically unqualified.
The original extension increment did not include QML rendering. Document 29 adds
a native Qt Quick snapshot preview, not interactive QML/device execution or
full VESC Tool parity. Motor/configuration/BMS/firmware writes and code execution
are excluded from acceptance. No new Ubuntu installation test is claimed.
@@ -0,0 +1,117 @@
# QML snapshot preview and connection evidence
This document records Node27. Node28 adds interactive input, optional snapshots
and Core RAM receipts; see [the current extension](30_VESC_SAMPLE_DATA_AND_INTERACTIVE_QML.md).
The existing shared QML editor and Extensions detail surface offer an explicit
preview. This is domain rendering inside the existing FeatureSettingsWindow;
SettingsCard, Button, Description and TextAreaField remain Design Guideline
controls. It does not create a workspace, navigation root or new generic control.
The operator submits the current source (up to 120 KiB) using checked 16 KiB
fragments. Two uploads at most, five-minute TTL and exact device/session binding
bound driver RAM. Begin/chunk/render are snapshot operations. The driver does not
persist source or frames in its journal; Node expires snapshot result bodies.
Core and Node still use their existing operation receipt persistence, which can
retain uploaded command fragments and Core result payloads. This is not an
end-to-end RAM-only guarantee; dedicated cross-layer payload expiry remains open.
Changed source or session clears the displayed frame. No preview runs on opening
a section, selecting a package, importing code or opening a file.
Rendering reads the controller identity, motor/application configurations and
values through the existing USB owner. A separate executable uses the same pinned
upstream VESC Tool objects/resources and real Qt Quick software rendering. Original
Commands/ConfigParams decode those snapshots. All outgoing Commands are discarded;
there is no transport path from this process back to a controller. The output is
one 640 x 480 frame, clearly marked as a snapshot. Input events and continuously
updated telemetry are not implemented by this increment. BMS/Lisp replies not
present in the snapshot cannot be invented; dependent package panels may be empty.
QML requiring additional modules reports native load errors.
Containment precedes Qt and user QML. Linux Landlock ABI 3 or later restricts reads
to the shipped runtime, fonts and local time data and denies filesystem writes.
Seccomp denies sockets/connections, executable/process creation, ptrace, process
memory access, namespace/mount changes and io_uring; Qt threads remain admitted.
The renderer checks that private file reads, networking and execution are denied.
There is no inherited device FD. Limits: 512 MiB virtual memory, three CPU seconds,
64 FDs, no core dumps, six-second parent wall deadline. Parent timeout kills and
reaps the child. One preview runs under the existing operation lock. The service
budget is 1 GiB and preview refuses admission above 384 MiB current cgroup usage.
Unsupported containment fails closed. No root/service-account workaround is used.
The native build downloads signed Ubuntu QML packages into private staging,
extracts them without installing packages, and bundles modules, fonts, dependency
closure and license notices. Cached packages must match recorded SHA-256 values.
The owner installer carries the runtime and service limits from first deployment.
This supports the declared Ubuntu 24.04 amd64 environment; it is not fresh-host
acceptance. Native tests cover rendering, discarded motor-command serialization
without transport, malformed QML, official package components and an infinite loop.
Connection evidence adds transition records (identified, first sample restored,
read failed, USB detached) to the service journal. Records include UTC/monotonic
time, UUID, USB address/port/tty, old session, last sample time/age and selected last
values. Record construction happens before session/sample cleanup. Native failure
records retain the initiating RPC, recent RPC history and old session. Failed
native startup retains the exit code and last 4 KiB of stderr before the next
attempt can replace its runtime log. Journal
failures cannot prevent cleanup. There is no per-sample journal write. Transition
records are bounded to 4 KiB; service rate limiting is 60 records per 30 seconds.
System journal retention still owns durable diagnostic storage.
## Diagnostic coverage and remaining work
Already available: firmware hw_status/faults/read-only terminal; live values
including Id/Iq, Vd/Vq, duty, ERPM, input/motor current, supply voltage and faults;
up to five minutes/1200 points in RAM; explicit CSV export; original Tool CSV import,
multiple analysis plots and bounded FFT. The live graph is at most 2 Hz and is not
a waveform oscilloscope. Disconnects remain gaps rather than zeroes.
Not yet full parity: original Sample Data high-frequency acquisition/triggers,
synchronised desired/applied command and Hall/observer traces, interactive QML
input and device command admission, and a combined bounded incident export spanning
MCU, USB owner and Linux kernel. The upstream LogUI package is a configurable log
interface, not proof that USB enumeration failures or arbitrary motor commutation
faults will be recorded. Package compatibility and required Lisp/firmware features
must be assessed individually. Current physical controllers remain firmware 5.02.
Low-speed diagnosis must correlate control mode, FOC sensor mode, Hall table and
signals, R/L/flux configuration hashes, commanded/applied output, current/voltage,
ERPM and phase data. Hall analysis and motor detection may energize the motor;
they are not read-only diagnostics. Calibration improvement alone does not rule
out sensor/wiring/load or mechanical causes. Do not change several parameters to
forum values without a measured baseline and a repeatable safe experiment.
## Rover evidence checked on 2026-10-18
The owner reports low-speed sticking on both sides, from both the transmitter and
Core. Unloaded calibration previously restored good response, followed by
recurrence the next day. This is not explained by the left/right sensor-mode
asymmetry alone.
Read-only current motor/application packets for both UUIDs exactly match their
2026-09-23 post-calibration archives (all four SHA-256 values and archived packet
payloads checked). A contemporaneous owner note describes excellent transmitter
response; that acceptance was unloaded and lacked synchronized command telemetry.
The present evidence does not support loss of the stored calibration. It does not
prove unchanged load, wiring, power or runtime conditions.
Archived attended Hall measurements on 2026-09-24 establish an earlier left
Hall-path defect: states [1,3,5,7], incomplete six-state table, firmware failure.
The right returned [1,2,3,4,5,6] and succeeded. Those measurements changed no
configuration. Left Sensorless / right Hall was already the accepted post-
calibration configuration; the left Hall circuit was not proved repaired. This
historical defect does not identify the current cause affecting both motors.
The current-boot Linux journal contains USB enumeration EPROTO (-71) on port1-3
and a later disconnect on port1-2 on October17. Pre-enumeration events cannot
reliably be bound to a controller UUID. No later physical disconnect appears in
the captured kernel journal, despite historical userspace native failures.
Linux documents EPROTO as an ambiguous USB failure, not a specific cable or
controller diagnosis. Current MCU counters show one USB configuration and zero
write timeouts on each controller, with no stored faults since startup. Those
counters do not cover earlier boots or failed host enumeration.
Raw read-only baseline, historical comparisons and source links are retained in
the task's vesc-qml-diagnostics-20261018 evidence. No motor operation, calibration,
power cycle, firmware update or controller configuration write was performed for
this investigation.
@@ -0,0 +1,81 @@
# Sample Data and interactive QML
Node 0.8.49-28 / VESC 0.17.0 adds two domain renderers inside the existing
FeatureSettingsWindow. All controls use Design Guideline exports. Sample Data
never arms on opening a page. QML never opens on selecting a package/source.
## Native Sample Data
The existing per-attachment VESC Tool owner receives Commands::samplesReceived.
The live profile is FW5.02: eight Auto32 numbers plus status/phase (34 bytes),
2000 samples maximum, third phase current derived from the first two. The
firmware has no raw-ADC flag, sample index, ACK, timestamp or capture identity.
NOW/START return the requested length; triggered modes return the full ring.
The host's capture UUID must never be described as an MCU-generated event ID.
The nominal interval uses decimation / reported sampling frequency.
Capture state is asynchronous; start/status/stop/fetch/read RPCs do not block
while waiting for a motor start/fault. RAM contains one buffer per USB owner,
up to 2000 rows, read in pages of 128. Deadline 2–120 seconds sends OFF; five
minutes discard RAM. A new capture waits for one second of quiet after a prior
transfer. Malformed/partial data is explicit, not padded with zeroes. Fetching
last samples is marked unverified because the firmware cannot prove provenance
or trigger completion. USB loss destroys host session authority; no stop ACK
can be claimed after detachment, and the controller may still retain a buffer.
During capture, configuration/firmware/code writes, measurements and temporary
CAN target operations are excluded. Ordinary driving is not initiated, claimed,
stopped or changed by capture. Stop is COMM_SAMPLE_PRINT/OFF, never a motor
command. Native qualification uses a disconnected upstream Commands serializer
and synthetic packets; no Sample Data acquisition was run on the rover.
The UI compares up to four signals, selects an interval, offers bounded FFT only
for a complete uniform buffer, and exports CSV/JSON with a capture passport.
The log analyser imports original Sample Data CSV including Tool7's trailing
semicolon on data rows only. Unindexed loss cannot be placed at an exact time;
an incomplete time axis is only an estimate from received samples.
## Interactive QML
A single isolated Qt Quick child preserves object state and accepts bounded
pointer, wheel, key and text events over private stdin/stdout. It renders a
640x480 PNG on each interaction or explicit refresh. No socket/USB connection
is handed to QML; outgoing Commands remain discarded. Default opening requires
no controller queries. An explicit snapshot option reads configurations/values
once. This is interactive viewing, not full device-command execution or video.
Limits: 32 events/frame, browser queue 128 events, 240 native requests,
60 seconds idle, 300 seconds lifetime, 12 CPU seconds, 512 MiB address space,
64 FDs, 512 KiB PNG, 6-second parent RPC deadline. The parent kills/reaps failed
children; discovery maintenance closes expired/detached sessions. Source,
section and session changes close the viewer. One child globally avoids an
unbounded process pool. Landlock/seccomp and shipped Qt dependencies follow
29_VESC_QML_PREVIEW_AND_DIAGNOSTICS.md. CPU limits for the legacy one-frame
preview remain three seconds. Unsupported imports fail visibly.
QML built around live Lisp/BMS replies or output/write commands still requires
an admitted device broker. These are remaining parity items; original objects
being linked does not grant a package hardware capability.
## Core data lifecycle
Sample Data and QML operation receipts are hydrated from a lock-protected RAM
cache, 64 entries/8 MiB, five minutes and UTC daily reset on access. Database
rows/history retain tombstones without payloads; restart never re-enqueues
an expired ephemeral request. Driver and Node already keep snapshot result
bodies in bounded RAM. This is not a claim that all legacy command fragments
or every package source has become nonpersistent. Existing records are not
removed by this increment.
## Acceptance scope
Native decoding, command serialization, timeout, QML clicks/state/text/key
input, containment and cleanup are software-qualified with fixtures. Python,
Core queue/cache and frontend CSV/FFT tests cover the adapters. Normal versioned
Ubuntu build and owner installer carry the same runtime. Current owner scope
excludes motor starts, fresh captures/logging, calibration, configuration writes,
firmware flashing, Lisp execution and a fresh-Ubuntu test. Hardware acquisition
and dangerous operation qualification remain explicit future work.
Remaining diagnostic priorities and upstream module review are retained in
outputs/vesc-samples-20261018/module-audit.txt. Full Tool parity is not claimed.
@@ -0,0 +1,75 @@
# Saved Sample Data analysis
Node0.8.49-29 / VESC0.17.1 extends the existing Sample Data section. It adds no
hardware operations, no telemetry subscriptions, no server-side file storage,
and no product navigation. Native VESC Tool remains7.00 at
01d5f10901116c311e3fb84d5a1541f663d3ce20; the native bundle is unchanged.
## Operator job and composition
The operator opens one or two existing captures to inspect current/Hall/phase
relationships, measure a selected interval and compare saved controller data.
The accepted placement is domain content inside the existing VESC settings
Sample Data section. A separate workspace would split capture and inspection;
the general CSV log analyser remains available for long RT/log-analysis files.
This is class A under the surface-extension protocol, not a new shared control.
SettingsCard, Description, Button, Select, RangeControl, ComparisonTable and
StatusBadge are existing DG exports. SignalPlot is the existing domain SVG
renderer; cursor strokes and discrete-state steps are data annotations.
Empty: open A/B; loading: file buttons disabled; error: retained old valid data
and explicit rejection; loaded: passports, interval, filters, cursors, plots,
measurements and optional FFT; expiry/close: discard RAM. Unsupported live
hardware does not block offline imports. No demonstration data is preloaded.
## Provenance and bounds
Each file is at most4MiB/2000samples. JSON schema
missioncore.vesc.sample-data/v1 validates indices, finite values, cadence,
state/count agreement and MCU UUID syntax. Metadata always comes from the
file, never the currently selected VESC. Export freezes the passport at read
time, so a subsequent status response cannot relabel a previous buffer.
Original VESC Tool Sample Data CSV includes its asymmetric trailing delimiter.
CSV has no identity/completeness proof; missing Hall/sampling columns remain
absent. A/B times start at zero independently: no capture synchronization or
causal correlation is claimed. FW5.02 loss positions cannot be reconstructed.
Partial/unverified passports disable FFT. CSV FFT is explicitly an analysis of
presented rows with unknown transfer completeness. All sources stay in browser
RAM for at most five minutes, with UTC daily reset and unmount cleanup.
## Numerical semantics
FIR coefficients match DigitalFiltering::generateFirFilter from the pinned
Tool: mirrored rectangular frequency bins, real normalized inverse transform,
fftshift, optional Hamming. Taps=2^bits, bits1..10, normalized cutoff0..0.5.
Moving mean uses uniform coefficients. Only I1/I2/I3 are filtered. Valid
convolution positions and optional half-window delay compensation match Tool.
Unlike Tool's padding, unsupported edges are null, never invented zero current.
Missing samples/irregular cadence break the filtered trace. Source arrays are
immutable. The bounded direct transform costs at most1024^2 operations per
coefficient change; coefficients and traces are memoized separately.
Cursors snap numerically to the nearest sample; readout reports actual times,
values, delta and elapsed time. Missing/out-of-source values remain absent.
Interval count/min/max/RMS and FFT use the displayed data. Discrete Hall and
commutation traces use steps. Signals retain separate vertical scales. Windows
shorter than1ms now use the entire plot width, including other SignalPlot users.
ResizeObserver supplies the actual SVG width, retaining readable12px axis text
and the chosen plot height in narrow modals; its observer disconnects on close.
FFT uses existing Hann/demean normalization and uniform-step checks; it selects
the last power-of-two count up to1024 in the bounded2000-sample capture. No
algorithm diagnoses a mechanical or electrical cause from these numbers alone.
## Acceptance boundary
Synthetic passport/CSV, invalid data, independent metadata, original FIR
coefficient vectors, convolution/delay, missing edges, cursors, short time axes
and FFT invariants are unit-tested. UI acceptance uses clearly labelled local
synthetic files only and sends no VESC operation. Standard Ubuntu qualification
and versioned installer ship the shared UI to the board. Core8000 is on the
operator Mac. No motor, capture/logging, calibration, configuration write,
firmware flash, Lisp execution or new-Ubuntu test is authorized in this pass.
Full VESC Tool parity remains open, particularly admitted live QML hardware
operations, motor/USB command-response correlation and remaining tools.
+45
View File
@@ -0,0 +1,45 @@
# QML hardware read broker
Node 0.8.49-30 / VESC adapter 0.18.0. Tool 7.00 remains pinned to
01d5f10901116c311e3fb84d5a1541f663d3ce20. This increment is not full Tool parity.
The existing QML page offers disconnected mode, a one-time controller snapshot,
and an explicit read-only hardware broker. No data acquisition starts when a
section is opened. The isolated Qt process retains no USB/socket descriptor.
Its real upstream Commands objects emit typed read intents to the parent service;
the existing exclusive native owner validates and constructs the USB operation.
Only FW identity, values, MC/APPCONF, PPM, ADC, Nunchuk, IMU mask and BMS values
are admitted. Firmware compatibility remains checked in the native engine.
The QML connection indicator represents the broker session. Upstream transport
stays closed, and writes/raw packets/CAN forwarding/terminal/Sample Data/Lisp/
flashing are blocked. All other action workflows still use their existing
prepare/confirm gates. This is not unrestricted execution of arbitrary packages.
On open, three queries establish the configuration/value context. Subsequently,
only interaction/Refresh frame services at most two reads, at most two batches
per second, with 1s per-command cooldown (10s for identity/configuration). There
is no background reader. A bounded nine-command queue coalesces duplicates;
responses use actual upstream decoding/signals, not replay of old telemetry.
The last reply time, read count, pending count and rejected commands are visible.
Controls use the existing Design Guideline Checker/Button/Description components.
A session is bound to device and USB session identity, lasts at most 5 minutes,
expires after 60s idle / 240 exchanges, and closes on disconnect, navigation,
source replacement, timeout or invalid reply. CPU/memory/filesystem/network
confinement and transient Core/Node receipt lifecycles are unchanged.
Validation covers exhaustive 256-command classification, malformed/trailing
payloads, batch atomic rejection, pacing, queue coalescing, stale session, busy
owner, response mismatch, actual Qt input and real Commands receive signals
using synthetic packets. These checks perform no physical motor/capture/flash.
End-to-end acceptance separately reads ordinary values through Core, then closes
QML; it does not start Sample Data, logging or any write operation.
Remaining diagnostic work: opt-in command/response/USB correlation, explicit
rotor/Hall mode admission, CAN Analyzer reception and full diagnostic console.
Original Debug Print is the Tool's Qt/application/status console (mainwindow.cpp
and pagedebugprint.cpp), not an automatic MCU/USB root-cause recorder. MCU terminal
prints, Linux USB events and native exchange failures must remain distinct in a
combined diagnostic report. Never infer a physical fault cause from one timeout.
No new fault collection or physical diagnosis is claimed by this release.
@@ -0,0 +1,50 @@
# VESC diagnostic report review
Node0.8.49-31 adds the same report projection to Core and onboard UI. The
native broker/engine remains VESC0.18.0 from qualified Node30.
## Product-surface admission
Class A: additional domain content in the existing VESC USB/error section.
The operator reads hw_status/faults and compares two explicit reads. Keep the
existing section rather than creating another console/workspace: it owns the
same controller and read lifecycle. Reuse SettingsCard, ComparisonTable compact,
Description and Button. No new DG geometry, states, icons or navigation.
The summary precedes optional original text. Missing/ambiguous counters stay
unknown; duplicate lines, overflow or negative values never become zero.
Fault entries retain original code and fields, including unrecognised fields;
no-error is recognised only from the exact firmware phrase. Reports end at
native print quiescence, not a firmware completion ACK. Partial reports are not
certified complete. A historical fault is not declared currently active.
The comparison uses controller ID, firmware/hardware identity, verified UUID in
hw_status, USB session and ordered observation times. Reduced counters suppress
all deltas (possible reset/overflow); same counters do not prove absence of USB
failure/reboot. Config events alone are not diagnosed as cable failures.
At most current and explicitly selected baseline live in window RAM. Each
expires after five minutes using monotonic and wall time, on UTC day change,
controller/session replacement, offline transition or section close. The timer
only expires memory; it never sends controller commands. Existing read receipt
storage semantics are unchanged; this is not an end-to-end persistence claim.
## Scope and verification
No protocol commands, USB owner, board dependencies, firmware admission, motor
controls or logger are added. Only existing vesc.diagnostics.read is used after
a button click. No new acquisition, output, configuration or flashing test.
The parser follows terminal.c hw_status/faults (original VESC firmware), with
redacted synthetic fixtures based on the previously retained 5.02 responses.
Local helper source: work/vesc-upstream/terminal.c in the owner investigation.
Missing Runtime in the installed firmware is not invented from wall-clock time.
Meaningful software checks cover partial/duplicate fields, bad identities,
changed USB session, reset/overflow, expired/reordered data, repeated faults,
unknown fields and TTL/day-boundary behaviour. UI acceptance and qualified
installer evidence are retained in outputs/vesc-diagnostic-review-20261018.
Remaining diagnostics: opt-in incident correlation, typed rotor/Hall stream
admission, CAN Analyzer and full debug-message console. This review does not
close full VESC Tool parity or establish the physical USB/low-speed cause.
+61
View File
@@ -0,0 +1,61 @@
# Rotor/Hall observations in saved Sample Data
The existing Sample Data analysis surface now reviews raw Hall states, observed
state spans, single/multiple-bit changes, phase steps and absolute motor current.
The A/B summaries follow the selected interval. A paginated event list moves the
existing Hall, electrical phase and current plots/cursors to an observed feature.
No transport, timer acquisition, logging, output lease or controller writes are
introduced. Imported files retain the existing 2000-row, 4 MiB, five-minute RAM
and UTC-day limits. Closing the section clears them.
This is an additional analysis view of original VESC Tool Sample Data, not the
live Rotor Position stream and not a physical stall detector. On FW5.02,
`mc_interface.c:1798` stores `mcpwm_foc_get_phase()` as an eight-bit angle using
250 steps/revolution; line1835 stores `mcpwm_read_hall_phase()` in three bits.
The phase is electrical control phase, not an independent shaft measurement.
CSV may lack Hall or provenance; unavailable fields never become zero.
A multi-bit difference between consecutive received samples may be decimation
or packet loss. No invented Hall order, direction or commutation fault is inferred.
0/7 are shown as observations; significance depends on connected/enabled sensors.
No all-six-state requirement is imposed on a short recording. A constant state
is not classified as stuck. Phase differences are shortest wrapped differences;
180 degrees is ambiguous, larger inter-sample motion is unknowable. Missing or
invalid samples break adjacency. No velocity or mechanical angle is inferred.
Unknown loss location in non-indexed FW5.02 data remains explicitly uncertain.
## Live Rotor Position admission remains separate
FW5.02 `commands.c:432-445`: COMM_SET_DETECT changes a display mode and resets
the control timeout in every mode; NONE releases a BLDC motor, INDUCTANCE starts
detection. It is not admitted through the QML read broker or a generic read API.
The new review does not send this command. Future live streaming must explicitly
own that operation, type-check motor/mode and bound cleanup without disguising
it as read-only. No live capture was used for this release's acceptance.
## Product surface
Class A: domain content in the existing VESC Sample Data section, using
SettingsCard, ComparisonTable, Select, ResourceRow/List, Description and Button.
A separate navigation destination was rejected: it would duplicate the same
file lifecycle, interval and plots. Empty state remains the existing import
prompt. Hardware availability does not gate offline analysis. Actions only
navigate already loaded data; no automatic upload or capture.
## Parameter editor spacing
LoadingRegion was the single grid child of SettingsCard; its nested selects,
search, helper and list therefore lost the parent gap. Manual read loading belongs to its button; the redundant region is replaced by
the existing sensor-content token stack. The same correction covers BMS and
peripheral/terminal reads; the independent backup list load retains its region
with that stack. Export/import and draft actions use the
existing wrapping sensor-actions group. The same grouping covers Sample Data
export. Design Guideline COMPONENTS.md documents wrappers preserving spacing.
## Acceptance boundary
Synthetic checks cover all six states in both orders, 0/7 runs, missing/invalid
channels, multi-bit transitions, gaps, phase wrap/half-turn ambiguity, interval
edges, event focus, legacy CSV, limits and immutability. Browser acceptance uses
synthetic files and ordinary configuration reads only. Motor output, Sample Data
start/fetch, logging, calibration and flashing are excluded.
+278
View File
@@ -0,0 +1,278 @@
# VESC control transport
The onboard VESC profile owns the transport used by Observation Center commands.
The operator chooses a common USB/CAN route or different routes for assigned
motors in the existing board settings. No motion is produced by opening or
saving this editor. The built-in VESC Tool uses the same selected endpoint for
its operations. A separately launched upstream desktop Tool owns its own
connection settings; this integration does not modify that application.
Controller CAN ID/bitrate and the board connection choice remain separate.
Changing a board route never rewrites controller configuration.
## Identity and availability
- Motor positions are bound to MCU UUID, never a tty number or physical USB port.
- USB and CAN endpoints for the same UUID produce one controller in inventory.
- CAN availability requires a firmware reply with the assigned UUID; detecting a
USB-CAN adapter does not establish controller availability.
- Initial defaults use verified USB, or the single verified CAN route when USB
is absent. When no route is verified, the UI shows unavailable.
- Explicit saved routes remain sticky across disconnect/reboot. There is no
automatic fallback in an active control session.
- Configured offline controllers remain in the inventory so board profile
metadata can be edited without a live VESC USB connection.
- FW 5.02 CAN ID and baud rate are obtained from verified configuration backups
and bounded read-only refreshes over USB. Unknown wiring or a different
configuration schema does not become a guessed usable endpoint.
## Runtime ownership
The USB-CAN service remains the sole SDK/USB owner. Its existing Unix socket
exposes a separate peer-UID-restricted bridge API to mission-core-vesc.
A channel lease lasts 750 ms and is renewed while the bridge is alive.
Manual analyser configuration, transmit, clear, start and stop cannot compete
with a leased channel. Closing the last lease stops that channel.
The pinned upstream VESC Tool continues to encode commands and enforce its
configuration, lease and watchdog guards. A private TCP bridge connects native
Tool to VESC CAN buffer framing. Only 127.0.0.1 in the VESC service's existing
PrivateNetwork=yes namespace is used. AF_INET is added by the shipped unit;
the namespace has no LAN or internet interface. No additional host listener,
route, capability, external service or system Python package is introduced.
CAN transmissions use classic extended frames. As of USB-CAN 0.2.7, exact
unicast native duty/current/RPM setters, the existing 250 ms PPM-output inhibit,
and six argument-free reads use normal transmission with adapter self reception.
Only one frame is submitted; the bridge waits for its exact echo within the
caller deadline and at most 40 ms. An error or missing/late echo retires every
claim on that channel and resets it. There is no application replay or silent
fallback. Other commands retain their existing classification: complete
acknowledged limits/configuration writes use their VESC ACK path; unclassified
packets stay single-shot. Responses validate target, size and CRC.
The private FIFO marker follows completion of those sends, so native setter
success now includes the adapter echo. This is not a VESC application ACK and
does not prove physical motor movement. DEV records the confirmation kind,
count and elapsed time separately in the existing CAN diagnostics.
An active manual control session pins profile revision, drive revision, UUID and
attachment session. Detach, replacement or changed selection terminates it.
The existing neutral checks, RC takeover, volatile current limits, native output
watchdog and controller command timeout remain in force.
## Portable installation
Node 0.8.49-64 carries VESC profile 0.20.6 and USB-CAN profile 0.2.7 and is
installed on Rover006. Earlier dated qualification entries below describe their
own releases; they do not override the current transport policy above.
The normal owner installer includes all Python bridge modules, pinned native
Tool runtime, Waveshare SDK, udev rules, service definitions and preparation
steps. A newly created VESC service account is admitted by the already-running
CAN service without a manual restart/permission repair.
The supported environment remains Ubuntu 24.04 amd64 with systemd. Other
OS/architectures must pass explicit dependency/driver qualification; no universal
OS compatibility is asserted. No clean-host experiment is required by this
change. Persistent controller metadata and transport choices live in the VESC
state directory and are separate from OS enumeration and the compiled payload.
Rollback preserves configuration files. A release predating the transport
profile supports USB only; its transport must be reviewed before manual driving.
## Validation boundary
Synthetic tests cover CAN fragmentation and CRC, expired/reconnected sessions,
UUID mismatch, common and mixed transport selection, offline inventory,
exclusive channel ownership and fail-closed loss of the selected bus.
The native artifact qualifies a loopback peer without loading the USB-CAN SDK
or opening hardware. Existing VESC/USB-CAN regression tests cover the prior
control guards. Physical movement, flashing, captures and diagnostic recordings
are excluded from assistant acceptance; manual driving belongs to the operator.
The Node inventory admits assigned offline UUID metadata and verified selected
CAN sessions from the installed VESC driver. Its direct USB attachment guard
remains unchanged for USB controllers and other protocol-identified devices.
## CAN status polling correction (2026-10-21)
A live bridge lost its lease after the adapter service rejected its poll with
“adapter busy”. NativeLink now preserves the original bridge failure before
cleanup instead of reporting only a generic process exit. Contention failures
also identify the SDK operation holding ownership and its elapsed duration.
While bridge claims exist, status returns the worker's RAM snapshot without
calling the vendor USB enumeration function. Exact sysfs USB generation checks,
RX failures, 750 ms lease expiry and transmission deadlines remain unchanged.
Synthetic regression covers status without USB enumeration and removal of an
adapter with an active claim. No timeout extension or transmission retry was
introduced. Live CAN1 identity remained in one session for 166 seconds after
initial retries; CAN2 has no replies yet. This establishes one connection, not
motion acceptance or complete CAN commissioning.
## CAN-only follow-up (2026-10-21)
After the operator rewired the second CAN pair, both controller UUIDs were read
through their independent CAN channels with direct controller USB unplugged.
Core saved an explicit CAN profile for both drive positions (revision1). A
normal live-view check exposed recurring read deadlines; the earlier idle
identity-session acceptance does not establish continuous telemetry readiness.
Node38/VESC0.19.3 gives passive CAN observation300ms instead of the
USB/control-loop60ms budget. Motor-loop limits, bridge lease and single-shot
transmissions are unchanged. Bounded bridge request/reply counts and elapsed
latency accompany existing failure records; no payload history is retained.
The candidate passed its offline qualification. The first installation was
rejected while automatic CAN claims were active. After operator USB-adapter
detach, the same normal installer completed at2026-10-21T16:43:12.882077Z
(session3332fe7341144c90be8e44873e186cef). Node38/VESC0.19.3/USB-CAN0.2.1 are
installed and active; source hashes match and the saved CAN profile remains
revision1. Adapter USB reconnect and read-only live acceptance are pending.
Continuous CAN telemetry and physical control remain unqualified. Evidence:
outputs/vesc-control-transport-20261021/release-proof38-installed.json.
## Read transport and immediate detach correction (2026-10-21, candidate39)
Node38 live acceptance failed: zero of27 evaluated snapshots contained both
fresh controllers. Existing bridge failure metadata showed accepted sends in
about1–2ms, successful replies in about15–16ms, and missing replies even at
300ms/2000ms. Extending the read timeout alone did not restore the link.
The vendor API manual (chapter2.5) documents that transmit_type1 discards a
frame after arbitration loss or a bus error. Candidate39 uses transmit_type0
only for a single exact PROCESS_SHORT_BUFFER request containing an argument-free
FW_VERSION, GET_VALUES, GET_MCCONF, GET_APPCONF or GET_DECODED_PPM command.
The response address must match its owner, and broadcasts/self-targets are
excluded. Motor, lease, write, forwarding, fragmented and unknown packets retain
single-shot transmission; no application replay is introduced. Existing request
deadlines and lease expiry still close/reset the channel after failure. Vendor
acceptance of a send is not treated as a proved response or motor execution.
This is a documented transport defect correction; arbitration loss on the
physical rover is a hypothesis until runtime acceptance, not a measured fact.
Source:https://files.waveshare.com/wiki/USB-CAN-FD/Manual/USB-CAN-FD-B-API-Manual.pdf.
Node inventory previously checked a VESC-reported adapter list without checking
current OS USB presence. Candidate39 carries the exact provisional USB generation
from the adapter driver and invalidates a selected CAN route against the Node's
fresh sysfs inventory. A stale driver cannot keep that route online after detach
or revive it on replug with a different USB generation. UUID, saved assignments
and transport choices remain available as offline settings. Synthetic tests
cover immediate detach/replug and every command byte's retransmission policy.
Node0.8.49-39, VESC0.19.3 and USB-CAN0.2.2 were installed through the qualified
owner installer after operator USB detach, completed at2026-10-21T17:09:02.434869Z
(session744b7f463c704308b4e67c1b1637a901). Nine runtime hashes match the source.
Two30-read ordinary Core live-view checks, before and after a real USB reconnect,
each passed27/27 evaluated snapshots after warm-up, with one stable session per
UUID, fault code0 and maximum ages311ms/305ms. On disconnect, the first Core
inventory with the adapter absent also invalidated both VESC routes; no stale
online inventory was observed with0.5s polling. The operator confirmed immediate
UI disappearance. Reconnect created new sessions automatically and retained the
exact saved routes at revision1. All three services stayed active with NRestarts=0.
Core8000 is healthy and the normal installer catalogue now publishes Node39 with
the qualified SHA. The operator accepts the reported approximately17s startup
latency; no startup optimization is requested. This proves bounded live reading
and one physical hotplug cycle, not motor delivery, long-duration reliability,
clean-OS qualification or the physical cause of earlier lost CAN replies.
No motor, flashing, raw capture or diagnostic recording was initiated. Evidence:
outputs/vesc-control-transport-20261021/release-proof39-installed.json.
### Node40: neighbour-query coverage and bounded acceptance
The human control-preparation attempt on Node39 failed at COMM_PING_CAN/query62,
before claiming outputs or applying temporary motor limits. This generic native
read was missing from the normal hardware-transmission allowlist. Node40 adds
only the exact argument-free62 request; forwarded/broadcast/argument-bearing
requests and all output commands retain the prior single-shot policy. No motor
lease or query deadline was extended and no application replay was introduced.
Node0.8.49-40, VESC0.19.3 and USB-CAN0.2.3 are installed through the owner
installer and published in Core's normal catalogue. After reconnect, two explicit
vesc.can.read operations completed through Core in2.59s/2.59s with matching
UUIDs; subsequent ordinary telemetry passed27/27 evaluated snapshots, max321ms,
fault0 and stable sessions. Saved routes remain revision1 and services are active.
This is bounded read/scan acceptance. Human control preparation, motion,
long-duration reliability and clean-OS qualification remain separate gates.
See the Node40 ledger section and private release-proof40-installed.json.
### Node41: acknowledged volatile-limits transport
The next human preparation step on Node40 reached COMM_SET_MCCONF_TEMP48,
a37-byte fragmented request, but received no ACK within the unchanged native
exchange deadline. Node41 uses normal hardware sending only for the exact
non-storing, non-forwarding, ACK-requested limits packet; CRC, ordered fragments,
unicast target and finite fields must all match. Motor commands and leases
retain single-shot transmission. There is no application command replay or
deadline extension. An unconfirmed limits write retires all claims on its
channel before hardware reset, preventing another reader from keeping an
uncertain hardware queue alive. Only the expected target's exact ACK clears it.
Node41/VESC0.19.4/USB-CAN0.2.4 are installed through the qualified owner
installer. Offline tests and installed hashes passed; saved routes are unchanged.
Physical ACK delivery and human control-preparation acceptance remain pending.
The two previous failures do not prove arbitration loss as the physical cause.
The installation ledger and private release-proof41-installed.json retain scope
and evidence.
Node41 live acceptance: after reconnect, ordinary telemetry passed27/27 evaluated
snapshots with stable sessions and fault0. The human then enabled control and
reported manual movement. Both controller rotation counters increased while
verified routes remained CAN and direct USB tty devices were absent. Ready
state proves the formerly failing volatile-limits ACK/readback stage completed
for both motors. After the human pressed Stop, Core reported stopped,
controlling=false, release_confirmed=true and no restoration error. Both motor
current/ERPM readings were zero, connection sessions unchanged, services active
with no restarts, and the bounded existing failure journal had no entries.
This establishes one bounded human drive/stop cycle; prolonged reliability,
physical packet-loss diagnosis and the separate low-speed stall symptom remain
unqualified. No assistant motor/control/configuration-write operation occurred.
See the Node41 installation ledger and private manual-can41-trial-acceptance.json.
## Confirmed configuration writes over the adapter
USB-CAN 0.2.6 uses normal CAN-controller arbitration for complete, CRC-checked
`COMM_SET_MCCONF` (13) and `COMM_SET_APPCONF` (16) packets generated and validated
by the pinned native VESC Tool. The recognizer accepts contiguous short/long
fragment offsets, one exact destination, the matching length/CRC commit and the
claim's reply address. It excludes forwarding, broadcasts and arbitrary output
commands. Schema validation, identity binding, preview expiry, backup and exact
readback remain owned by the existing configuration editor.
A pending transaction records both target and expected ACK command. Only that
exact reply releases it. Closing or expiring an unconfirmed transaction, another
send before ACK, or a partial-send deadline resets the channel and retires its
shared claims, discarding queued transmission. There is no application-level
replay or automatic configuration rollback. Ordinary motor setpoints retain
single-shot transmission and their existing lease/timeout boundary.
This addresses a gap where long configuration writes used single-shot CAN and
could lose a fragment during arbitration, while short reads and volatile limits
already used normal arbitration. Inert bus tests cover a 458-byte motor packet,
a 313-byte application packet, the offset-width boundary, CRC/address/order
rejection, mismatched ACKs, queue disposal and no replay. Hardware acceptance
and any actual configuration change must be recorded separately in the ledger.
## Bounded adapter confirmation (2026-10-24, Node64)
The 20% operator drive showed constant requested duty while measured output
intermittently became zero. It did not show a broken Core-to-board command
stream in that interval. Single-shot motor/PPM-lease sending could lose a CAN
arbitration while still returning SDK acceptance. Physical loss of those exact
frames remains unproved; the correction removes that unobserved sending path.
376 USB-CAN tests and 418 VESC tests passed, followed by all 24 Ubuntu package
qualification stages. The owner installer upgraded only Node; CAN maintenance
reported motor_commands=false and observation restored. Firmware, Hall tables,
current settings, native watchdog and command TTL were not changed.
Passive acceptance on the actual adapter: 45/45 fresh Core polls, 98 fresh
samples per controller, one unchanged attachment generation each, zero fault,
watchdog and native output counts. Sampled adapter echoes took 0.148–3.346 ms;
no CAN error or connection gap occurred in the 22.897 s DEV record. The closed
file contains 828 events, writer dropped=0. This accepts the read transport and
instrumentation; powered setter behavior and smooth loaded driving require the
operator's next recorded drive. Private source/build/install and complete DEV
evidence: outputs/rover-can-confirmation-20261024/.
@@ -0,0 +1,23 @@
import {Button,Description,TextField,Select,SettingsCard} from '@nodedc/ui-react';
import {swdTargets,type CanFirmwareTarget,type SwdTarget} from './firmwareFiles';
export function FirmwareDestination({mode,onMode,disabled,targets,options,canId,onCanId,scan,read,target,swd,onSwd}:{
mode:string;onMode:(v:string)=>void;disabled:boolean;targets:string[];options:{value:string;label:string}[];canId:string;onCanId:(v:string)=>void;
scan:()=>void;read:()=>void;target:CanFirmwareTarget|null;swd:SwdTarget;onSwd:(v:SwdTarget)=>void;
}){
return <SettingsCard title="Куда записать прошивку" description="Подготовка файла не изменяет flash и не подключает отладчик. Запись начинается только после отдельного подтверждения.">
<Select label="Подключение" value={mode} disabled={disabled} options={[{value:'usb',label:'Этот VESC · USB'},...(targets.includes('can')?[{value:'can',label:'Один контроллер по CAN'}]:[]),...(targets.includes('swd')?[{value:'swd',label:'Внешний процессор по SWD'}]:[])]} onChange={onMode}/>
{mode==='can'&&<><Button disabled={disabled} onClick={scan}>Найти устройства CAN</Button>
<Select label="Адрес CAN" value={canId} disabled={disabled||!options.length} options={options} onChange={onCanId}/>
<Button disabled={disabled||!canId} onClick={read}>Определить контроллер</Button>
{target&&<Description>CAN {target.can_id} · {target.hardware} · FW {target.major}.{String(target.minor).padStart(2,'0')} · UUID {target.uuid.toUpperCase()}</Description>}
<Description>Файл получит только выбранный UUID. При смене устройства на этом CAN-адресе запись отменяется.</Description></>}
{mode==='swd'&&<>
<Description>VESC по USB работает программатором. Проверьте распиновку и допустимые уровни напряжения целевой платы. Подключение SWD останавливает её процессор; запись стирает всю основную flash. Образ должен содержать всё необходимое для запуска. Семейство проверяется перед стиранием; модель платы и её UUID этим протоколом не определяются.</Description>
<Select label="Целевой процессор" value={String(swd.target_code)} options={swdTargets} disabled={disabled} onChange={v=>onSwd({...swd,target_code:Number(v),address:Number(v)>=2&&Number(v)<=8?0:0x08000000,flash_bytes:128*1024})}/>
<Select label="Распиновка программатора" value={swd.pins} options={[{value:'default',label:'Стандартная SWD'},{value:'nrf5x',label:'NRF5x'}]} disabled={disabled} onChange={pins=>onSwd({...swd,pins})}/>
<TextField label="Начальный адрес записи, байт" type="number" value={String(swd.address)} disabled={disabled} onChange={e=>onSwd({...swd,address:Number(e.target.value)})}/>
<TextField label="Доступно от этого адреса, КиБ" type="number" value={String(swd.flash_bytes/1024)} disabled={disabled} onChange={e=>onSwd({...swd,flash_bytes:Number(e.target.value)*1024})}/>
<Description>Укажите диапазон по документации конкретного процессора. BIN начинается с указанного адреса; HEX должен начинаться там же. Option bytes, UICR и периферия исключены. Каждый записанный блок обязательно читается обратно.</Description>
</>}
</SettingsCard>;
}
+36
View File
@@ -0,0 +1,36 @@
import {useEffect,useMemo,useRef,useState} from 'react';
import {Description,Icon,IconButton,SettingsCard} from '@nodedc/ui-react';
export interface SignalPoint {at:number;value:number|null}
const number=(n:number|null)=>n===null?'—':n.toLocaleString('ru-RU',{maximumFractionDigits:3});
export function signalView(points:readonly SignalPoint[],from:number,to:number,height=180,width=800){
const span=Math.max(1,width-84);
const visible=points.filter(p=>p.at>=from&&p.at<=to),valid=visible.filter(p=>p.value!==null&&Number.isFinite(p.value));
let min:number|null=null,max:number|null=null,mean=0;
for(const p of valid){min=min===null?p.value!:Math.min(min,p.value!);max=max===null?p.value!:Math.max(max,p.value!);mean+=p.value!/valid.length;}
const pad=Math.max(((max??1)-(min??0))*.1,Math.abs(max??0)*.01,.001),low=(min??0)-pad,high=(max??1)+pad;
const segments:SignalPoint[][]=[];let line:SignalPoint[]=[];
const flush=()=>{if(line.length)segments.push(line);line=[];};
for(const p of visible){if(p.value===null||!Number.isFinite(p.value))flush();else line.push(p);}flush();
// Min/max per pixel bucket preserves spikes; gaps are never joined.
const render=segments.map(segment=>{const out:SignalPoint[]=[];let bucket:SignalPoint[]=[];let previous=-1;
const emit=()=>{if(!bucket.length)return;const values=[bucket[0],bucket.reduce((a,b)=>a.value!<b.value!?a:b),bucket.reduce((a,b)=>a.value!>b.value!?a:b),bucket.at(-1)!];out.push(...[...new Set(values)].sort((a,b)=>a.at-b.at));bucket=[];};
for(const p of segment){const x=Math.floor((p.at-from)/Math.max(Number.EPSILON,to-from)*span);if(x!==previous){emit();previous=x;}bucket.push(p);}emit();
return out.map(p=>({x:64+(p.at-from)/Math.max(Number.EPSILON,to-from)*span,y:20+(1-(p.value!-low)/(high-low))*height}));});
return {segments:render,min,max,mean:valid.length?mean:null,count:valid.length,low,high};
}
export function SignalPlot({title,unit,points,from,to,xUnit='с',xScale=1000,cursors=[],step=false}:{title:string;unit:string;points:readonly SignalPoint[];from:number;to:number;xUnit?:string;xScale?:number;cursors?:readonly number[];step?:boolean}){
const [expanded,setExpanded]=useState(false),[width,setWidth]=useState(800),height=expanded?384:160,span=Math.max(1,width-84);
const svg=useRef<SVGSVGElement>(null);
useEffect(()=>{const element=svg.current;if(!element)return;const observer=new ResizeObserver(entries=>{const next=Math.max(160,Math.round(entries[0].contentRect.width));setWidth(old=>old===next?old:next);});observer.observe(element);return()=>observer.disconnect();},[]);
const view=useMemo(()=>signalView(points,from,to,height,width),[points,from,to,height,width]);
return <SettingsCard title={title} description={`Минимум: ${number(view.min)} · максимум: ${number(view.max)} · среднее: ${number(view.mean)} ${unit} · ${view.count} измерений`}
actions={<div className="nodedc-viewport-controls"><IconButton label={expanded?`Свернуть: ${title}`:`Развернуть: ${title}`} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>}>
<svg ref={svg} style={{height:height+56}} className={`vesc-trend-plot${expanded?' vesc-trend-plot--expanded':''}`} viewBox={`0 0 ${width} ${height+56}`} role="img" aria-label={`${title}, ${unit}; ${view.count} измерений`}>
{[0,.5,1].map(f=><g key={f}><line className="vesc-trend-grid" x1="64" x2={width-20} y1={20+f*height} y2={20+f*height}/><text x="56" y={24+f*height} textAnchor="end">{number(view.high-f*(view.high-view.low))}</text></g>)}
{view.segments.map((line,i)=>line.length===1?<circle key={i} className="vesc-trend-point" cx={line[0].x} cy={line[0].y} r="2"/>:<polyline key={i} className="vesc-trend-line" points={line.flatMap((p,j)=>step&&j?[`${p.x},${line[j-1].y}`,`${p.x},${p.y}`]:[`${p.x},${p.y}`]).join(' ')}/>)}
{cursors.map((at,i)=>at>=from&&at<=to?<g key={i}><line className="vesc-trend-cursor" x1={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} x2={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} y1="20" y2={height+20}/><text x={64+(at-from)/Math.max(Number.EPSILON,to-from)*span} y="14" textAnchor="middle">{i+1}</text></g>:null)}
<text x="64" y={height+47}>{number(from/xScale)} {xUnit}</text><text x={width-20} y={height+47} textAnchor="end">{number(to/xScale)} {xUnit}</text>
</svg>
{!view.count&&<Description>В этом интервале нет измерений. Пропуски не заменяются нулями.</Description>}
</SettingsCard>;
}
+13 -7
View File
@@ -1,8 +1,14 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useState} from 'react';
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import {useVescEditor} from './useVescEditor';
import {VescChangeReview} from './VescChangeReview';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import type {ConfigurationVersion,SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
export function VescBackups({deviceId,archive,revision}: {deviceId:string;archive:SensorTransport['configurationArchive'];revision:string|null}) {
export function VescBackups({deviceId,archive,revision,editorProps}: {deviceId:string;archive:SensorTransport['configurationArchive'];revision:string|null;editorProps:ReadProps}) {
const editor=useVescEditor(editorProps);
const [reload,setReload]=useState(0);
const [items,setItems]=useState<ConfigurationVersion[]>([]);
const [next,setNext]=useState<string|null>(null);
@@ -37,15 +43,15 @@ export function VescBackups({deviceId,archive,revision}: {deviceId:string;archiv
}catch{setError('Не удалось скачать выбранную версию.');}
finally{setDownload(null);}
}
return <SettingsCard title="История конфигураций" description="Сохранённые версии остаются на борту и передаются в Core при подключении." actions={<Button disabled={loading||!archive} onClick={()=>setReload(value=>value+1)}>Обновить историю</Button>}>
<LoadingRegion loading={loading&&!items.length} label="Загрузка версий конфигурации">
{error&&<p role="alert">{error}</p>}
{!loading&&!items.length&&!error&&<p>Сохранённых версий пока нет.</p>}
return <><VescChangeReview editor={editor} pending={vescStatus(editorProps.device).configuration_pending} blocked={editorProps.blocked}/><SettingsCard title="История конфигураций" description="Сохранённые версии остаются на борту и передаются в Core при подключении." actions={<Button disabled={loading||!archive} onClick={()=>setReload(value=>value+1)}>Обновить историю</Button>}>
<LoadingRegion className="sensor-content" loading={loading&&!items.length} label="Загрузка версий конфигурации">
{error&&<Description role="alert">{error}</Description>}
{!loading&&!items.length&&!error&&<Description>Сохранённых версий пока нет.</Description>}
<ResourceList aria-label="Версии конфигурации VESC">{items.map(item=><li key={item.id}>
<ResourceRow title={new Date(item.observed_at).toLocaleString()} description={`Прошивка ${item.firmware} · мотор и входы`}
actions={<Button disabled={download!==null} loading={download===item.id} onClick={()=>void save(item.id)}>Скачать</Button>}/>
actions={<><Button disabled={download!==null} loading={download===item.id} onClick={()=>void save(item.id)}>Скачать</Button>{editor.available&&<Button disabled={editor.busy||editorProps.blocked} onClick={()=>void editor.prepare({backup_id:item.id})}>Сравнить и восстановить</Button>}</>}/>
</li>)}</ResourceList>
</LoadingRegion>
{next&&<Button loading={loading} disabled={loading} onClick={()=>void more()}>Ещё версии</Button>}
</SettingsCard>;
</SettingsCard></>;
}
+86
View File
@@ -0,0 +1,86 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {VescBmsConfiguration} from './VescBmsConfiguration';
import {vescStatus} from './model';
import {bmsCommands,bmsNumber,bmsCells,bmsCellSummary,bmsTemperature,bmsCanOptions,type BmsReading,type BmsPreview} from './bmsView';
const fields=[['v_tot','Напряжение батареи, В'],['v_charge','Напряжение зарядки, В'],['i_in','Ток батареи, А'],['i_in_ic','Ток измерителя, А'],['ah_cnt','Счётчик заряда, А·ч'],['wh_cnt','Счётчик энергии, Вт·ч'],['soc','Заряд, %'],['soh','Остаточная ёмкость, %'],['ah_cnt_chg_total','Заряжено всего, А·ч'],['ah_cnt_dis_total','Разряжено всего, А·ч'],['wh_cnt_chg_total','Энергия заряда всего, Вт·ч'],['wh_cnt_dis_total','Энергия разряда всего, Вт·ч'],['humidity','Влажность, %'],['pressure','Давление, Па']] as const;
function Values({reading}:{reading:BmsReading}){
const values=reading.values??{},cells=bmsCells(values),summary=bmsCellSummary(values),temps=Array.isArray(values.temps)?values.temps.slice(0,32):[];
if(reading.state!=='received')return <SettingsCard title="Ответ BMS"><Description>{reading.state==='not_bms'?'По этому адресу ответило другое устройство. Выберите BMS.':reading.state==='unsupported'?'Чтение BMS не поддерживается текущей прошивкой.':'Ответ BMS не получен.'}</Description></SettingsCard>;
if(!cells.length)return <SettingsCard title="Данные батареи"><Description>VESC ответил без данных ячеек. Наличие подключённой BMS не подтверждено.</Description></SettingsCard>;
return <>
<SettingsCard title="Батарея" description={`Снимок получен ${new Date(reading.observed_at).toLocaleString('ru-RU')}. Он не обновляется автоматически.`}>
{reading.source!=='direct_can'&&<Description>Это сохранённые сведения из VESC. Прошивка 5.02 не сообщает адрес BMS и возраст этих измерений; наличие связи с батареей по этому ответу определить нельзя.</Description>}
<ResourceList aria-label="Показатели батареи">{fields.filter(([key])=>key in values).map(([key,label])=><li key={key}><ResourceRow title={label} description={bmsNumber(values[key],3,key==='soc'||key==='soh'?100:1)}/></li>)}</ResourceList>
{typeof values.status==='string'&&values.status&&<Description>{values.status}</Description>}
</SettingsCard>
<SettingsCard title="Ячейки" description="Номер соответствует порядку ячеек в ответе BMS. Балансировка показана на момент чтения.">
{summary&&<ResourceList aria-label="Разброс напряжений"><li><ResourceRow title="Минимум / максимум" description={`${bmsNumber(summary.min)} / ${bmsNumber(summary.max)} В`}/></li><li><ResourceRow title="Разброс" description={`${bmsNumber(summary.spreadMv,1)} мВ`}/></li></ResourceList>}
<ResourceList aria-label="Напряжения ячеек">{cells.map(cell=><li key={cell.index}><ResourceRow title={`Ячейка ${cell.index+1}`} description={`${bmsNumber(cell.voltage)} В · ${cell.balancing===null?'балансировка не сообщается':cell.balancing?'балансируется':'не балансируется'}`}/></li>)}</ResourceList>
</SettingsCard>
<SettingsCard title="Температуры">
<ResourceList aria-label="Температуры батареи">{temps.map((v,i)=><li key={i}><ResourceRow title={`Датчик ${i+1}`} description={bmsTemperature(v)}/></li>)}
<li><ResourceRow title="Измеритель" description={bmsTemperature(values.temp_ic)}/></li><li><ResourceRow title="Самая горячая ячейка" description={bmsTemperature(values.temp_cells_highest)}/></li><li><ResourceRow title="Датчик влажности" description={bmsTemperature(values.temp_hum_sensor)}/></li>
</ResourceList>
</SettingsCard>
</>;
}
export function VescBms(props:ReadProps){
const {device,transport,failure}=props,status=vescStatus(device);
const [source,setSource]=useState('proxy'),[reading,setReading]=useState<BmsReading|null>(null);
const [options,setOptions]=useState<{value:string;label:string}[]>([]),[canId,setCanId]=useState(''),[scanned,setScanned]=useState(false);
const [busy,setBusy]=useState(false),[command,setCommand]=useState('charge_disable');
const [preview,setPreview]=useState<BmsPreview|null>(null),[confirmed,setConfirmed]=useState(false),[isolated,setIsolated]=useState(false);
const [result,setResult]=useState<{state:string;command:string;target:{can_id:number;uuid:string}}|null>(null);
const running=useRef(false),mounted=useRef(true);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const supported=status.engine?.contract?.methods.includes('bms_read')===true;
const available=props.enabled&&device.online&&device.verified&&status.readable;
const disabled=!available||props.blocked||busy;
const call=<T,>(action:string,p:Record<string,unknown>={})=>perform<T>(transport,device,action,p,30000);
async function run(work:()=>Promise<void>){
if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
try{await work();}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
function reset(){setReading(null);setPreview(null);setConfirmed(false);setIsolated(false);setResult(null);}
const scan=()=>run(async()=>{const value=await call<{can_ids:number[]}>('vesc.can.read');if(mounted.current){const choices=bmsCanOptions(value.can_ids);setOptions(choices);setCanId(choices[0]?.value??'');setScanned(true);reset();}});
const read=()=>run(async()=>{reset();const value=await call<BmsReading>(source==='proxy'?'vesc.tools.read':'vesc.bms.read',source==='proxy'?{tool:'bms'}:{can_id:Number(canId)});if(mounted.current)setReading(value);});
const prepare=()=>run(async()=>{setPreview(null);setResult(null);setConfirmed(false);setIsolated(false);const value=await call<BmsPreview>('vesc.bms.prepare',{can_id:Number(canId),command});if(mounted.current)setPreview(value);});
const apply=()=>run(async()=>{if(!preview||!confirmed||!isolated)return;const plan=preview;setPreview(null);setConfirmed(false);setIsolated(false);setReading(null);const value=await call<{state:string;command:string;target:{can_id:number;uuid:string}}>('vesc.bms.apply',{preview_id:plan.preview_id,confirmed:true,inputs_isolated:true});if(mounted.current)setResult(value);});
return <div className="sensor-content">
<SettingsCard title="Аккумулятор BMS" description="Данные батареи и адресные команды через CAN выбранного контроллера.">
<Select label="Источник данных" value={source} options={[{value:'proxy',label:'Сведения через VESC'},...(supported?[{value:'direct',label:'BMS по CAN-адресу'}]:[])]} disabled={disabled} onChange={v=>{setSource(v);reset();}}/>
{source==='direct'&&<>
<Button disabled={disabled} loading={busy} onClick={()=>void scan()}>Найти устройства CAN</Button>
{options.length>0&&<Select label="Адрес устройства" value={canId} options={options} disabled={disabled} onChange={v=>{setCanId(v);reset();}}/>}
{scanned&&!options.length&&<Description>Устройства CAN не ответили. Проверьте подключение и питание BMS.</Description>}
<Description>Перед чтением и каждой командой проверяются тип устройства и UUID BMS. Номер CAN сам по себе не определяет батарею.</Description>
</>}
<Button disabled={disabled||(source==='direct'&&!canId)} loading={busy} onClick={()=>void read()}>Прочитать батарею</Button>
</SettingsCard>
<div className="sensor-content">
{reading?.target&&<SettingsCard title="Устройство на CAN"><ResourceList aria-label="Идентификация BMS"><li><ResourceRow title={`CAN ${reading.target.can_id} · ${reading.target.hardware}`} description={`FW ${reading.target.major}.${String(reading.target.minor).padStart(2,'0')} · UUID ${reading.target.uuid.toUpperCase()}`}/></li></ResourceList></SettingsCard>}
{reading&&<Values reading={reading}/>}
</div>
{source==='direct'&&reading?.target?.hardware_type===1&&<SettingsCard title="Управление BMS" description="Каждая команда выполняется отдельно. Повторного выполнения после потери связи нет.">
{!reading.commands_supported?<Description>Установленное ядро поддерживает команды BMS с прошивкой 6.00. Для этой версии доступно чтение.</Description>:<>
<Select label="Действие" value={command} options={bmsCommands} disabled={disabled} onChange={v=>{setCommand(v);setPreview(null);setConfirmed(false);setIsolated(false);}}/>
<Description>{command==='zero_current'?'Калибровка сохраняет смещение измерителя. Отключите зарядку и нагрузку; процедура занимает около двух секунд.':command.startsWith('reset_')?'Обнуляется текущий счётчик. Ранее накопленное значение не восстанавливается этой командой.':command.startsWith('balance_')?'BMS управляет балансировкой по своей конфигурации и состоянию ячеек. Разрешение не означает немедленное включение всех каналов.':'Разрешение зарядки влияет на работу батареи. Перед командой проверьте зарядное устройство и условия зарядки.'}</Description>
<Button disabled={disabled} loading={busy} onClick={()=>void prepare()}>Подготовить команду</Button>
</>}
</SettingsCard>}
{source==='direct'&&reading?.commands_supported&&reading.target&&(reading.target.custom_configs??0)>0&&<VescBmsConfiguration {...props} key={`${canId}-${reading.target.uuid}`} canId={Number(canId)} count={reading.target.custom_configs??0}/>}
{preview&&<SettingsCard title="Подтверждение команды BMS" description="Подтверждение действует одну минуту и только для текущего сеанса.">
<Description>{bmsCommands.find(c=>c.value===preview.command)?.label} · CAN {preview.target.can_id} · UUID {preview.target.uuid.toUpperCase()}</Description>
<Checker label="Подтверждаю команду для этой батареи" checked={confirmed} onChange={setConfirmed} disabled={disabled}/>
<Checker label="Входы управления отключены, нагрузка и зарядка проверены" checked={isolated} onChange={setIsolated} disabled={disabled}/>
<Button variant="primary" disabled={disabled||!confirmed||!isolated} onClick={()=>void apply()}>Отправить команду BMS</Button>
</SettingsCard>}
{result&&<SettingsCard title="Результат команды BMS"><Description role="status">{result.state==='sent_unconfirmed'?'Команда отправлена. BMS не возвращает подтверждение выполнения.':'Итог команды неизвестен: связь прервалась.'} Автоматического повторения нет. Прочитайте батарею заново и проверьте её состояние.</Description><ResourceList aria-label="Адресат команды BMS"><li><ResourceRow title={`CAN ${result.target.can_id}`} description={result.target.uuid.toUpperCase()}/></li></ResourceList></SettingsCard>}
</div>;
}
@@ -0,0 +1,54 @@
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
import {Button,Checker,Description,ResourceList,ResourceRow,Select,SettingsCard,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {groupedParameters,groupLabel,parameterValue,type VescConfig} from './configuration';
import {VescParameterEditor,initialDraft,parseDraft,type Drafts} from './VescParameterEditor';
import {plainDescription,downloadText} from './editorFiles';
interface Snapshot {configuration:VescConfig;schema_sha256:string;pending:boolean}
interface Preview {preview_id:string;changes:{name:string;title:string;before:unknown;after:unknown}[]}
export function VescBmsConfiguration(props:ReadProps&{canId:number;count:number}){
const [index,setIndex]=useState('0'),[value,setValue]=useState<Snapshot|null>(null),[group,setGroup]=useState('all'),[query,setQuery]=useState('');
const [drafts,setDrafts]=useState<Drafts>({}),[editing,setEditing]=useState<string|null>(null),[description,setDescription]=useState<string|null>(null);
const [preview,setPreview]=useState<Preview|null>(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[result,setResult]=useState('');
const running=useRef(false),mounted=useRef(true),file=useRef<HTMLInputElement>(null);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const disabled=busy||props.blocked||!props.enabled||!props.device.online||!props.device.verified;
const call=<T,>(name:string,p:Record<string,unknown>,timeout=60000)=>perform<T>(props.transport,props.device,'vesc.bms.configuration.'+name,p,timeout);
const target={can_id:props.canId,index:Number(index)};
function clear(){setPreview(null);setConfirmed(false);setResult('');}
async function run(work:()=>Promise<void>){if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
async function read(){await run(async()=>{const v=await call<Snapshot>('read',target);if(mounted.current){setValue(v);setDrafts({});setEditing(null);clear();}});}
async function prepare(source:Record<string,unknown>){if(!value)return;await run(async()=>{clear();const p=await call<Preview>('preview',{...target,baseline:value.configuration.packet_sha256,schema_sha256:value.schema_sha256,...source});if(mounted.current)setPreview(p);});}
async function apply(){if(!preview||!confirmed)return;const id=preview.preview_id;await run(async()=>{clear();const r=await call<{verified:boolean;message?:string}>('apply',{preview_id:id,confirmed:true,inputs_isolated:true},120000);if(mounted.current){setValue(v=>v?{...v,pending:!r.verified}:null);setResult(r.verified?'Параметры записаны и проверены повторным чтением. Прочитайте новую конфигурацию.':r.message??'Итог записи неизвестен.');setDrafts({});}});}
async function recover(restore:boolean){await run(async()=>{clear();if(restore){const p=await call<Preview>('restore',target);if(mounted.current)setPreview(p);}else{const r=await call<{verified:boolean;outcome:string}>('reconcile',target);if(mounted.current){setValue(v=>v?{...v,pending:!r.verified}:null);setResult(r.verified?'Итог записи подтверждён.':'Значения отличаются от исходных и ожидаемых. Можно восстановить исходную копию.');}}});}
async function importXml(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;try{if(f.size>32768)throw new Error('XML превышает 32 КБ.');await prepare({xml:await f.text()});}catch(e){props.failure(e);}}
const config=value?.configuration,parameters=config?groupedParameters(config,group,query):[];
const changes=Object.entries(drafts).flatMap(([name,draft])=>{const p=config?.parameters.find(p=>p.name===name);return p?[{name,...parseDraft(p,draft)}]:[];});
return <>
<SettingsCard title="Расширенные настройки BMS" description="Группы, типы, единицы и допустимые значения предоставляет прошивка выбранной BMS. Заводские значения сначала показываются для сравнения.">
{props.count>1&&<Select label="Конфигурация BMS" value={index} options={Array.from({length:Math.min(props.count,8)},(_,i)=>({value:String(i),label:`Конфигурация ${i+1}`}))} disabled={disabled} onChange={v=>{setIndex(v);setValue(null);setDrafts({});clear();}}/>}
<Button disabled={disabled} loading={busy} onClick={()=>void read()}>Прочитать настройки BMS</Button>
{value?.pending&&<><Description>Результат предыдущей записи не подтверждён. При смене CAN-адреса выберите новый адрес этой BMS.</Description><Button disabled={disabled} onClick={()=>void recover(false)}>Проверить запись BMS</Button><Button disabled={disabled} onClick={()=>void recover(true)}>Сравнить с исходной копией</Button></>}
{config&&<>
<Select label="Группа BMS" value={group} options={[{value:'all',label:'Все группы'},...config.groups.map(g=>({value:g.name,label:groupLabel(g.name)}))]} onChange={setGroup}/>
<TextField label="Поиск параметра BMS" value={query} onChange={e=>setQuery(e.target.value)}/>
<ResourceList aria-label="Параметры BMS">{parameters.map(p=><li key={p.name}><ResourceRow title={p.title||p.name} description={`${p.name} · ${parameterValue(p)}`} actions={<>{p.transmittable&&p.type!=='undefined'&&<Button disabled={disabled||value.pending} onClick={()=>{clear();setEditing(editing===p.name?null:p.name);}}>Изменить</Button>}{p.description&&<Button variant="ghost" onClick={()=>setDescription(description===p.name?null:p.name)}>Описание</Button>}</>}/>
{editing===p.name&&<VescParameterEditor parameter={p} value={drafts[p.name]??initialDraft(p)} disabled={disabled||value.pending} onChange={v=>{clear();setDrafts(old=>({...old,[p.name]:v}));}}/>}
{description===p.name&&<Description>{plainDescription(p.description)}</Description>}
</li>)}</ResourceList>
{!parameters.length&&<Description>Параметры не найдены.</Description>}
<Button onClick={()=>downloadText(`bms-${props.canId}-${index}.xml`,config.xml,'application/xml')}>Скачать XML BMS</Button>
<input hidden type="file" accept=".xml" ref={file} onChange={e=>void importXml(e)}/><Button disabled={disabled||value.pending} onClick={()=>file.current?.click()}>Импортировать XML BMS</Button>
<Button disabled={disabled||value.pending} onClick={()=>void prepare({defaults:true})}>Сравнить с заводскими значениями</Button>
{changes.length>0&&<Button disabled={disabled||value.pending||changes.some(c=>c.error!==null)} onClick={()=>void prepare({changes:Object.fromEntries(changes.map(c=>[c.name,c.value]))})}>Сравнить изменения BMS ({changes.length})</Button>}
</>}
</SettingsCard>
{preview&&<SettingsCard title="Сравнение параметров BMS" description="Исходная копия сохраняется перед записью. CAN-адрес и скорость CAN могут повлиять на связь после записи.">
<ResourceList aria-label="Изменения BMS">{preview.changes.map(c=><li key={c.name}><ResourceRow title={c.title||c.name} description={`${String(c.before)} → ${String(c.after)}`}/></li>)}</ResourceList>
{!preview.changes.length?<Description>Изменений нет.</Description>:<><Checker label="Подтверждаю изменения; зарядка, нагрузка и входы управления отключены" checked={confirmed} onChange={setConfirmed} disabled={disabled}/><Button variant="primary" disabled={disabled||!confirmed} onClick={()=>void apply()}>Записать настройки BMS</Button></>}
</SettingsCard>}
{result&&<SettingsCard title="Результат настройки BMS"><Description role="status">{result}</Description></SettingsCard>}
</>;
}
@@ -1,14 +1,19 @@
import {Description} from '@nodedc/ui-react';
import {useRef,useState} from 'react';
import {Button,InspectorSelectField,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import type {SensorBoardSettingsProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform,type Sensor} from '../../../../packages/sensor-ui/src/contracts';
import {drivePositions,vescStatus,type DriveProfile} from './model';
import {VescControlTransport} from './VescControlTransport';
import type {ControlTransportProfile} from './controlTransport';
import {VescLimits} from './VescLimits';
export function VescBoardSettings({inventory,transport,enabled,refresh,failure,openDevice}:SensorBoardSettingsProps){
const controllers=inventory?.items.filter(device=>device.kind==='vesc.controller')??[];
const profile=controllers.map(device=>vescStatus(device).drive_profile).filter((value):value is DriveProfile=>!!value).sort((a,b)=>b.revision-a.revision)[0];
const anchor=controllers.find(device=>device.online&&device.verified&&vescStatus(device).board_settings_supported);
const transportAnchor=controllers.find(device=>!!vescStatus(device).control_transport);
const controlStatus=transportAnchor?vescStatus(transportAnchor):null;
const [busy,setBusy]=useState(false);const running=useRef(false);
const active=inventory?.operations?.some(value=>['queued','running'].includes(value.state)&&controllers.some(device=>device.id===value.device_id));
const blocked=!enabled||!anchor||busy||active||!profile;
@@ -26,10 +31,10 @@ export function VescBoardSettings({inventory,transport,enabled,refresh,failure,o
{value:'1x1',label:'1×1 · 2 мотора',disabled:!!profile?.bindings['left.2']||!!profile?.bindings['right.2']},
{value:'2x2',label:'2×2 · 4 мотора'},
]} onChange={layout=>{if(anchor)void change(anchor,'vesc.drive.layout',{layout});}}/>
{!profile&&<p>{inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}</p>}
{profile&&!anchor&&<p>Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.</p>}
{!profile&&<Description>{inventory?'Подключите VESC, чтобы получить профиль привода с борта.':'Получение профиля привода…'}</Description>}
{profile&&!anchor&&<Description>Профиль показан по последним сведениям с борта. Для изменения нужна связь с VESC и актуальное бортовое приложение.</Description>}
{profile?.layout&&<>
<p>Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.</p>
<Description>Стороны — по направлению движения вперёд. Назначения сохраняются автоматически и остаются с контроллером при смене USB-порта.</Description>
{Object.entries(positions).map(([slot,label])=>{
const bound=profile.bindings[slot];
const missing=bound&&!controllers.some(device=>device.id===bound.device_id);
@@ -49,6 +54,13 @@ export function VescBoardSettings({inventory,transport,enabled,refresh,failure,o
})}</ResourceList>
</>}
</SettingsCard>
{profile&&controlStatus?.control_transport&&transportAnchor&&<VescControlTransport drive={profile} profile={controlStatus.control_transport}
adapters={controlStatus.control_adapters??[]} endpoints={controlStatus.control_endpoints??[]}
enabled={enabled&&!busy} active={!!active||controllers.some(d=>!!vescStatus(d).test_active)} failure={failure}
save={async parameters=>{
const result=await perform<{control_transport:ControlTransportProfile}>(transport,transportAnchor,'vesc.transport.configure',parameters);
await refresh();return result.control_transport;
}}/>}
<VescLimits controllers={controllers} transport={transport} enabled={enabled&&!busy&&!active} failure={failure}/>
</div>;
}
@@ -1,4 +1,5 @@
import {useRef,useState} from 'react';
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,ResourceList,ResourceRow,SettingsCard,TextField} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
@@ -9,11 +10,12 @@ interface CalibrationResult {
native:{success?:boolean;code?:number;sensor_mode?:number;parameters?:Record<string,number>};
}
export function VescCalibration({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){
export function VescCalibration({device,transport,enabled,refresh,failure,blocked,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
const [loss,setLoss]=useState('50');
const [confirmed,setConfirmed]=useState(false);
const [busy,setBusy]=useState(false);
const [result,setResult]=useState<CalibrationResult|null>(null);
useEffect(()=>{if(!active)setConfirmed(false);},[active]);
const running=useRef(false);
const limits=vescStatus(device).foc_calibration;
const power=Number(loss);
@@ -37,16 +39,16 @@ export function VescCalibration({device,transport,enabled,refresh,failure,blocke
const parameters=result?.native.parameters;
const calibrated=result?.native.success===true&&result.configuration_verified;
return <SettingsCard title="Калибровка мотора" description={`${device.name} · штатное автоопределение FOC в VESC Tool.`}>
<p>Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.</p>
<Description>Мастер измеряет сопротивление, индуктивность и магнитный поток, определяет датчики и записывает параметры выбранного мотора. Версии до и после сохраняются в истории; настройки аккумулятора и пульта сохраняются.</Description>
<TextField type="number" label="Допустимые потери в моторе, Вт" value={loss} onChange={event=>setLoss(event.target.value)} disabled={busy||blocked||!limits} min={limits?.min_power_loss_w} max={limits?.max_power_loss_w} step="5" aria-invalid={!valid} description="Параметр нагрева для мастера VESC Tool, не номинальная мощность мотора. По нему мастер выбирает токи измерения; предел тока проверки вращения здесь не применяется."/>
<p>Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.</p>
<Description>Мотор будет двигаться и разгоняться. На прошивке 5.02 процедуру нельзя прервать кнопкой или пультом — только отключением силового питания. Оставьте пульт выключенным и приводы вывешенными до завершения; цикл может занять до трёх минут.</Description>
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Наблюдаю мотор, питание могу отключить"/>
<Button disabled={!available||blocked||!confirmed||!valid||busy} loading={busy} onClick={()=>void calibrate()}>Откалибровать мотор</Button>
{busy&&<p role="status">Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.</p>}
{busy&&<Description role="status">Подготовка и калибровка VESC Tool. Дождитесь результата и снятия тока.</Description>}
{result&&<>
<p role="status">{calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}</p>
<Description role="status">{calibrated?'Параметры мотора измерены, записаны и проверены.':result.completed?`Калибровка не принята. Код VESC: ${result.native.code??'не получен'}.`:'Завершение калибровки не подтверждено. Проверьте состояние мотора и питание.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока пока не подтверждено. Перед следующей проверкой верните управление после нейтрали.'} {!result.configuration_verified&&' Проверка конфигурации не завершена; новое движение заблокировано.'}</Description>
{calibrated&&<>
<p>{result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}</p>
<Description>{result.native.sensor_mode===0?'Выбран режим без датчиков. Холлы не определились; качество запуска нужно проверить вращением.':result.native.sensor_mode===2?'Определены датчики Холла.':'Определён энкодер.'}</Description>
{parameters&&<ResourceList aria-label="Результат калибровки">
{([['foc_motor_r','Сопротивление',1000,'мОм'],['foc_motor_l','Индуктивность',1e6,'мкГн'],['foc_motor_flux_linkage','Магнитный поток',1000,'мВб'],['l_current_max','Предел тока мотора',1,'А']] as const).map(([key,title,scale,unit])=><li key={key}><ResourceRow title={title} description={`${(parameters[key]*scale).toLocaleString('ru-RU',{maximumFractionDigits:3})} ${unit}`}/></li>)}
</ResourceList>}
@@ -0,0 +1,35 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useState,useRef} from 'react';
import {Button,Checker,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import type {useVescEditor} from './useVescEditor';
type Editor=ReturnType<typeof useVescEditor>;
function value(v:number|string|boolean,scale:number,suffix:string){
return typeof v==='number'?`${(v*(scale||1)).toLocaleString('ru-RU',{maximumSignificantDigits:9})} ${suffix}`:typeof v==='boolean'?(v?'Включено':'Выключено'):v;
}
export function VescChangeReview({editor,pending,blocked=false}:{editor:Editor;pending?:boolean;blocked?:boolean}){
const [confirmed,setConfirmed]=useState(false);
const review=useRef<HTMLDivElement>(null);
useEffect(()=>setConfirmed(false),[editor.preview?.preview_id]);
useEffect(()=>{if(editor.preview||editor.result)review.current?.scrollIntoView({block:'nearest'});},[editor.preview?.preview_id,editor.result]);
if(!pending&&!editor.preview&&!editor.result)return null;
return <div ref={review} className="sensor-content" role="region" aria-label="Сравнение и результат конфигурации">
{pending&&<SettingsCard title="Проверить незавершённую запись" description="До проверки результата управление заблокировано. Повторное чтение не меняет контроллер.">
<Button disabled={editor.busy||blocked||!editor.available} loading={editor.busy} onClick={()=>void editor.reconcile()}>Проверить результат записи</Button>
</SettingsCard>}
{editor.preview&&<SettingsCard title="Изменения перед записью" description={`VESC ${editor.preview.identity.uuid.toUpperCase()} · сравнение действует пять минут.`}>
<ResourceList aria-label="Изменения конфигурации">{editor.preview.changes.map(c=><li key={`${c.kind}:${c.name}`}><ResourceRow title={c.title||c.name}
description={`${c.kind==='motor'?'Мотор':'Входы'} · ${c.name}: ${value(c.before,c.editor_scale,c.suffix)} → ${value(c.after,c.editor_scale,c.suffix)}`}/></li>)}</ResourceList>
{!editor.preview.changes.length?<Description>Параметры совпадают. Запись не требуется.</Description>:<>
<Description>Изменения записываются в контроллер и влияют на работу привода. Перед записью выключите пульт и физически отключите другие источники команд. Все приводы должны быть вывешены и полностью остановлены. Исходная конфигурация сохраняется автоматически.</Description>
<Checker checked={confirmed} onChange={setConfirmed} label="Входы отключены, приводы вывешены и остановлены" disabled={editor.busy}/>
<Button variant="primary" disabled={!confirmed||editor.busy||blocked||!editor.available} loading={editor.busy} onClick={()=>{setConfirmed(false);void editor.apply();}}>Записать и проверить</Button>
</>}
<Button variant="ghost" disabled={editor.busy} onClick={editor.clear}>Отменить изменения</Button>
</SettingsCard>}
{editor.result&&<SettingsCard title={editor.result.verified?'Результат подтверждён':'Требуется проверка результата'}
description={editor.result.message??(editor.result.outcome==='no_pending_write'?'Незавершённых записей нет.':editor.result.outcome==='unchanged'?'Конфигурация не изменилась.':'Параметры записаны и подтверждены повторным чтением. Прочитайте их заново перед следующим редактированием.')}>
{editor.result.before_backup_id&&<Description>Исходная копия сохранена в истории конфигураций. Управление включается отдельно.</Description>}
</SettingsCard>}
</div>;
}
@@ -0,0 +1,68 @@
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
import {Button,Checker,Description,ResourceList,ResourceRow,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {VescQmlPreview} from './VescQmlPreview';
import {bytesBase64,downloadText,validateProject,type CodeProject} from './editorFiles';
interface Preview {preview_id:string;kind?:string;bytes?:number;sha256?:string;erase?:boolean;command?:string;text?:string}
interface Reading {project:CodeProject;bytes:number;sha256:string;pending:boolean;execution_pending:boolean}
export function VescCodeTools(props:ReadProps&{kind:'lisp'|'qml';active?:boolean}){
const {kind}=props,status=vescStatus(props.device),label=kind==='lisp'?'LispBM':'QML';
const [project,setProject]=useState<CodeProject>({kind,source:'',imports:{},fullscreen:false}),[reading,setReading]=useState<Reading|null>(null);
const [preview,setPreview]=useState<Preview|null>(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState('');
const [repl,setRepl]=useState(''),[output,setOutput]=useState(''),[stats,setStats]=useState<Record<string,unknown>|null>(null);
const running=useRef(false),mounted=useRef(true),file=useRef<HTMLInputElement>(null),attachment=useRef<HTMLInputElement>(null);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0&&status.engine?.contract?.methods.includes('code_read')===true;
const available=props.enabled&&props.device.online&&props.device.verified&&supported;
const disabled=busy||props.blocked,unavailable=disabled||!available;
const call=<T,>(name:string,p:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.code.'+name,p,timeout);
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
async function run(work:()=>Promise<void>){if(running.current||unavailable)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
const read=(hardware=false)=>run(async()=>{clear();const v=await call<Reading>('read',{kind:hardware?'qml_hw':kind});if(mounted.current){setReading(v);setProject(v.project);setMessage(hardware?'Прочитан встроенный QML. Его можно сохранить или использовать как основу приложения.':'Код прочитан. Загрузка и запуск выполняются отдельно.');}});
const prepare=()=>run(async()=>{
clear();const checked=validateProject(project,kind),data=new TextEncoder().encode(JSON.stringify(checked));
const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data))).map(v=>v.toString(16).padStart(2,'0')).join('');
const upload=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,size:data.length,sha256});
for(let at=0;at<data.length;at+=upload.chunk_bytes){const chunk=data.slice(at,at+upload.chunk_bytes),r=await call<{offset:number}>('chunk',{upload_id:upload.upload_id,offset:at,data:bytesBase64(chunk)});if(r.offset!==at+chunk.length)throw new Error('Передача проекта не подтверждена.');}
const p=await call<Preview>('prepare',{upload_id:upload.upload_id});if(mounted.current)setPreview(p);
});
const prepareAction=(name:string,p:Record<string,unknown>)=>run(async()=>{clear();const v=await call<Preview>(name,p);if(mounted.current)setPreview(v);});
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const p=preview;clear();const r=await call<{verified?:boolean;outcome?:string;message?:string;acknowledged?:boolean;command?:string;output?:string}>(p.command?'control_apply':'apply',{preview_id:p.preview_id,confirmed:true,inputs_isolated:true},180000);if(mounted.current){if(r.output)setOutput(r.output);setMessage(r.message??(p.command?(r.acknowledged?'Смена состояния Lisp подтверждена.':'Команда REPL отправлена. Вывод относится только к этому запросу; завершение программы не подтверждается.'):r.verified?'Код записан и проверен. Запуск не выполнялся.':'Итог записи неизвестен.'));if(!p.command)setReading(v=>v?{...v,pending:!r.verified}:null);}await props.refresh();});
const reconcile=()=>run(async()=>{clear();const v=await call<{verified:boolean;outcome:string}>('reconcile',{kind});if(mounted.current){setMessage(v.verified?'Содержимое подтверждено повторным чтением.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление копии.');setReading(r=>r?{...r,pending:!v.verified}:null);}await props.refresh();});
async function open(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;try{if(f.size>256*1024)throw new Error('Файл превышает 256 КБ.');const text=await f.text();const value=f.name.endsWith('.json')?validateProject(JSON.parse(text),kind):validateProject({kind,source:text,imports:{},fullscreen:false},kind);setProject(value);clear();}catch(e){props.failure(e);}}
async function attach(event:ChangeEvent<HTMLInputElement>){const files=Array.from(event.target.files??[]);event.target.value='';try{const imports={...project.imports};for(const f of files){if(f.size>120*1024)throw new Error('Вложение слишком велико.');imports[f.name]=bytesBase64(new Uint8Array(await f.arrayBuffer()));}setProject(validateProject({...project,imports},kind));clear();}catch(e){props.failure(e);}}
const pending=reading?.pending||status.code_pending;
return <div className="sensor-content">
<SettingsCard title={`${label} · редактор`} description={kind==='lisp'?'Исходный код и вложения LispBM. Запись во flash и запуск программы — отдельные действия.':'Исходный код интерфейса Qt Quick. Доступны чтение и запись QML приложения; встроенный QML читается отдельно.'}>
{!supported&&<Description role="status">На этом контроллере прошивка {status.identity?.version??'не определена'}. Чтение и запись программ в памяти контроллера доступны для профиля VESC 6.00. Здесь можно открыть, отредактировать и сохранить проект.</Description>}
<Button disabled={unavailable} loading={busy} onClick={()=>void read()}>Прочитать {label}</Button>
{kind==='qml'&&<Button disabled={unavailable} onClick={()=>void read(true)}>Прочитать встроенный QML</Button>}
<input hidden ref={file} type="file" accept={kind==='lisp'?'.lisp,.lbm,.json':'.qml,.json'} onChange={e=>void open(e)}/><Button disabled={disabled} onClick={()=>file.current?.click()}>Открыть файл или проект</Button>
<TextAreaField label={`Исходный код ${label}`} value={project.source} rows={18} disabled={disabled} onChange={e=>{setProject(p=>({...p,source:e.target.value}));clear();}}/>
{kind==='qml'&&<Checker label="Открывать QML на весь экран в VESC Tool" checked={project.fullscreen} onChange={fullscreen=>{setProject(p=>({...p,fullscreen}));clear();}} disabled={disabled}/>}
{kind==='lisp'&&<><input ref={attachment} type="file" hidden multiple onChange={e=>void attach(e)}/><Button disabled={disabled} onClick={()=>attachment.current?.click()}>Добавить файлы import</Button><Description>В import укажите имя прикреплённого файла без пути к папке или ссылку pkg@ / pkg:: на библиотеку из сохранённого каталога расширений. Исходный код и вложения вместе — до 120 КБ.</Description>
<ResourceList aria-label="Вложения Lisp">{Object.keys(project.imports).map(name=><li key={name}><ResourceRow title={name} actions={<Button disabled={disabled} onClick={()=>{setProject(p=>({...p,imports:Object.fromEntries(Object.entries(p.imports).filter(([key])=>key!==name))}));clear();}}>Убрать</Button>}/></li>)}</ResourceList></>}
<Button disabled={disabled} onClick={()=>downloadText(`vesc-${kind}.${kind==='lisp'?'lisp':'qml'}`,project.source)}>Скачать исходный код</Button>
<Button disabled={disabled} onClick={()=>{try{downloadText(`vesc-${kind}-project.json`,JSON.stringify(validateProject(project,kind),null,2),'application/json');}catch(e){props.failure(e);}}}>Скачать проект с вложениями</Button>
<Button disabled={unavailable||pending||!project.source.trim()} onClick={()=>void prepare()}>Подготовить запись {label}</Button>
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('erase_prepare',{kind})}>Подготовить удаление {label}</Button>
</SettingsCard>
{kind==='qml'&&<VescQmlPreview {...props} source={project.source} active={props.active}/>}
{pending&&<SettingsCard title="Проверка записи кода" description="Предыдущая запись не подтверждена. Автоматического повторения нет."><Button disabled={unavailable} onClick={()=>void reconcile()}>Проверить запись</Button><Button disabled={unavailable} onClick={()=>void prepareAction('restore',{kind})}>Подготовить восстановление копии</Button></SettingsCard>}
{kind==='lisp'&&<SettingsCard title="LispBM · выполнение" description="Программа и REPL могут управлять выходами, включая мотор. Перед запуском отключите внешние входы и подготовьте безопасный стенд.">
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('control_prepare',{command:'start',text:''})}>Подготовить запуск Lisp</Button><Button disabled={unavailable} onClick={()=>void prepareAction('control_prepare',{command:'stop',text:''})}>Подготовить остановку Lisp</Button>
<TextField label="Выражение REPL" value={repl} disabled={disabled} onChange={e=>{setRepl(e.target.value);clear();}}/>
<Button disabled={unavailable||pending||!repl.trim()} onClick={()=>void prepareAction('control_prepare',{command:'repl',text:repl})}>Подготовить команду REPL</Button>
<Button disabled={unavailable} onClick={()=>void run(async()=>{const v=await call<Record<string,unknown>>('stats');if(mounted.current)setStats(v);})}>Прочитать статистику Lisp</Button>
{stats&&<ResourceList aria-label="Статистика Lisp">{[['cpu_use','CPU, %'],['heap_use','Куча, %'],['mem_use','Память, %'],['stack_use','Стек, %'],['done_ctx_r','Результат завершённого контекста']].map(([key,title])=><li key={key}><ResourceRow title={title} description={String(stats[key]??'—')}/></li>)}</ResourceList>}
{output&&<TextAreaField label="Полученный вывод REPL" value={output} rows={8} readOnly/>}
</SettingsCard>}
{preview&&<SettingsCard title="Подтверждение операции" description="Подтверждение действует пять минут и привязано к этому контроллеру и сеансу.">
<Description>{preview.command?(preview.command==='repl'?`REPL: ${preview.text}`:preview.command==='start'?'Запуск сохранённой программы Lisp.':'Остановка Lisp.'):(preview.erase?`Удаление ${label} из контроллера.`:`Запись ${label}: ${preview.bytes} байт. Исходная копия сохраняется автоматически. Lisp не запускается.`)}</Description>
<Checker label="Подтверждаю операцию; внешние входы отключены, стенд подготовлен" checked={confirmed} onChange={setConfirmed} disabled={disabled}/><Button variant="primary" disabled={unavailable||!confirmed} onClick={()=>void apply()}>Выполнить подтверждённую операцию</Button>
</SettingsCard>}
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
</div>;
}
@@ -0,0 +1,83 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useMemo,useState,useRef,type ChangeEvent} from 'react';
import {Button,ResourceList,ResourceRow,Select,SettingsCard,TextField} from '@nodedc/ui-react';
import {VescChangeReview} from './VescChangeReview';
import {useVescEditor} from './useVescEditor';
import {VescParameterEditor,initialDraft,parseDraft,type Drafts} from './VescParameterEditor';
import {vescStatus} from './model';
import {useVescRead,type ReadProps} from './useVescRead';
import {groupLabel,groupedParameters,parameterValue,type ConfigurationRead} from './configuration';
function plainDescription(value:string){
const doc=new DOMParser().parseFromString(value,'text/html');
doc.querySelectorAll('script,style,img,iframe').forEach(node=>node.remove());
doc.querySelectorAll('br,p,li').forEach(node=>node.append(' '));
return doc.body.textContent?.replace(/\s+/g,' ').trim()??'';
}
export function VescConfiguration(props:ReadProps&{active:boolean;kind:'motor'|'application'}){
const {kind}=props,status=vescStatus(props.device);
const editor=useVescEditor(props);
const [drafts,setDrafts]=useState<Drafts>({}),[editing,setEditing]=useState<string|null>(null);
const file=useRef<HTMLInputElement>(null);
const {value,busy,available,read}=useVescRead<ConfigurationRead>(props,'vesc.configuration.read',status.configuration_read_supported===true);
const [group,setGroup]=useState(''),[subgroup,setSubgroup]=useState(''),[query,setQuery]=useState(''),[description,setDescription]=useState<string|null>(null);
useEffect(()=>{setDrafts({});setEditing(null);editor.clear();setGroup('');setSubgroup('');setQuery('');setDescription(null);},[kind]);
const config=value?.configuration[kind];
useEffect(()=>{setDrafts({});setEditing(null);editor.clear();},[value]);
const changed=Object.entries(drafts).flatMap(([name,draft])=>{const p=config?.parameters.find(p=>p.name===name);return p?[{name,...parseDraft(p,draft)}]:[];});
const working=busy||editor.busy;
const baseline=value?{motor:value.configuration.motor.packet_sha256,application:value.configuration.application.packet_sha256}:null;
async function importXml(event:ChangeEvent<HTMLInputElement>){
const selected=event.target.files?.[0];event.target.value='';if(!selected||!baseline)return;
try{if(selected.size>32768)throw new Error('XML превышает 32 КБ.');const xml=await selected.text();await editor.prepare({kind,baseline,xml});}
catch(error){props.failure(error);}
}
const currentGroup=config?.groups.find(item=>item.name===group)??config?.groups[0];
const selectedGroup=group==='all'?'all':currentGroup?.name??'';
const currentSubgroup=currentGroup?.subgroups.find(item=>item.name===subgroup)??currentGroup?.subgroups[0];
const selectedSubgroup=subgroup==='all'?'all':currentSubgroup?.name??'';
const parameters=useMemo(()=>config?groupedParameters(config,selectedGroup,query,selectedSubgroup):[],[config,selectedGroup,query,selectedSubgroup]);
function download(){
if(!config)return;
const url=URL.createObjectURL(new Blob([config.xml],{type:'application/xml'}));
const link=document.createElement('a');link.href=url;link.download=`vesc-${props.device.id}-${kind}.xml`;link.click();
setTimeout(()=>URL.revokeObjectURL(url),1000);
}
return <div className="sensor-content">
<VescChangeReview editor={editor} pending={status.configuration_pending} blocked={props.blocked}/>
<SettingsCard title={kind==='motor'?'Параметры мотора':'Входы и приложения'}
description={value?`Прочитано ${new Date(value.observed_at).toLocaleString('ru-RU')}`:'Полная схема параметров VESC Tool для прошивки подключённого контроллера.'}
actions={<Button disabled={!available||working||props.blocked} loading={busy} onClick={()=>void read()}>Прочитать параметры</Button>}>
{!status.configuration_read_supported&&<Description>Для чтения полной конфигурации требуется обновление бортового приложения.</Description>}
<div className="sensor-content">
{!config&&<Description>Прочитайте конфигурацию, чтобы увидеть группы, значения, единицы и описания параметров.</Description>}
{config&&<>
<Select label="Группа параметров" value={selectedGroup} options={[{value:'all',label:'Все группы'},...config.groups.map(item=>({value:item.name,label:groupLabel(item.name)}))]} onChange={value=>{setGroup(value);setSubgroup('');setQuery('');}}/>
{selectedGroup!=='all'&&currentGroup&&<Select label="Раздел параметров" value={selectedSubgroup} options={[{value:'all',label:'Все разделы группы'},...currentGroup.subgroups.map(item=>({value:item.name,label:groupLabel(item.name)}))]} onChange={value=>{setSubgroup(value);setQuery('');}}/>}
<TextField label="Поиск по всем группам" placeholder="Название или имя параметра VESC" value={query} onChange={event=>setQuery(event.target.value)}/>
<Description>{parameters.length} параметров. Значения относятся к указанному времени чтения.</Description>
<ResourceList aria-label="Параметры VESC Tool">{parameters.map(parameter=><li key={parameter.name}>
<ResourceRow title={<span className="vesc-parameter-title">{parameter.title||parameter.name}</span>}
description={`${parameter.name} · ${parameterValue(parameter)}${parameter.transmittable?'':' · справочное значение схемы'}`}
actions={<>{editor.available&&parameter.transmittable&&parameter.type!=='undefined'&&<Button disabled={working||props.blocked} onClick={()=>{editor.clear();setEditing(editing===parameter.name?null:parameter.name);}}>Изменить</Button>}{parameter.description?<Button variant="ghost" onClick={()=>setDescription(description===parameter.name?null:parameter.name)}>{description===parameter.name?'Скрыть описание':'Описание'}</Button>:null}</>}/>
{editing===parameter.name&&<VescParameterEditor parameter={parameter} value={drafts[parameter.name]??initialDraft(parameter)} disabled={working||props.blocked} onChange={draft=>{editor.clear();setDrafts(old=>({...old,[parameter.name]:draft}));}}/>}
{description===parameter.name&&<Description>{plainDescription(parameter.description)}</Description>}
</li>)}</ResourceList>
{!parameters.length&&<Description>Параметры не найдены.</Description>}
<div className="sensor-actions"><Button onClick={download}>Скачать XML VESC Tool</Button>
{editor.available&&<>
<input ref={file} type="file" accept=".xml,application/xml,text/xml" hidden onChange={event=>void importXml(event)}/>
<Button disabled={working||props.blocked} onClick={()=>file.current?.click()}>Импортировать XML</Button>
</>}
</div>
{editor.available&&changed.length>0&&<><Description>Изменено параметров: {changed.length}. Сначала проверьте сравнение с контроллером.</Description>
<div className="sensor-actions"><Button disabled={working||props.blocked||changed.some(c=>c.error!==null)} loading={editor.busy} onClick={()=>void editor.prepare({kind,baseline,changes:Object.fromEntries(changed.map(c=>[c.name,c.value]))})}>Сравнить изменения</Button>
<Button disabled={working} variant="ghost" onClick={()=>{setDrafts({});editor.clear();}}>Сбросить черновик</Button></div>
</>}
</>}
</div>
</SettingsCard>
</div>;
}
@@ -0,0 +1,73 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,InspectorSelectField,SettingsCard} from '@nodedc/ui-react';
import {drivePositions,type DriveProfile} from './model';
import {routeError,transportMode,type ControlAdapter,type ControlEndpoint,type ControlRoute,type ControlTransportProfile} from './controlTransport';
interface Props {
drive:DriveProfile;profile:ControlTransportProfile;adapters:ControlAdapter[];endpoints:ControlEndpoint[];
enabled:boolean;active:boolean;
save:(parameters:{revision:number;drive_revision:number;routes:Record<string,ControlRoute>})=>Promise<ControlTransportProfile>;
failure:(error:unknown)=>void;
}
const routeKey=(r:ControlRoute)=>r.kind==='usb'?'usb':JSON.stringify([r.adapter_id,r.channel,r.can_id,r.bitrate]);
export function VescControlTransport({drive,profile,adapters,endpoints,enabled,active,save,failure}:Props){
const [draft,setDraft]=useState(()=>structuredClone(profile.routes));
const [base,setBase]=useState({revision:profile.revision,drive:drive.revision});
const [dirty,setDirty]=useState(false),[busy,setBusy]=useState(false);
const pending=useRef(false);
const stale=base.revision!==profile.revision||base.drive!==drive.revision;
const blocked=!enabled||active||busy||stale;
const labels=drivePositions(drive.layout),bindings=Object.entries(drive.bindings);
const available=(id:string)=>endpoints.filter(e=>e.device_id===id&&e.verified);
const ready=(id:string,r:ControlRoute|undefined)=>!!r&&available(id).some(e=>routeKey(e.route)===routeKey(r));
const allReady=bindings.length>0&&bindings.every(([,b])=>ready(b.device_id,draft[b.device_id]));
const mode=Object.keys(draft).length?transportMode(draft):'none';
const error=routeError(draft,drive);
const profileKey=JSON.stringify(profile);
useEffect(()=>{
if(!dirty&&!pending.current&&profile.revision>=base.revision){setDraft(structuredClone(profile.routes));setBase({revision:profile.revision,drive:drive.revision});}
},[profileKey,drive.revision,dirty]); // Availability can change without a saved-profile revision.
function reload(){setDraft(structuredClone(profile.routes));setBase({revision:profile.revision,drive:drive.revision});setDirty(false);}
async function apply(){
if(blocked||error||!allReady||pending.current)return;
pending.current=true;setBusy(true);failure(null);
try{const ack=await save({revision:base.revision,drive_revision:base.drive,routes:draft});setDraft(structuredClone(ack.routes));setBase({revision:ack.revision,drive:base.drive});setDirty(false);}
catch(e){failure(e);}finally{pending.current=false;setBusy(false);}
}
function title(r:ControlRoute){
if(r.kind==='usb')return 'USB';
const adapter=adapters.find(a=>a.id===r.adapter_id);
return 'CAN'+(r.channel+1)+' · ID '+r.can_id+' · '+r.bitrate/1000+' кбит/с'+(adapters.length>1?' · '+(adapter?.label??'адаптер'):'');
}
return <SettingsCard title="Шина управления" description="Подключение моторов при управлении из центра наблюдения.">
<div className="sensor-content">
<InspectorSelectField label="Для всех моторов" value={mode} disabled={blocked} options={[
{value:'none',label:'Недоступно',disabled:true},
{value:'usb',label:'USB',disabled:!bindings.length||!bindings.every(([,b])=>available(b.device_id).some(e=>e.route.kind==='usb'))},
{value:'can',label:'CAN',disabled:!bindings.length||!bindings.every(([,b])=>available(b.device_id).some(e=>e.route.kind==='can'))},
{value:'mixed',label:'По моторам',disabled:true},
]} onChange={value=>{
if(value!=='usb'&&value!=='can')return;
setDraft(Object.fromEntries(bindings.map(([,b])=>[b.device_id,available(b.device_id).find(e=>e.route.kind===value)!.route])));setDirty(true);
}}/>
{bindings.map(([slot,b])=>{
const route=draft[b.device_id],choices=available(b.device_id);
const current=route?routeKey(route):'';
return <SettingsCard key={b.device_id} title={labels[slot]??slot} description={'VESC '+b.uuid.slice(0,6).toUpperCase()}>
<InspectorSelectField label="Соединение" value={current} disabled={blocked} options={[
{value:'',label:'Недоступно',disabled:true},
...choices.map(e=>({value:routeKey(e.route),label:title(e.route)})),
...(route&&!ready(b.device_id,route)?[{value:current,label:title(route)+' · недоступно',disabled:true}]:[]),
]} onChange={value=>{
const selected=choices.find(e=>routeKey(e.route)===value);if(!selected)return;
setDraft(v=>({...v,[b.device_id]:selected.route}));setDirty(true);
}}/>
</SettingsCard>;
})}
<Description>Доступность CAN подтверждается ответом назначенного VESC. При обрыве выбранной связи текущий сеанс управления завершается. Смена шины применяется после сохранения.</Description>
{active&&<Description>Завершите управление перед сменой шины.</Description>}
{!allReady&&<Description>Один или несколько моторов недоступны по выбранному соединению.</Description>}
{stale?<Button disabled={busy} onClick={reload}>Обновить профиль</Button>:<Button disabled={blocked||!!error||!allReady} loading={busy} onClick={()=>void apply()}>Сохранить выбор шины</Button>}
</div>
</SettingsCard>;
}
+102 -25
View File
@@ -1,13 +1,26 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {Button,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge,FeatureSettingsWindow} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {vescLabel,vescStatus,type VescTelemetry} from './model';
import {SensorGeneralSettings} from '../../../../packages/sensor-ui/src/SensorGeneralSettings';
import {VescBackups} from './VescBackups';
import {VescMotor} from './VescMotor';
import {VescHall} from './VescHall';
import {VescCalibration} from './VescCalibration';
import {VescConfiguration} from './VescConfiguration';
import {VescDiagnostics,VescConnections} from './VescDiagnostics';
import './vesc.css';
import {VescTools,VescTerminal} from './VescTools';
import {VescFirmware} from './VescFirmware';
import {VescLink} from './VescLink';
import {VescPackages} from './VescPackages';
import {VescSampleData} from './VescSampleData';
import {VescCodeTools} from './VescCodeTools';
import {VescBms} from './VescBms';
import {VescTrends} from './VescTrends';
import {VescLogAnalysis} from './VescLogAnalysis';
const fields=[['input_voltage_v','Напряжение питания','В'],['input_current_a','Ток питания','А'],
['motor_current_a','Ток мотора','А'],['erpm','Электрические обороты','ERPM'],['duty','Заполнение PWM',''],
@@ -21,11 +34,15 @@ export function VescDetail(props:SensorDetailProps){
const [telemetry,setTelemetry]=useState<VescTelemetry|null>(status.telemetry);
const [pending,setPending]=useState<string|null>(null);
const [saved,setSaved]=useState<string|null>(null);
const [section,setSection]=useState('general');
const [motorBusy,setMotorBusy]=useState(false);
const [hallBusy,setHallBusy]=useState(false);
const [calibrationBusy,setCalibrationBusy]=useState(false);
const [configBusy,setConfigBusy]=useState(false);
const [diagnosticBusy,setDiagnosticBusy]=useState(false);
const [linkBusy,setLinkBusy]=useState(false);
const poweredBusy=motorBusy||hallBusy||calibrationBusy||linkBusy;
const [generalBusy,setGeneralBusy]=useState(false);
const poweredBusy=generalBusy||motorBusy||hallBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy;
const running=useRef(false);const mounted=useRef(true);
const available=enabled&&device.online&&device.verified&&status.readable;
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
@@ -44,37 +61,97 @@ export function VescDetail(props:SensorDetailProps){
finally{running.current=false;if(mounted.current)setPending(null);}
}
const backupAt=saved??status.backup?.observed_at;
return <div className="sensor-content">
<div><Button onClick={back}>К устройствам</Button></div>
<SettingsCard title={`${device.name} · Настройка VESC`} description={`${device.model} · ${device.connection_label??'USB'}`}
actions={<StatusBadge tone={label.tone}>{label.label}</StatusBadge>}>
{!enabled||!device.online?<p>Нет свежей связи с контроллером.</p>:status.message?<p>{status.message}</p>:null}
{status.identity?<ResourceList aria-label="Контроллер VESC">
<li><ResourceRow title="Прошивка" description={status.identity.version}/></li>
<li><ResourceRow title="Аппаратная версия" description={status.identity.hardware}/></li>
<li><ResourceRow title="UUID" description={status.identity.uuid.toUpperCase()}/></li>
{status.identity.test_firmware!==null&&status.identity.test_firmware>0&&<li><ResourceRow title="Тестовая прошивка" description={String(status.identity.test_firmware)}/></li>}
</ResourceList>:<p>Аппаратный идентификатор ещё не подтверждён.</p>}
</SettingsCard>
const busy=poweredBusy||pending!==null;
const sections=[
{id:'general',label:'Общие данные',group:'Устройство'},
{id:'overview',label:'Контроллер и прошивка',group:'Устройство'},
{id:'diagnostics',label:'Текущие показания',group:'Устройство'},
{id:'trends',label:'Графики и CSV',group:'Устройство'},
{id:'hardware',label:'USB и журнал ошибок',group:'Устройство'},
{id:'connections',label:'CAN и приёмник',group:'Устройство'},
{id:'samples',label:'Sample Data',group:'Диагностика'},
{id:'motor-parameters',label:'Мотор',group:'Параметры VESC Tool'},
{id:'application-parameters',label:'Входы и приложения',group:'Параметры VESC Tool'},
{id:'calibration',label:'Калибровка FOC',group:'Настройка мотора'},
{id:'hall',label:'Датчики Холла',group:'Настройка мотора'},
{id:'rotation',label:'Проверка вращения',group:'Настройка мотора'},
{id:'configuration',label:'Резервные копии',group:'Конфигурации'},
{id:'firmware',label:'Прошивка и загрузчик',group:'Конфигурации'},
{id:'bms',label:'Аккумулятор BMS',group:'Инструменты'},
{id:'peripherals',label:'Входы и IMU',group:'Инструменты'},
{id:'log-analysis',label:'Анализ журналов и FFT',group:'Инструменты'},
{id:'terminal',label:'Терминал диагностики',group:'Инструменты'},
{id:'packages',label:'Расширения',group:'Программирование'},
{id:'lisp',label:'LispBM',group:'Программирование'},
{id:'qml',label:'QML-интерфейс',group:'Программирование'},
].map(item=>({...item,disabled:busy&&item.id!==section}));
return <FeatureSettingsWindow open title="Настройка VESC" subtitle={device.connection_label??device.name}
identity={{title:device.name,subtitle:device.model,avatarLabel:'VESC'}}
sections={sections} activeSection={section} onSectionChange={value=>{if(!busy)setSection(value);}}
onClose={()=>{if(!busy)back();}} headerActions={<StatusBadge tone={label.tone}>{label.label}</StatusBadge>}>
<div className="sensor-content">
{!enabled||!device.online?<Description role="status">Нет свежей связи с контроллером. Показаны последние полученные сведения.</Description>:status.message?<Description role="status">{status.message}</Description>:null}
{section==='general'&&<SensorGeneralSettings {...props} blocked={motorBusy||hallBusy||calibrationBusy||configBusy||diagnosticBusy||linkBusy||pending!==null} onBusyChange={setGeneralBusy}/>}
<div hidden={section!=='overview'}><div className="sensor-content">
<SettingsCard title="О контроллере" description="Идентификация VESC и его прошивки. Эти сведения читаются по USB; разбирать корпус не требуется.">
{status.identity?<ResourceList aria-label="Контроллер VESC">
<li><ResourceRow title="Прошивка" description={status.identity.version}/></li>
<li><ResourceRow title="Аппаратная конфигурация" description={status.identity.hardware}/></li>
<li><ResourceRow title="UUID микроконтроллера" description={status.identity.uuid.toUpperCase()}/></li>
{status.identity.test_firmware!==null&&status.identity.test_firmware>0&&<li><ResourceRow title="Тестовая прошивка" description={String(status.identity.test_firmware)}/></li>}
</ResourceList>:<Description>Аппаратный идентификатор ещё не подтверждён.</Description>}
<Description>Аппаратная конфигурация — название платформы в прошивке. Она не подтверждает производителя и точную модель платы. UUID позволяет узнавать этот контроллер после смены USB-порта; это идентификатор процессора, а не заводской серийный номер платы.</Description>
</SettingsCard>
{status.engine&&<SettingsCard title="Ядро VESC Tool">
<ResourceList aria-label="Версия VESC Tool"><li><ResourceRow title="Версия" description={status.engine.version}/></li>
<li><ResourceRow title="Ревизия исходного кода" description={status.engine.commit.slice(0,12)}/></li>
{status.engine.contract&&<li><ResourceRow title="Проверенные версии прошивок" description={status.engine.contract.firmware_profiles.map(item=>`${item.major}.${String(item.minor).padStart(2,'0')}`).join(', ')}/></li>}
</ResourceList>
<Description>Ядро обновляется вместе с бортовым приложением. Его обновление не перепрошивает контроллеры.</Description>
</SettingsCard>}
<SettingsCard title="Работа с VESC">
<Description>В разделе «Устройство» находятся показания, ошибки и связь. «Параметры VESC Tool» содержит настройки мотора и входов из схемы установленной прошивки. Калибровка и проверка вращения выделены отдельно: они подают ток на мотор. Резервные копии сохраняют конфигурацию перед изменениями.</Description>
</SettingsCard>
</div></div>
<div hidden={section!=='diagnostics'}><div className="sensor-content">
<SettingsCard title="Показания контроллера" description={telemetry?`Снимок: ${new Date(telemetry.observed_at).toLocaleString()}`:'Получите текущие значения и код ошибки.'}
actions={<Button disabled={!available||pending!==null||poweredBusy} loading={pending==='vesc.telemetry.read'} onClick={()=>void read('vesc.telemetry.read')}>Обновить показания</Button>}>
<LoadingRegion loading={pending==='vesc.telemetry.read'&&!telemetry} label="Чтение показаний VESC">
{telemetry?<ResourceList aria-label="Показания VESC">{fields.map(([key,title,unit])=>{
const value=telemetry.values[key];if(value===undefined)return null;
return <li key={key}><ResourceRow title={title} description={typeof value==='boolean'?(value?'Активен':'Не активен'):`${Number(value).toLocaleString(undefined,{maximumFractionDigits:3})}${unit?' '+unit:''}`}/></li>;
})}</ResourceList>:<p>Показания ещё не прочитаны.</p>}
})}</ResourceList>:<Description>Показания ещё не прочитаны.</Description>}
</LoadingRegion>
<p>ERPM — электрические обороты. Обороты вала зависят от числа пар полюсов мотора.</p>
<Description>ERPM — электрические обороты. Обороты вала зависят от числа пар полюсов мотора.</Description>
</SettingsCard>
<SettingsCard title="Резервная копия конфигурации" description="Сохраните текущие параметры мотора и входов новой версией."
<VescLink {...props} blocked={motorBusy||hallBusy||calibrationBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setLinkBusy}/>
</div></div>
<div hidden={section!=='configuration'}><div className="sensor-content">
<SettingsCard title="Сохранить конфигурацию" description="Сохраните текущие параметры мотора и входов новой версией."
actions={<Button disabled={!available||pending!==null||poweredBusy} loading={pending==='vesc.config.backup'} onClick={()=>void read('vesc.config.backup')}>Сохранить версию</Button>}>
{backupAt&&<p>Последняя копия: {new Date(backupAt).toLocaleString()}</p>}
<p>Копия привязана к UUID и прошивке. Версии до и после калибровки остаются в истории.</p>
{backupAt&&<Description>Последняя копия: {new Date(backupAt).toLocaleString()}</Description>}
<Description>Копия привязана к UUID и прошивке. Версии до и после калибровки остаются в истории.</Description>
</SettingsCard>
<VescLink {...props} blocked={motorBusy||hallBusy||calibrationBusy||pending!==null} onBusyChange={setLinkBusy}/>
<VescCalibration {...props} blocked={linkBusy||motorBusy||hallBusy||pending!==null} onBusyChange={setCalibrationBusy}/>
<VescHall {...props} blocked={linkBusy||motorBusy||calibrationBusy||pending!==null} onBusyChange={setHallBusy}/>
<VescMotor {...props} blocked={linkBusy||hallBusy||calibrationBusy||pending!==null} onBusyChange={setMotorBusy}/>
<VescBackups deviceId={device.id} archive={transport.configurationArchive} revision={backupAt??null}/>
</div>;
{section==='configuration'&&<VescBackups editorProps={{...props,blocked:motorBusy||hallBusy||calibrationBusy||linkBusy||diagnosticBusy||pending!==null,onBusyChange:setConfigBusy}} deviceId={device.id} archive={transport.configurationArchive} revision={backupAt??null}/>}
</div></div>
{section==='samples'&&<VescSampleData {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
<div hidden={section!=='trends'}><VescTrends {...props} active={section==='trends'}/></div>
{section==='log-analysis'&&<VescLogAnalysis/>}
{section==='packages'&&<VescPackages {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
<div hidden={section!=='lisp'}><VescCodeTools {...props} kind="lisp" blocked={busy} onBusyChange={setConfigBusy}/></div>
<div hidden={section!=='qml'}><VescCodeTools {...props} kind="qml" active={section==='qml'} blocked={busy} onBusyChange={setConfigBusy}/></div>
{section==='bms'&&<VescBms {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
{section==='peripherals'&&<VescTools {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
{section==='terminal'&&<VescTerminal {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
{section==='firmware'&&<VescFirmware {...props} blocked={busy} onBusyChange={setConfigBusy}/>}
{section==='hardware'&&<VescDiagnostics {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/>}
<div hidden={section!=='connections'}><VescConnections {...props} blocked={busy} onBusyChange={setDiagnosticBusy}/></div>
<div hidden={!section.endsWith('-parameters')}><VescConfiguration {...props}
active={section.endsWith('-parameters')} kind={section==='application-parameters'?'application':'motor'}
blocked={motorBusy||hallBusy||calibrationBusy||linkBusy||diagnosticBusy||pending!==null} onBusyChange={setConfigBusy}/></div>
<div hidden={section!=='calibration'}><VescCalibration {...props} active={section==='calibration'} blocked={motorBusy||hallBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setCalibrationBusy}/></div>
<div hidden={section!=='hall'}><VescHall {...props} active={section==='hall'} blocked={motorBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setHallBusy}/></div>
<div hidden={section!=='rotation'}><VescMotor {...props} active={section==='rotation'} blocked={hallBusy||calibrationBusy||linkBusy||configBusy||diagnosticBusy||pending!==null} onBusyChange={setMotorBusy}/></div>
</div>
</FeatureSettingsWindow>;
}
@@ -0,0 +1,76 @@
import {useEffect,useRef,useState} from 'react';
import {Button,ComparisonTable,Description,SettingsCard} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {vescStatus} from './model';
import {type ReadProps} from './useVescRead';
import {compareDiagnostics,diagnosticExpired,diagnosticSnapshot,type DiagnosticRead,type DiagnosticSnapshot} from './diagnosticReview';
const number=(v:number|null)=>v===null?'Не сообщается':v.toLocaleString('ru-RU');
const timestamp=(v:DiagnosticSnapshot)=>new Date(v.read.observed_at).toLocaleString('ru-RU');
const faultFields:Record<string,string>={Motor:'Мотор',Current:'Ток, А','Current filtered':'Ток после фильтра, А',Voltage:'Напряжение, В','Gate drv voltage':'Питание драйвера, В',Duty:'Duty',RPM:'Обороты, ERPM',Tacho:'Тахометр','Cycles running':'Рабочие циклы','Comm step':'Шаг коммутации',Temperature:'Температура, °C'};
const usbFields=[['port','USB-порт'],['tty','Последовательный порт'],['speed','Скорость USB'],['idVendor','USB VID'],['idProduct','USB PID'],['manufacturer','Производитель USB-интерфейса'],['product','USB-устройство'],['serial','Серийная строка USB']] as const;
export function VescDiagnosticReview(props:ReadProps){
const {device,transport,enabled,failure,blocked,onBusyChange}=props;
const status=vescStatus(device),supported=status.diagnostics_read_supported===true;
const available=enabled&&device.online&&device.verified&&status.readable&&supported;
const [current,setCurrent]=useState<DiagnosticSnapshot|null>(null),[baseline,setBaseline]=useState<DiagnosticSnapshot|null>(null);
const [busy,setBusy]=useState(false),[raw,setRaw]=useState(false),[expired,setExpired]=useState(false);
const mounted=useRef(true),running=useRef(false);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
useEffect(()=>{if(!current&&!baseline)return;const timer=setInterval(()=>{
if(current&&diagnosticExpired(current)){setCurrent(null);setExpired(true);}
if(baseline&&diagnosticExpired(baseline)){setBaseline(null);setExpired(true);}
},1000);return()=>clearInterval(timer);},[current,baseline]);
async function read(){
if(running.current||blocked||!available)return;
running.current=true;setBusy(true);onBusyChange(true);failure(null);
try{
const result=await perform<DiagnosticRead>(transport,device,'vesc.diagnostics.read',{},30000);
if(result.device_id!==device.id||result.identity?.uuid.toLowerCase()!==status.identity?.uuid.toLowerCase())throw new Error('Ответ относится к другому контроллеру. Обновите подключение.');
const next=diagnosticSnapshot(result,device.snapshot.context.session_id);
if(mounted.current){setCurrent(next);setExpired(false);}
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
}
const comparison=baseline&&current?compareDiagnostics(baseline,current):null;
const snapshots=baseline&&current&&baseline!==current?[baseline,current]:current?[current]:[];
const columns=snapshots.map((s,i)=>({id:String(i),label:s===baseline?'Опорный снимок':'Последний снимок'}));
return <div className="sensor-content">
<SettingsCard title="Аппаратная диагностика" description="Состояние USB и ошибки, сохранённые прошивкой с момента её запуска. Чтение выполняется только по кнопке."
actions={<Button disabled={!available||busy||blocked} loading={busy} onClick={()=>void read()}>Прочитать диагностику</Button>}>
{!supported&&<Description>Для чтения аппаратной диагностики требуется обновление бортового приложения.</Description>}
{!current&&<Description>{expired?'Снимки удалены из памяти по истечении срока.':'Диагностика ещё не прочитана.'} Команды hw_status и faults не запускают мотор.</Description>}
{current&&<>
<Description>Прочитано {timestamp(current)}. Ответ терминала завершается после паузы вывода: прошивка не передаёт признак полноты. Отсутствующие поля не считаются нулевыми.</Description>
{!current.identityMatches&&<Description role="alert">UUID в тексте hw_status не совпал с идентификацией контроллера или отсутствует. Сравнение отключено.</Description>}
<div className="sensor-actions"><Button disabled={busy||blocked||!current.identityMatches} onClick={()=>{if(!diagnosticExpired(current)){setBaseline(current);setExpired(false);}}}>Использовать как опорный</Button><Button disabled={busy||blocked} onClick={()=>{setCurrent(null);setBaseline(null);setRaw(false);setExpired(false);}}>Очистить снимки</Button><Button onClick={()=>setRaw(v=>!v)}>{raw?'Скрыть исходный ответ':'Показать исходный ответ'}</Button></div>
<Description>В памяти окна остаются максимум два снимка на пять минут. Смена контроллера, USB-сеанса или закрытие раздела очищает их. Непрерывная запись не включается.</Description>
</>}
</SettingsCard>
{current&&<>
<SettingsCard title="Состояние USB" description="Счётчики принадлежат текущему запуску микроконтроллера. USB configuration event сам по себе не означает неисправность кабеля.">
<ComparisonTable density="compact" label="Счётчики диагностики" heading="Параметр" columns={columns} rows={[
{id:'time',label:'Время чтения',cells:snapshots.map(timestamp)},
{id:'config',label:'События USB',cells:snapshots.map(s=>number(s.configEvents))},
{id:'timeouts',label:'Таймауты USB',cells:snapshots.map(s=>number(s.writeTimeouts))},
{id:'offsets',label:'Смещения FOC',cells:snapshots.map(s=>s.offsets?.join(' · ')??'Не сообщается')},
]}/>
{!baseline?<Description>Для сравнения отметьте этот снимок как опорный, затем прочитайте диагностику ещё раз.</Description>:comparison?.reason?<Description role="status">{comparison.reason}</Description>:comparison&&<Description role="status">Изменение от опорного снимка: конфигурирования USB — {number(comparison.configEvents)}; таймауты записи — {number(comparison.writeTimeouts)}.</Description>}
<Description>Рост счётчика подтверждает событие прошивки, но не определяет его физическую причину. Нулевая разность не исключает пропадание связи, перезапуск или подзаедание без ошибки.</Description>
</SettingsCard>
<SettingsCard title="Ошибки контроллера" description="Это сообщения faults с момента запуска прошивки; они могут относиться к уже завершившемуся событию.">
<Description>{current.faults.state==='none'?'Прошивка сообщает: зарегистрированных ошибок с момента запуска нет.':current.faults.state==='unknown'?'Формат ответа не распознан. Откройте исходный ответ.':`В полученном ответе записей: ${current.faults.entries.length}.`}</Description>
{current.faults.entries.map((entry,i)=><SettingsCard key={i} title={`${i+1} · ${entry.code}`}><ComparisonTable density="compact" label={`Запись ошибки ${i+1}`} heading="Параметр" columns={[{id:'value',label:'При ошибке'}]} rows={Object.entries(entry.fields).map(([key,value])=>({id:key,label:faultFields[key]??key,cells:[value]}))}/></SettingsCard>)}
<Description>Отсутствие faults не подтверждает исправность двигателя, датчиков или проводки. Смещения токовых каналов без сопоставимого измерения не дают такого заключения.</Description>
</SettingsCard>
<SettingsCard title="USB-подключение" description="Привязка к стороне ровера сохраняется по UUID микроконтроллера. Серийная строка USB может совпадать у разных VESC.">
<ComparisonTable density="compact" label="Подключение VESC" heading="Параметр" columns={[{id:'value',label:'Последний снимок'}]} rows={[
{id:'uuid',label:'UUID микроконтроллера',cells:[current.read.identity.uuid]},
...usbFields.map(([key,label])=>({id:key,label,cells:[current.read.usb[key]??'Не сообщается']})),
]}/>
</SettingsCard>
{raw&&Object.entries(current.read.reports).map(([name,report])=><SettingsCard key={name} title={name==='hw_status'?'Исходный hw_status':'Исходный faults'}><pre className="vesc-diagnostic-output">{report.text}</pre></SettingsCard>)}
</>}
</div>;
}
@@ -0,0 +1,24 @@
import {Description} from '@nodedc/ui-react';
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import {useVescRead,type ReadProps} from './useVescRead';
import {VescDiagnosticReview} from './VescDiagnosticReview';
export function VescDiagnostics(props:ReadProps){
const {device}=props;
const binding=`${device.id}:${device.snapshot.context.session_id}:${device.online&&device.verified}`;
return <VescDiagnosticReview key={binding} {...props}/>;
}
export function VescConnections(props:ReadProps){
const input=useVescRead<{observed_at:string;input:{level:number;pulse_ms:number}}>(props,'vesc.input.read');
const can=useVescRead<{observed_at:string;can_ids:number[];elapsed_s:number}>(props,'vesc.can.read');
return <div className="sensor-content">
<SettingsCard title="Вход приёмника PPM" description="Декодированный сигнал входа контроллера. Значение около нуля означает нейтраль; это снимок, а не проверка электрического подключения."
actions={<Button disabled={!input.available||props.blocked||input.busy||can.busy} loading={input.busy} onClick={()=>void input.read()}>Прочитать PPM</Button>}>
{input.value?<ResourceList aria-label="Приёмник VESC"><li><ResourceRow title="Уровень сигнала" description={input.value.input.level.toLocaleString('ru-RU')}/></li><li><ResourceRow title="Длительность импульса" description={`${input.value.input.pulse_ms.toLocaleString('ru-RU')} мс`}/></li><li><ResourceRow title="Время чтения" description={new Date(input.value.observed_at).toLocaleString('ru-RU')}/></li></ResourceList>:<Description>Сигнал ещё не прочитан.</Description>}
</SettingsCard>
<SettingsCard title="Устройства на CAN" description="Поиск контроллеров, которые отвечают на CAN-запрос выбранного VESC. Отсутствие ответа само по себе не определяет причину неисправности шины."
actions={<Button disabled={!can.available||props.blocked||input.busy||can.busy} loading={can.busy} onClick={()=>void can.read()}>Проверить CAN</Button>}>
{can.value?<><Description role="status">{can.value.can_ids.length?`Ответили CAN ID: ${can.value.can_ids.join(', ')}`:'Другие контроллеры не ответили.'}</Description><Description>Проверено {new Date(can.value.observed_at).toLocaleString('ru-RU')}.</Description></>:<Description>Поиск ещё не выполнен.</Description>}
</SettingsCard>
</div>;
}
+174
View File
@@ -0,0 +1,174 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,ProgressBar,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus,type VescFirmwareState} from './model';
import {FirmwareDestination} from './FirmwareDestination';
import type {CanFirmwareTarget,SwdTarget} from './firmwareFiles';
import {firmwareFileError,firmwareVariant,type FirmwarePreview,type FirmwareCatalog} from './firmwareFiles';
const labels:Record<string,string>={idle:'Загрузка не выполняется',not_started:'Запись не начиналась; исходные настройки подтверждены',uploading:'Запись контроллера',awaiting_identity:'Ожидается повторное определение контроллера',identified:'Контроллер определён после загрузки',unknown:'Итог записи не подтверждён'};
const encode=(bytes:Uint8Array)=>btoa(Array.from(bytes,value=>String.fromCharCode(value)).join(''));
export function VescFirmware(props:ReadProps){
const {device,transport,enabled,failure}=props, status=vescStatus(device);
const [mode,setMode]=useState('usb'),[canId,setCanId]=useState(''),[target,setTarget]=useState<CanFirmwareTarget|null>(null),[canOptions,setCanOptions]=useState<{value:string;label:string}[]>([]);
const [swd,setSwd]=useState<SwdTarget>({target_code:1,pins:'default',address:0x08000000,flash_bytes:128*1024});
const [source,setSource]=useState('file'),[catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[imageId,setImageId]=useState('');
const [withoutLimits,setWithoutLimits]=useState(false);
const [kind,setKind]=useState('firmware'),[version,setVersion]=useState(status.identity?.version??'');
const [preview,setPreview]=useState<FirmwarePreview|null>(null),[result,setResult]=useState<VescFirmwareState|null>(null);
const [busy,setBusy]=useState(false),[uploading,setUploading]=useState(false),[progress,setProgress]=useState<number|null>(null);
const [compatible,setCompatible]=useState(false),[isolated,setIsolated]=useState(false),[cancelling,setCancelling]=useState(false);
const input=useRef<HTMLInputElement>(null),running=useRef(false),mounted=useRef(true);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const remote=status.firmware_update??{state:'idle'};
const state=uploading||remote.state==='uploading'?remote:result??remote;
const active=uploading||remote.state==='uploading';
const available=enabled&&device.online&&device.verified&&status.readable&&status.firmware_update_supported===true;
const formats=status.engine?.contract?.firmware_formats??['bin'];
const versions=status.engine?.contract?.firmware_profiles.map(p=>`${p.major}.${String(p.minor).padStart(2,'0')}`)??[];
const disabled=!available||props.blocked||busy||active;
const destinationReady=mode!=='can'||!!target;
const hardware=mode==='can'?target?.hardware:status.identity?.hardware;
const targetVersion=mode==='can'&&target?`${target.major}.${String(target.minor).padStart(2,'0')}`:status.identity?.version;
const resetDestination=()=>{setPreview(null);setCompatible(false);setIsolated(false);setCatalog(null);setImageId('');};
async function canRead(scan:boolean){if(disabled||running.current)return;running.current=true;setBusy(true);props.onBusyChange(true);failure(null);resetDestination();setTarget(null);
try{if(scan){const v=await perform<{can_ids:number[]}>(transport,device,'vesc.can.read',{},30000);const options=v.can_ids.filter(id=>Number.isInteger(id)&&id>=0&&id<=253).map(id=>({value:String(id),label:`CAN ${id}`}));if(mounted.current){setCanOptions(options);setCanId(options[0]?.value??'');if(!options.length)failure(new Error('Устройства CAN не ответили.'));}}
else{const v=await call<{target:CanFirmwareTarget}>('target',{can_id:Number(canId)});if(mounted.current)setTarget(v.target);}}
catch(e){if(mounted.current)failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
const call=<T,>(name:string,p:Record<string,unknown>={},timeout=30000)=>perform<T>(transport,device,`vesc.firmware.${name}`,p,timeout);
async function stage(file:File){
if(running.current||disabled||!destinationReady)return;
running.current=true;setBusy(true);props.onBusyChange(true);setPreview(null);setResult(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);setProgress(0);failure(null);
let transfer:string|null=null;
try{
const issue=firmwareFileError(file,kind,formats);if(issue)throw new Error(issue);
const data=new Uint8Array(await file.arrayBuffer());
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data)),v=>v.toString(16).padStart(2,'0')).join('');
transfer=(await call<{transfer_id:string}>('begin',{name:file.name,bytes:data.length,sha256:digest,kind,
hardware,target_version:mode==='swd'?status.identity?.version:kind==='bootloader'?targetVersion:version,...(mode==='can'?{can_id:Number(canId),target}:{}),...(mode==='swd'?{swd}:{})})).transfer_id;
for(let offset=0;offset<data.length;offset+=32768){
if(!mounted.current)throw new Error('Подготовка файла остановлена.');
const chunk=data.subarray(offset,offset+32768);
await call('chunk',{transfer_id:transfer,offset,data:encode(chunk)});
if(mounted.current)setProgress((offset+chunk.length)/data.length);
}
const value=await call<FirmwarePreview>('seal',{transfer_id:transfer});
if(mounted.current)setPreview(value);
}catch(error){
if(mounted.current)failure(error);
if(transfer)try{await call('discard',{transfer_id:transfer});}catch{/* Expires without a write. */}
}finally{running.current=false;props.onBusyChange(false);if(mounted.current){setBusy(false);setProgress(null);}}
}
async function readCatalog(){
if(running.current||disabled)return;
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
try{const value=await call<FirmwareCatalog>('catalog',mode==='can'?{can_id:Number(canId)}:{});if(mounted.current){setCatalog(value);setImageId(value.items.find(i=>i.hardware_limits)?.id??value.items[0]?.id??'');}}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
async function prepareCatalog(){
if(running.current||disabled||!imageId)return;
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);setPreview(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);
try{const value=await call<FirmwarePreview>('catalog_prepare',{image_id:imageId,...(mode==='can'?{can_id:Number(canId)}:{})});if(mounted.current){setKind('firmware');setPreview(value);}}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
async function discard(){
if(!preview||running.current||disabled)return;
running.current=true;setBusy(true);props.onBusyChange(true);failure(null);
try{
await call('discard',{transfer_id:preview.transfer_id});
if(mounted.current){setPreview(null);setCompatible(false);setIsolated(false);}
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
async function apply(){
if(!preview||!compatible||!isolated||(preview.image.hardware_limits===false&&!withoutLimits)||running.current||disabled)return;
running.current=true;setUploading(true);setResult(null);failure(null);
const id=preview.transfer_id;setPreview(null);setCompatible(false);setIsolated(false);
try{
const value=await call<VescFirmwareState>('apply',{transfer_id:id,rig_clear:true,inputs_isolated:true,compatible_image_confirmed:true,...(preview.image.swd?{swd_target_confirmed:true}:{}),...(preview.image.hardware_limits===false?{hardware_limits_removed_confirmed:withoutLimits}:{})},300000);
if(mounted.current)setResult(value);
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current){setUploading(false);await props.refresh();}}
}
async function downloadBackup(){
if(!state.operation_id||busy||active)return;
setBusy(true);failure(null);
try{const value=await call<{backup:unknown}>('backup',{operation_id:state.operation_id});const url=URL.createObjectURL(new Blob([JSON.stringify(value.backup,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`vesc-backup-${state.before_backup_id}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
catch(error){if(mounted.current)failure(error);}finally{if(mounted.current)setBusy(false);}
}
async function reconcile(){
if(running.current||!enabled||!device.verified)return;
running.current=true;setBusy(true);failure(null);
try{const value=await call<VescFirmwareState>('reconcile');if(mounted.current){setResult(value);await props.refresh();}}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current)setBusy(false);}
}
async function cancel(){
if(!state.operation_id||cancelling)return;
setCancelling(true);failure(null);
try{await call('cancel',{operation_id:state.operation_id});}
catch(error){if(mounted.current)failure(error);}
finally{if(mounted.current)setCancelling(false);}
}
return <div className="sensor-content">
<FirmwareDestination mode={mode} onMode={v=>{setMode(v);setSource('file');setKind('firmware');setTarget(null);resetDestination();}} disabled={disabled} targets={status.engine?.contract?.firmware_targets??['usb']}
options={canOptions} canId={canId} onCanId={v=>{setCanId(v);setTarget(null);resetDestination();}} scan={()=>void canRead(true)} read={()=>void canRead(false)} target={target} swd={swd} onSwd={v=>{setSwd(v);resetDestination();}}/>
<SettingsCard title="Прошивка и загрузчик" description="Загрузка выбранного файла в указанное устройство. Конфигурация сохраняется перед записью; повторная запись после обрыва связи выполняется только по новой команде.">
{!status.firmware_update_supported&&<Description>Для загрузки прошивки требуется обновление бортового приложения.</Description>}
<Select label="Источник образа" value={source} options={[{value:'file',label:formats.includes('hex')?'Файл BIN / HEX':'Файл BIN'},...(formats.includes('hex')&&mode!=='swd'?[{value:'catalog',label:'Архив VESC'}]:[])]} disabled={disabled} onChange={value=>{setSource(value);setPreview(null);setCompatible(false);setIsolated(false);setWithoutLimits(false);}}/>
{source==='catalog'?<>
<Description>Официальный архив входит в бортовое приложение. Показаны образы для аппаратной конфигурации этого контроллера и версий, поддерживаемых установленным ядром. Архивные версии выбирают для восстановления или конкретной задачи.</Description>
<Button disabled={disabled||!destinationReady} loading={busy} onClick={()=>void readCatalog()}>Открыть архив для контроллера</Button>
{catalog&&<>
{catalog.items.length?<><Select label="Образ из архива" value={imageId} options={catalog.items.map(i=>({value:i.id,label:firmwareVariant(i)}))} disabled={disabled} onChange={value=>{setImageId(value);setPreview(null);setCompatible(false);setWithoutLimits(false);}}/>
<Button disabled={disabled||!imageId} loading={busy} onClick={()=>void prepareCatalog()}>Проверить выбранный образ</Button></>:<Description>В установленном архиве нет подходящего образа. Можно выбрать свой файл или обновить бортовое приложение.</Description>}
<ResourceList aria-label="Источник архива"><li><ResourceRow title="Репозиторий" description={catalog.repository}/></li><li><ResourceRow title="Ревизия архива" description={catalog.commit.slice(0,12)}/></li></ResourceList>
</>}
</>:<>
{mode!=='swd'&&<Select label="Тип образа" value={kind} options={[{value:'firmware',label:'Прошивка контроллера'},{value:'bootloader',label:'Загрузчик'}]} disabled={disabled}
onChange={value=>{setKind(value);setPreview(null);setCompatible(false);setIsolated(false);}}/>}
{mode!=='swd'&&kind==='firmware'&&<Select label="Версия в выбранном образе" value={version} options={Array.from(new Set(versions)).map(value=>({value,label:`Прошивка ${value}`}))} disabled={disabled}
onChange={value=>{setVersion(value);setPreview(null);setCompatible(false);}}/>}
<Description>BIN и HEX не подтверждают производителя платы. Выберите образ для {mode==='swd'?'выбранного процессора':hardware??'своего контроллера'} и указанной версии. Проверка структуры и SHA-256 не подтверждает происхождение файла. HEX проверяется оригинальным читателем VESC Tool; адреса и итоговый образ проверяются до записи. Сжатые BIN здесь не принимаются.</Description>
<input ref={input} type="file" accept={formats.includes('hex')?'.bin,.hex':'.bin'} hidden onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void stage(file);}}/>
<Button disabled={disabled||!version||!destinationReady} loading={busy} onClick={()=>input.current?.click()}>Выбрать и проверить файл</Button>
</>}
{progress!==null&&<ProgressBar label="Передача файла на борт" value={progress}/>}
</SettingsCard>
{preview&&<SettingsCard title="Образ готов к записи">
<ResourceList aria-label="Проверенный файл прошивки">
<li><ResourceRow title="Файл" description={preview.image.name}/></li>
<li><ResourceRow title="Размер" description={`${preview.image.bytes.toLocaleString('ru-RU')} байт`}/></li>
<li><ResourceRow title={preview.image.swd?"USB-программатор":"Контроллер"} description={`${preview.image.hardware} · ${preview.identity.uuid.toUpperCase()}`}/></li>
{preview.image.can_id!==undefined&&<li><ResourceRow title="Адрес CAN" description={String(preview.image.can_id)}/></li>}
{preview.image.swd&&<li><ResourceRow title="Цель SWD" description={`Семейство ${preview.image.swd.target_code} · ${preview.image.swd.pins} · адрес 0x${preview.image.swd.address.toString(16).toUpperCase()}`}/></li>}
<li><ResourceRow title="SHA-256 образа для записи" description={preview.image.sha256}/></li>
{preview.image.source_sha256&&preview.image.source_sha256!==preview.image.sha256&&<li><ResourceRow title="SHA-256 исходного файла" description={preview.image.source_sha256}/></li>}
{preview.image.format==='hex'&&<li><ResourceRow title="Адрес HEX" description={`0x${preview.image.base_address?.toString(16).toUpperCase()} · пропуски заполнены 0xFF`}/></li>}
</ResourceList>
<Description>Подготовка действует до 10 минут и отменяется после переподключения. Запись изменяет постоянную память; не отключайте питание. Старые настройки после смены прошивки автоматически не восстанавливаются.</Description>
{preview.image.hardware_limits===false&&<><Description>Этот вариант удаляет аппаратные пределы тока и напряжения из прошивки. Ошибочные настройки могут повредить контроллер или мотор.</Description><Checker label="Подтверждаю выбор образа без аппаратных пределов" checked={withoutLimits} onChange={setWithoutLimits} disabled={disabled}/></>}
<Checker label={preview.image.swd?"Подтверждаю физическую цель SWD, распиновку, flash и совместимость полного образа":"Образ соответствует этой плате и версии"} checked={compatible} onChange={setCompatible} disabled={disabled}/>
<Checker label="Входы отключены, приводы вывешены и остановлены" checked={isolated} onChange={setIsolated} disabled={disabled}/>
<Button variant="primary" disabled={disabled||!compatible||!isolated||(preview.image.hardware_limits===false&&!withoutLimits)} onClick={()=>void apply()}>{kind==='bootloader'?'Записать загрузчик':'Записать прошивку'}</Button>
<Button disabled={disabled} onClick={()=>void discard()}>Убрать подготовленный файл</Button>
</SettingsCard>}
{state.state!=='idle'&&<SettingsCard title="Результат загрузки">
<Description role="status">{labels[state.state]??state.state}</Description>
{active&&<><ProgressBar label="Запись контроллера" value={state.progress}/><Button disabled={!state.operation_id||cancelling} loading={cancelling} onClick={()=>void cancel()}>Запросить отмену</Button></>}
{state.image&&<ResourceList aria-label="Последняя загрузка"><li><ResourceRow title="Файл" description={state.image.name}/></li><li><ResourceRow title="SHA-256" description={state.image.sha256}/></li></ResourceList>}
{state.before_backup_id&&<><Description>Исходная конфигурация сохранена по UUID контроллера.</Description><Button disabled={busy||active||!available} onClick={()=>void downloadBackup()}>Скачать исходную конфигурацию</Button></>}
{!active&&!['identified','not_started'].includes(state.state)&&<>
<Description>Управление заблокировано до подтверждения результата. После обрыва или отмены версия контроллера сама по себе не доказывает завершение записи. Автоматического повторения нет.</Description>
<Button disabled={!enabled||!device.verified||busy} loading={busy} onClick={()=>void reconcile()}>Проверить контроллер после загрузки</Button>
</>}
{state.state==='identified'&&state.image?.swd&&<Description>Записанные байты прочитаны обратно и совпали; команда перезапуска подтверждена. Запуск приложения целевой платы ещё необходимо проверить.</Description>}
{state.state==='identified'&&!state.image?.swd&&<Description>Передача подтверждена, UUID и версия контроллера прочитаны заново. Обратное чтение бинарного образа этим протоколом не выполнено. Перед управлением проверьте настройки.</Description>}
</SettingsCard>}
</div>;
}
+18 -39
View File
@@ -1,42 +1,21 @@
import {useRef,useState} from 'react';
import {Button,Checker,SettingsCard} from '@nodedc/ui-react';
import {useEffect,useState} from 'react';
import {Button,Description,SettingsCard} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {vescStatus} from './model';
import {VescHallInputs} from './VescHallInputs';
import {VescHallMeasurement} from './VescHallMeasurement';
interface HallResult {
completed:boolean;configuration_restored:boolean;release_confirmed:boolean;
measurement:null|{valid_six_states:boolean;observed_states:number[];hall_table:number[]};
}
export function VescHall({device,transport,enabled,refresh,failure,blocked,onBusyChange}:SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void}){
const [confirmed,setConfirmed]=useState(false);
const [busy,setBusy]=useState(false);
const [result,setResult]=useState<HallResult|null>(null);
const running=useRef(false);
const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!vescStatus(device).hall_measurement;
async function measure(){
if(running.current||blocked||!available||!confirmed)return;
running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null);
try{
const inventory=await transport.inventory();
const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online);
const target=controllers.find(item=>item.id===device.id);
if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.');
setResult(await perform<HallResult>(transport,target,'vesc.hall.measure',{
rig_clear:true,native_cycle_confirmed:true,
...(vescStatus(target).hall_measurement?.standstill_confirmation_required?{standstill_confirmed:true}:{}),
sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])),
},60000));
}catch(error){failure(error);}
finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);await refresh();}
}
return <SettingsCard title="Датчики Холла" description={`${device.name} · штатное измерение VESC Tool, 5 А.`}>
<p>Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.</p>
<p>На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.</p>
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Все моторы остановлены, наблюдаю"/>
<Button disabled={!available||blocked||!confirmed||busy} loading={busy} onClick={()=>void measure()}>Измерить датчики Холла</Button>
{busy&&<p role="status">Подготовка и штатное измерение датчиков. Дождитесь результата.</p>}
{result&&<p role="status">{!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}</p>}
</SettingsCard>;
export function VescHall(props:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
const [expanded,setExpanded]=useState(false),[measuring,setMeasuring]=useState(false);
const identity=`${props.device.id}:${props.device.snapshot.context.session_id}`;
useEffect(()=>{if(props.active===false&&!measuring)setExpanded(false);},[props.active,measuring]);
useEffect(()=>setExpanded(false),[identity]);
const busy=(value:boolean)=>{setMeasuring(value);props.onBusyChange(value);};
return <div className="sensor-content">
<VescHallInputs {...props} key={identity} blocked={props.blocked||measuring}/>
<SettingsCard title="Измерение с вращением" description="Отдельная процедура VESC Tool: подаёт ток и вращает мотор. Для проверки контакта запускать её не обязательно.">
<Description>Пассивный просмотр выше не подаёт ток. Измерение ниже требует вывешенных приводов и выключенного пульта.</Description>
<Button variant="ghost" disabled={measuring} aria-expanded={expanded} onClick={()=>setExpanded(v=>!v)}>{expanded?'Скрыть процедуру':'Открыть процедуру с вращением'}</Button>
</SettingsCard>
{expanded&&<VescHallMeasurement {...props} key={identity} onBusyChange={busy}/>}
</div>;
}
@@ -0,0 +1,42 @@
import {useEffect,useRef,useState} from 'react';
import {Button,ComparisonTable,Description,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import type {ConfigurationRead} from './configuration';
import {vescStatus} from './model';
import {hallConfiguration} from './hallInputs';
export function VescHallInputs(props:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
const {device,transport,enabled,blocked,failure,onBusyChange}=props,status=vescStatus(device);
const [value,setValue]=useState<ConfigurationRead|null>(null),[busy,setBusy]=useState(false);
const mounted=useRef(true),running=useRef(false),epoch=useRef(0);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
useEffect(()=>{if(!device.online||!enabled){epoch.current++;setValue(null);}},[device.online,enabled]);
const available=enabled&&device.online&&device.verified&&status.readable&&status.configuration_read_supported;
async function read(){
if(running.current||blocked||!available||props.active===false)return;
const token=epoch.current;running.current=true;setBusy(true);setValue(null);onBusyChange(true);failure(null);
try{const result=await perform<ConfigurationRead>(transport,device,'vesc.configuration.read',{},30000);if(mounted.current&&token===epoch.current)setValue(result);}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
}
const config=hallConfiguration(value),fw=status.identity?.version;
return <>
<SettingsCard title="Входы Холла · без вращения" description="Три логических сигнала положения ротора. Это часть управления мотором, а не только телеметрия.">
<StatusBadge tone="neutral">{!device.online||!enabled?'Нет связи':fw==='5.02'?'Пассивное чтение H1–H3 недоступно':'Пассивное чтение H1–H3 не подтверждено'}</StatusBadge>
<ComparisonTable density="compact" label="Доступность входов Холла" heading="Сигнал" columns={[1,2,3].map(i=>({id:String(i),label:`H${i}`}))} rows={[
{id:'level',label:'Уровень 0 / 1',cells:config.inputs.map(()=>'Нет данных')},
{id:'changes',label:'Переключения',cells:config.transitions.map(()=>'Не измерены')},
]}/>
<Description>{fw==='5.02'?'Штатная прошивка 5.02 не предоставляет отдельное пассивное чтение этих входов. Код Hall в Sample Data — преобразованная фаза; он не подтверждает уровни H1–H3.':'Для этой прошивки достоверный способ пассивного чтения трёх входов пока не подтверждён.'}</Description>
<Description>«Нет данных» не означает обрыв. Неподвижный вал не обязан давать переключения; одно состояние не доказывает исправность всех трёх датчиков. Установка пина обратно не меняет режим управления автоматически.</Description>
</SettingsCard>
<SettingsCard title="Использование датчиков в контроллере" description={value?`Настройки прочитаны ${new Date(value.observed_at).toLocaleString('ru-RU')}`:'Прочитайте сохранённые настройки. Чтение не подаёт ток и не меняет конфигурацию.'}
actions={<Button disabled={!available||blocked||busy} loading={busy} onClick={()=>void read()}>Прочитать настройки датчиков</Button>}>
<ResourceList aria-label="Настройки датчиков Холла">{[
['Тип мотора',config.motor],['Режим порта датчиков',config.port],['Режим датчиков FOC',config.mode],['Участие Холлов в управлении',config.use],
].map(([title,description])=><li key={title}><ResourceRow title={title} description={description}/></li>)}</ResourceList>
<Description>Это выбранные настройки, а не результат обнаружения датчика. Ремонт контакта и правильность переключений ими не подтверждаются.</Description>
</SettingsCard>
</>;
}
@@ -0,0 +1,47 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,SettingsCard} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {vescStatus} from './model';
interface HallResult {
completed:boolean;configuration_restored:boolean;release_confirmed:boolean;
measurement:null|{valid_six_states:boolean;observed_states:number[];hall_table:number[]};
}
export function VescHallMeasurement({device,transport,enabled,refresh,failure,blocked,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked:boolean;onBusyChange:(busy:boolean)=>void}){
const [confirmed,setConfirmed]=useState(false);
const [raised,setRaised]=useState(false),[remoteOff,setRemoteOff]=useState(false);
const [busy,setBusy]=useState(false);
const [result,setResult]=useState<HallResult|null>(null);
useEffect(()=>{if(!active){setConfirmed(false);setRaised(false);setRemoteOff(false);}},[active]);
const running=useRef(false);
const available=enabled&&device.online&&device.verified&&device.vesc_status?.test_supported===true&&!!vescStatus(device).hall_measurement;
async function measure(){
if(!active||running.current||blocked||!available||!confirmed||!raised||!remoteOff)return;
running.current=true;setBusy(true);onBusyChange(true);setResult(null);failure(null);
try{
const inventory=await transport.inventory();
const controllers=inventory.items.filter(item=>item.kind==='vesc.controller'&&item.online);
const target=controllers.find(item=>item.id===device.id);
if(inventory.fresh===false||!target||controllers.some(item=>!item.verified))throw new Error('Нужна свежая связь со всеми VESC борта.');
setResult(await perform<HallResult>(transport,target,'vesc.hall.measure',{
rig_clear:true,native_cycle_confirmed:true,
...(vescStatus(target).hall_measurement?.standstill_confirmation_required?{standstill_confirmed:true}:{}),
sessions:Object.fromEntries(controllers.map(item=>[item.id,item.snapshot.context.session_id])),
},60000));
}catch(error){failure(error);}
finally{running.current=false;setBusy(false);onBusyChange(false);setConfirmed(false);setRaised(false);setRemoteOff(false);await refresh();}
}
return <SettingsCard title="Измерение с вращением мотора" description={`${device.name} · штатное измерение VESC Tool, 5 А.`}>
<Description>Мотор медленно смещается в обе стороны около 12 секунд. Измерение проверяет состояния датчиков и получает таблицу их положения; новая таблица автоматически не записывается.</Description>
<Description>На прошивке 5.02 этот цикл нельзя прервать кнопкой или пультом. Для немедленной остановки нужно отключить силовое питание. Пульт должен оставаться выключенным, все приводы — вывешенными. Перед запуском убедитесь, что все моторы полностью остановились: в бессенсорном режиме показание оборотов на остановленном моторе может быть ненулевым.</Description>
<Checker checked={raised} onChange={setRaised} disabled={busy||blocked} label="Все приводы вывешены"/>
<Checker checked={remoteOff} onChange={setRemoteOff} disabled={busy||blocked} label="Пульт выключен"/>
<Checker checked={confirmed} onChange={setConfirmed} disabled={busy||blocked} label="Все моторы остановлены, наблюдаю"/>
<Button disabled={!active||!available||blocked||!confirmed||!raised||!remoteOff||busy} loading={busy} onClick={()=>void measure()}>Запустить вращение и измерение · 5 А</Button>
{busy&&<Description role="status">Подготовка и штатное измерение датчиков. Дождитесь результата.</Description>}
{result&&<Description role="status">{!result.completed?'Завершение измерения не подтверждено. Проверьте мотор и питание.':result.measurement?.valid_six_states?'Измерение получило шесть состояний Холла.':'Не удалось получить полную таблицу Холла. Возможны отсутствие движения или неисправность датчиков/соединения.'} {result.release_confirmed?'Снятие тока подтверждено.':'Снятие тока не подтверждено.'} {result.configuration_restored?'Исходная конфигурация сохранена.':'Возврат исходной конфигурации не подтверждён.'}</Description>}
</SettingsCard>;
}
+3 -2
View File
@@ -1,3 +1,4 @@
import {Description} from '@nodedc/ui-react';
import {useRef,useState} from 'react';
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import {perform,type Sensor,type SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
@@ -16,7 +17,7 @@ export function VescLimits({controllers,transport,enabled,failure}:{controllers:
catch(error){failure(error);}finally{running.current=false;setBusy(false);}
}
return <SettingsCard title="Ограничения контроллеров" description="Текущие настройки VESC. Чтение не запускает моторы и не меняет конфигурацию." actions={<Button disabled={!enabled||busy||!readable.length} loading={busy} onClick={()=>void read()}>Прочитать ограничения</Button>}>
<p>Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.</p>
<Description>Ток мотора задаёт тягу; ток батареи ограничивает потребление. Эти настройки действуют и при управлении с пульта. Паспортные пределы моторов, контроллеров и батареи проверяются отдельно.</Description>
{controllers.map(device=>{
const value=values[device.id];if(!value)return null;
const p=value.parameters;
@@ -30,6 +31,6 @@ export function VescLimits({controllers,transport,enabled,failure}:{controllers:
];
return <SettingsCard key={device.id} title={device.name} description={`Прочитано ${new Date(value.observed_at).toLocaleString('ru-RU')}`}><ResourceList aria-label={`Ограничения ${device.name}`}>{fields.map(([title,description])=><li key={title}><ResourceRow title={title} description={description}/></li>)}</ResourceList></SettingsCard>;
})}
{!Object.keys(values).length&&<p>Прочитайте значения для подключённых контроллеров.</p>}
{!Object.keys(values).length&&<Description>Прочитайте значения для подключённых контроллеров.</Description>}
</SettingsCard>;
}
+3 -2
View File
@@ -1,3 +1,4 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,ResourceList,ResourceRow,SettingsCard} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
@@ -35,8 +36,8 @@ export function VescLink({device,transport,enabled,failure,refresh,blocked,onBus
'Измерение не завершено.';
return <SettingsCard title="Связь с контроллерами" description="Проверяет ответы всех VESC борта около 10 секунд. Моторы должны стоять; команды вращения и изменения настроек не отправляются."
actions={<Button disabled={!available||blocked||busy} loading={busy} onClick={()=>void check()}>Проверить связь</Button>}>
{busy&&<p role="status">Измеряется время ответа контроллеров.</p>}
{result&&<><p role="status">{text}</p><ResourceList aria-label="Связь VESC">{Object.entries(result.devices).map(([id,item])=><li key={id}><ResourceRow title={item.name}
{busy&&<Description role="status">Измеряется время ответа контроллеров.</Description>}
{result&&<><Description role="status">{text}</Description><ResourceList aria-label="Связь VESC">{Object.entries(result.devices).map(([id,item])=><li key={id}><ResourceRow title={item.name}
description={`${item.summary.replies} ответов${item.summary.max_ms===undefined?'':` · 95% не дольше ${Math.ceil(item.summary.p95_ms??0)} мс · максимум ${Math.ceil(item.summary.max_ms)} мс`}`}/></li>)}</ResourceList></>}
</SettingsCard>;
}
@@ -0,0 +1,40 @@
import {useEffect,useMemo,useRef,useState} from 'react';
import {Button,Description,RangeControl,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {LOG_MAX_BYTES,parseVescLog,spectrum,type VescLog} from './logAnalysis';
import {SignalPlot} from './SignalPlot';
export function VescLogAnalysis(){
const [log,setLog]=useState<VescLog|null>(null),[name,setName]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
const [keys,setKeys]=useState<string[]>([]),[from,setFrom]=useState(0),[to,setTo]=useState(0),[fftKey,setFftKey]=useState(''),[fftEnabled,setFftEnabled]=useState(false);
const input=useRef<HTMLInputElement>(null),generation=useRef(0);
useEffect(()=>()=>{generation.current++;},[]);
async function open(file:File){const request=++generation.current;setBusy(true);setError('');
try{if(file.size>LOG_MAX_BYTES)throw new Error('Максимальный размер CSV — 4 МиБ.');const parsed=parseVescLog(await file.text());if(request!==generation.current)return;
setLog(parsed);setName(file.name);setKeys(parsed.columns.slice(0,2).map(c=>c.key));setFrom(0);setTo(parsed.duration);setFftKey(parsed.columns[0].key);setFftEnabled(false);
}catch(e){if(request===generation.current)setError(e instanceof Error?e.message:'Не удалось прочитать журнал.');}
finally{if(request===generation.current)setBusy(false);}
}
const fft=useMemo(()=>{if(!log||!fftEnabled)return null;try{return {value:spectrum(log.points,fftKey,from,to),error:''};}catch(e){return {value:null,error:e instanceof Error?e.message:'Спектр недоступен.'};}},[log,fftKey,from,to,fftEnabled]);
const options=log?.columns.map(c=>({value:c.key,label:c.label+(c.unit?` · ${c.unit}`:'')}))??[];
return <div className="sensor-content"><SettingsCard title="Анализ журнала" description="Откройте CSV Mission Core или оригинального VESC Tool. Файл обрабатывается в этом окне и не отправляется на борт." actions={<StatusBadge>Сохранённые данные</StatusBadge>}>
<input ref={input} type="file" hidden accept=".csv,text/csv" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void open(file);}}/>
<div className="sensor-actions"><Button loading={busy} onClick={()=>input.current?.click()}>Открыть CSV</Button>{log&&<Button disabled={busy} onClick={()=>{generation.current++;setLog(null);setName('');setError('');}}>Закрыть журнал</Button>}</div>
{error&&<Description role="alert">{error}</Description>}
<Description>До 4 МиБ и 20 000 строк. Поддерживаются Sample Data, RT CSV и Log Analysis CSV VESC Tool. Пустые ячейки остаются пропусками. При закрытии раздела журнал удаляется из памяти. Импорт не меняет живую телеметрию и настройки контроллера.</Description>
{log&&<ResourceList aria-label="Открытый журнал"><li><ResourceRow title={name} description={`${log.format} · ${log.points.length} строк · ${(log.duration/1000).toLocaleString('ru-RU')} с`}/></li><li><ResourceRow title="Контроллер в журнале" description={log.uuid?`${log.uuid.toUpperCase()} · ${log.hardware??'аппаратура не указана'} · ${log.firmware??'прошивка не указана'}`:'UUID в этом формате не указан. Принадлежность открытому VESC не подтверждена.'}/></li></ResourceList>}
</SettingsCard>{log&&<>
<SettingsCard title="Сравнение сигналов" description="До четырёх графиков с общей осью времени. Каждый сигнал сохраняет собственные единицы и шкалу.">
<RangeControl label="Начало интервала" min={0} max={log.duration} step={1} value={from} onChange={value=>setFrom(Math.min(value,to))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/>
<RangeControl label="Конец интервала" min={0} max={log.duration} step={1} value={to} onChange={value=>setTo(Math.max(from,value))} formatValue={v=>`${(v/1000).toFixed(3)} с`}/>
{keys.map((key,i)=><div key={i} className="sensor-actions"><Select label={`Сигнал ${i+1}`} value={key} options={options.filter(o=>o.value===key||!keys.includes(o.value))} onChange={value=>setKeys(previous=>previous.map((v,j)=>i===j?value:v))}/><Button disabled={keys.length===1} onClick={()=>setKeys(previous=>previous.filter((_,j)=>j!==i))}>Убрать сигнал {i+1}</Button></div>)}
<Button disabled={keys.length>=4||keys.length>=options.length} onClick={()=>{const next=options.find(o=>!keys.includes(o.value));if(next)setKeys(previous=>[...previous,next.value]);}}>Добавить сигнал</Button>
</SettingsCard>
{keys.map(key=>{const column=log.columns.find(c=>c.key===key)!;return <SignalPlot key={key} title={column.label} unit={column.unit} from={from} to={to} points={log.points.map(p=>({at:p.at,value:p.gap?null:p.values[key]??null}))}/>;})}
<SettingsCard title="Частотный анализ FFT" description="Амплитудный спектр выбранного участка. Среднее удаляется, применяется окно Ханна; амплитуда указана в единицах сигнала.">
<Select label="Сигнал для FFT" value={fftKey} options={options} onChange={setFftKey}/><Button onClick={()=>setFftEnabled(v=>!v)}>{fftEnabled?'Скрыть спектр':'Показать спектр'}</Button>
<Description>Используются последние 32–4096 измерений участка, число округляется вниз до степени двойки. Пропуски и неравномерный шаг блокируют расчёт. Верхняя частота — половина частоты измерений; журнал с частотой 2 Гц не позволяет анализировать быстрые процессы мотора.</Description>
{fft?.error&&<Description role="status">{fft.error}</Description>}
{fft?.value&&<Description>{fft.value.n} измерений · частота {(fft.value.rate).toLocaleString('ru-RU',{maximumFractionDigits:3})} Гц · разрешение {(fft.value.rate/fft.value.n).toLocaleString('ru-RU',{maximumFractionDigits:5})} Гц · интервал {(fft.value.from/1000).toFixed(3)}–{(fft.value.to/1000).toFixed(3)} с · пик {fft.value.peak.hz.toLocaleString('ru-RU',{maximumFractionDigits:5})} Гц / {fft.value.peak.amplitude.toLocaleString('ru-RU',{maximumFractionDigits:5})} {log.columns.find(c=>c.key===fftKey)?.unit}</Description>}
</SettingsCard>
{fft?.value&&<SignalPlot title="Амплитудный спектр" unit={log.columns.find(c=>c.key===fftKey)?.unit??''} points={fft.value.bins.map(b=>({at:b.hz,value:b.amplitude}))} from={0} to={fft.value.rate/2} xUnit="Гц" xScale={1}/>}
</>}</div>;
}
+11 -9
View File
@@ -1,10 +1,11 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,Select,TextField,SettingsCard} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {testInput,speedInput,rotationResult,vescStatus,driveTestIds,drivePositions} from './model';
export function VescMotor({device,transport,enabled,refresh,failure,blocked=false,onBusyChange}:SensorDetailProps&{blocked?:boolean;onBusyChange?:(busy:boolean)=>void}){
export function VescMotor({device,transport,enabled,refresh,failure,blocked=false,onBusyChange,active=true}:SensorDetailProps&{active?:boolean;blocked?:boolean;onBusyChange?:(busy:boolean)=>void}){
const [duration,setDuration]=useState('30');
const [current,setCurrent]=useState('30');
const [speed,setSpeed]=useState('2000');
@@ -17,6 +18,7 @@ export function VescMotor({device,transport,enabled,refresh,failure,blocked=fals
const [clear,setClear]=useState(false);const [busy,setBusy]=useState(false);
const [result,setResult]=useState<string|null>(null);const [stopping,setStopping]=useState(false);
const [rc,setRc]=useState(device.vesc_status?.rc_latched===true);
useEffect(()=>{if(!active)setClear(false);},[active]);
const running=useRef(false);const mounted=useRef(true);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const limits=vescStatus(device).test_limits;
@@ -66,24 +68,24 @@ export function VescMotor({device,transport,enabled,refresh,failure,blocked=fals
}
useEffect(()=>setRc(device.vesc_status?.rc_latched===true),[device.vesc_status?.rc_latched]);
return <SettingsCard title="Проверка вращения" description={`${device.name} · ${device.connection_label??'USB'}. Конфигурации подключённых контроллеров сохраняются автоматически.`}>
<p>Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.</p>
<Description>Для вывешенных колёс без нагрузки. При команде с приёмника проверка прекращается; повторный запуск требует явного возврата управления.</Description>
<Select label="Проверяемые моторы" value={scope} disabled={busy||blocked} options={[{value:'single',label:`Только ${device.name}`},{value:'profile',label:'Все моторы профиля одновременно',disabled:!groupAvailable}]} onChange={setScope}/>
{group&&profile&&<p>{Object.keys(drivePositions(profile.layout)).map(slot=>`${drivePositions(profile.layout)[slot]} · VESC ${profile.bindings[slot]?.uuid.slice(0,6).toUpperCase()??'не назначен'}`).join('; ')}. Общий отсчёт начинается, когда все моторы удерживают скорость. Остановка любого завершает всю проверку. Предел тока применяется к каждому мотору.</p>}
{group&&profile&&<Description>{Object.keys(drivePositions(profile.layout)).map(slot=>`${drivePositions(profile.layout)[slot]} · VESC ${profile.bindings[slot]?.uuid.slice(0,6).toUpperCase()??'не назначен'}`).join('; ')}. Общий отсчёт начинается, когда все моторы удерживают скорость. Остановка любого завершает всю проверку. Предел тока применяется к каждому мотору.</Description>}
<Select label="Направление вращения" value={direction} disabled={busy||blocked} options={[{value:'forward',label:'Прямое'},{value:'reverse',label:'Обратное',disabled:speedLimits?.reverse_supported!==true}]} onChange={value=>{setDirection(value);setClear(false);}}/>
<p>Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.</p>
<Description>Направление относительно настроек VESC. Перед обратным запуском дождитесь полной остановки всех моторов и подтвердите её.</Description>
<TextField type="number" inputMode="decimal" label="Скорость, ERPM" value={speed} onChange={event=>setSpeed(event.target.value)} disabled={busy||!speedLimits} min={speedLimits?.min_erpm} max={speedLimits?.max_erpm} step="100" aria-invalid={!!speedValue.error} description={speedValue.error??'Электрические обороты в минуту. VESC плавно разгоняет мотор и удерживает заданную скорость.'}/>
<TextField type="number" inputMode="decimal" label="Предел тока мотора, А" value={current} onChange={event=>setCurrent(event.target.value)} disabled={busy||!limits} min={limits?.min_current_a} max={limits?.max_current_a} step="0.1" aria-invalid={!!input.currentError} hint={limits?`${limits.min_current_a}–${limits.max_current_a} А`:undefined} description={input.currentError??'Максимальный ток разгона и удержания скорости. Прежние пределы сохраняются перед тестом и восстанавливаются после него.'}/>
<TextField type="number" inputMode="decimal" label="Длительность вращения, с" value={duration} onChange={event=>setDuration(event.target.value)} disabled={busy||!limits} min={limits?.min_duration_s} max={limits?.max_duration_s} step="0.1" aria-invalid={!!input.durationError} hint={limits?`${limits.min_duration_s}–${limits.max_duration_s} с`:undefined} description={input.durationError??'Отсчёт начинается после разгона и стабилизации скорости. Подготовка, разгон и остановки не входят в это время.'}/>
<p>Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.</p>
{limits?.stall_timeout_s&&<p>При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.</p>}
<p>Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.</p>
<Description>Время считается по скорости и тахометру VESC. Если мотор не разгонится за 15 секунд, потеряет скорость или сработает ограничение, результат покажет фактическое время и причину остановки. Показания контроллера нужно сопоставить с видимым вращением.</Description>
{limits?.stall_timeout_s&&<Description>При токе выше {limits.stall_current_a} А и отсутствии подтверждённого движения в течение {limits.stall_timeout_s} секунд проверка остановится.</Description>}
<Description>Все приводы должны быть вывешены, вращение свободно. Подтверждение требуется перед каждым запуском.</Description>
<Checker checked={clear} onChange={setClear} disabled={busy} label="Все моторы остановлены, наблюдаю"/>
{blockedReason&&<p role="status">{blockedReason}</p>}
{blockedReason&&<Description role="status">{blockedReason}</Description>}
<div className="sensor-actions">
{rc?<Button disabled={!available||!clear||busy||!valid} loading={busy} onClick={()=>void execute(true)}>Вернуть управление после нейтрали</Button>:
<Button disabled={!available||!clear||busy||!valid} loading={busy} onClick={()=>void execute()}>Проверить вращение</Button>}
<Button disabled={!enabled||!device.online||blocked} loading={stopping} onClick={()=>void stop()}>Остановить проверку</Button>
</div>
{result&&<p role="status">{result}</p>}
{result&&<Description role="status">{result}</Description>}
</SettingsCard>;
}
@@ -0,0 +1,89 @@
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
import {Button,Checker,Description,ResourceList,ResourceRow,Select,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {VescQmlPreview} from './VescQmlPreview';
import {bytesBase64} from './editorFiles';
interface Item {id:string;name:string;path:string;library:boolean;imported?:boolean;bytes:number;lisp_bytes:number;qml_bytes:number;description:string;qml_source?:string;compatible?:boolean|null;fits?:boolean}
interface Catalog {sha256:string;items:Item[];source:string}
interface Installed {pending:boolean;recognized:boolean;empty:boolean;installed:{id:string;name:string;path:string}|null}
interface Preview {preview_id:string;package:{id:string;name:string}|null;before:Record<string,{bytes:number}>}
const hash=async(data:Uint8Array)=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array(data)))).map(v=>v.toString(16).padStart(2,'0')).join('');
export function VescPackages(props:ReadProps){
const status=vescStatus(props.device),file=useRef<HTMLInputElement>(null),running=useRef(false),mounted=useRef(true);
const [catalog,setCatalog]=useState<Catalog|null>(null),[selected,setSelected]=useState<Item|null>(null),[installed,setInstalled]=useState<Installed|null>(null);
const [busy,setBusy]=useState(false),[query,setQuery]=useState(''),[category,setCategory]=useState('all'),[message,setMessage]=useState('');
const [library,setLibrary]=useState(false),[compatible,setCompatible]=useState(false),[confirmed,setConfirmed]=useState(false),[preview,setPreview]=useState<Preview|null>(null);
const available=props.enabled&&props.device.online&&props.device.verified,disabled=busy||props.blocked||!available;
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0;
const pending=installed?.pending||status.package_pending;
const call=<T,>(action:string,parameters:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.packages.'+action,parameters,timeout);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
async function run(work:()=>Promise<void>){if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
async function list(){const c=await call<Catalog>('catalog');if(mounted.current){setCatalog(c);setSelected(old=>old&&c.items.some(i=>i.id===old.id)?old:null);}}
async function read(){const v=await call<Installed>('status',{},90000);if(mounted.current)setInstalled(v);}
const load=()=>run(async()=>{clear();await list();});
const inspect=(id:string)=>run(async()=>{clear();setCompatible(false);const v=await call<Item>('inspect',{id});if(mounted.current)setSelected(v);});
async function importFile(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;await run(async()=>{
clear();const kind=f.name.toLowerCase().endsWith('.rcc')?'catalog':'package',limit=kind==='catalog'?8*1024*1024:1024*1024;
if(f.size>limit)throw new Error('Файл превышает предел: пакет — 1 МБ, каталог — 8 МБ.');
const data=new Uint8Array(await f.arrayBuffer()),sha256=await hash(data);
const b=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,name:f.name.replace(/[^A-Za-z0-9_. -]/g,'_').slice(0,128),size:data.length,sha256,library,source:'import'});
for(let at=0;at<data.length;at+=b.chunk_bytes){const chunk=data.slice(at,at+b.chunk_bytes),v=await call<{offset:number}>('chunk',{upload_id:b.upload_id,offset:at,data:bytesBase64(chunk)});if(v.offset!==at+chunk.length)throw new Error('Фрагмент файла не подтверждён.');}
await call('load',{upload_id:b.upload_id});await list();if(mounted.current)setMessage('Импорт проверен и добавлен в каталог. Контроллер не изменён.');
});}
const download=()=>run(async()=>{if(!selected)return;const pieces:Uint8Array[]=[];let at=0;
while(at<selected.bytes){const v=await call<{id:string;bytes:number;offset:number;data:string}>('download',{id:selected.id,offset:at});const part=Uint8Array.from(atob(v.data),c=>c.charCodeAt(0));if(v.id!==selected.id||v.offset!==at||v.bytes!==selected.bytes||!part.length||at+part.length>selected.bytes)throw new Error('Получен неполный пакет.');pieces.push(part);at+=part.length;}
const data=new Uint8Array(at);at=0;for(const p of pieces){data.set(p,at);at+=p.length;}if(await hash(data)!==selected.id)throw new Error('Контрольная сумма пакета не совпала.');
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'})),a=document.createElement('a');a.href=url;a.download=selected.path.split('/').at(-1)||'extension.vescpkg';a.click();setTimeout(()=>URL.revokeObjectURL(url),0);
});
const prepare=(action:string,p:Record<string,unknown>={})=>run(async()=>{clear();const v=await call<Preview>(action,p,90000);if(mounted.current)setPreview(v);});
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const id=preview.preview_id;clear();const v=await call<{verified:boolean;message?:string}>('apply',{preview_id:id,confirmed:true,inputs_isolated:true},350000);if(mounted.current){setMessage(v.message??(v.verified?'Расширение записано и проверено. Lisp не запускался.':'Итог записи неизвестен.'));setInstalled(old=>old?{...old,pending:!v.verified}:null);}await props.refresh();if(v.verified)await read();});
const items=catalog?.items.filter(i=>(category==='all'||(category==='libraries')===i.library)&&`${i.name} ${i.path}`.toLowerCase().includes(query.toLowerCase()))??[];
const updating=Boolean(installed?.installed&&selected&&installed.installed.path===selected.path&&installed.installed.id!==selected.id);
return <div className="sensor-content">
<SettingsCard title="Расширения VESC" description="Готовые приложения и библиотеки Lisp/QML из каталога VESC Tool. Загрузка пакета в каталог, запись на контроллер и запуск Lisp выполняются отдельно.">
<Button loading={busy} disabled={disabled} onClick={()=>void load()}>Открыть сохранённый каталог</Button>
<Button disabled={disabled} onClick={()=>void run(async()=>{clear();await call('refresh',{},180000);await list();if(mounted.current)setMessage('Каталог автора обновлён. Установленное расширение не изменено.');})}>Обновить каталог автора</Button>
<Description>Автор распространяет каталог по HTTP. Перед установкой проверьте описание, совместимость и состав выбранного пакета.</Description>
<input hidden type="file" ref={file} accept=".vescpkg,.rcc" onChange={e=>void importFile(e)}/>
<Button disabled={disabled} onClick={()=>file.current?.click()}>Импорт пакета или каталога</Button>
<Checker label="Импортировать отдельный пакет как библиотеку" checked={library} onChange={setLibrary} disabled={disabled}/>
{!supported&&<Description role="status">Прошивка контроллера {status.identity?.version??'не определена'}. Каталог и импорт доступны; запись расширений поддерживается для VESC 6.00. Обновление каталога не меняет прошивку.</Description>}
</SettingsCard>
<SettingsCard title="На контроллере" description="Состояние определяется чтением обеих частей: Lisp и QML. После ручного изменения кода старое название пакета не считается подтверждённым.">
<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();await read();})}>Прочитать установленное расширение</Button>
{installed&&<Description>{installed.installed?`${installed.installed.name} · ${installed.installed.id.slice(0,12)}`:installed.empty?'Lisp и QML приложения отсутствуют.':'Есть пользовательский код. Его пакет не определён.'}</Description>}
{pending&&<Description role="status">Предыдущее изменение не подтверждено. Проверьте содержимое или восстановите исходную копию.</Description>}
{pending&&<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();const v=await call<{verified:boolean}>('reconcile',{},90000);await props.refresh();await read();if(mounted.current)setMessage(v.verified?'Содержимое подтверждено.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление.');})}>Проверить запись</Button>}
<Button disabled={disabled||!supported} onClick={()=>void prepare('restore')}>Подготовить восстановление копии</Button>
<Button disabled={disabled||!supported||pending} onClick={()=>void prepare('remove_prepare')}>Подготовить удаление расширения</Button>
</SettingsCard>
{selected&&<SettingsCard title={selected.name} description={`${selected.library?'Библиотека':'Приложение'} · ревизия ${selected.id.slice(0,12)}`}>
<ResourceList aria-label="Состав расширения"><li><ResourceRow title="Lisp с вложениями" description={`${selected.lisp_bytes} байт`}/></li><li><ResourceRow title="QML-интерфейс" description={`${selected.qml_bytes} байт`}/></li><li><ResourceRow title="Совместимость по описанию автора" description={selected.compatible===true?'Тип контроллера разрешён автором':selected.compatible===false?'Этот контроллер исключён автором':'Условия не определены или не удалось проверить'}/></li></ResourceList>
{selected.description&&<TextAreaField label="README автора" value={selected.description} readOnly rows={12}/>}
{selected.library?<Description>Библиотеку используют через import в проекте Lisp. Она не заменяет приложение контроллера. Примеры pkg@ и pkg:: из README работают в редакторе Lisp: вложения берутся из сохранённого каталога.</Description>:<>
{selected.compatible==null&&<Checker label="Совместимость проверена по документации автора" checked={compatible} onChange={setCompatible} disabled={disabled}/>}
<Description>Запись заменит Lisp и QML приложения, включая пустые части пакета. Исходная копия сохраняется. Запуск здесь не выполняется; поведение после перезагрузки определяется прошивкой контроллера.</Description>
<Button disabled={disabled||!supported||pending||selected.compatible===false||selected.fits===false||(selected.compatible==null&&!compatible)} onClick={()=>void prepare('prepare',{id:selected.id,compatibility_confirmed:compatible})}>{updating?'Подготовить обновление':'Подготовить установку'}</Button>
{selected.fits===false&&<Description>Код не помещается во flash текущего профиля.</Description>}
</>}
<Button disabled={disabled} onClick={()=>void download()}>Скачать .vescpkg</Button>
{selected.imported&&<Button disabled={disabled} onClick={()=>void run(async()=>{await call('forget',{id:selected.id});if(mounted.current)setSelected(null);await list();})}>Убрать импорт из каталога</Button>}
</SettingsCard>}
{selected?.qml_source&&<VescQmlPreview {...props} source={selected.qml_source}/>}
{preview&&<SettingsCard title="Подтверждение записи" description="Операция привязана к UUID, прошивке, текущему коду и сеансу контроллера; подтверждение действует пять минут.">
<Description>{preview.package?`Запись: ${preview.package.name}.`:'Удаление кода приложения или восстановление пользовательского кода.'} При потере связи автоматического повтора не будет. Проверка результата и восстановление доступны выше.</Description>
<Checker label="Операция подтверждена, внешние входы отключены" checked={confirmed} onChange={setConfirmed} disabled={disabled}/>
<Button variant="primary" disabled={disabled||!confirmed} onClick={()=>void apply()}>Выполнить запись без запуска</Button>
</SettingsCard>}
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
{catalog&&<SettingsCard title="Каталог" description={`${catalog.items.length} пакетов · ревизия ${catalog.sha256.slice(0,12)}`}>
<TextField label="Поиск расширения" value={query} onChange={e=>setQuery(e.target.value)}/><Select label="Тип пакета" value={category} onChange={setCategory} options={[{value:'all',label:'Все'},{value:'applications',label:'Приложения'},{value:'libraries',label:'Библиотеки'}]}/>
<ResourceList aria-label="Расширения VESC">{items.map(item=><li key={item.path+item.id}><ResourceRow title={item.name} description={`${item.library?'Библиотека':'Приложение'} · ${item.id.slice(0,12)}`} actions={<Button disabled={disabled} onClick={()=>void inspect(item.id)}>Открыть</Button>}/></li>)}</ResourceList>
{!items.length&&<Description>Подходящих пакетов нет.</Description>}
</SettingsCard>}
</div>;
}
@@ -0,0 +1,25 @@
import {Checker,Select,TextField} from '@nodedc/ui-react';
import type {VescParameter} from './configuration';
export type Drafts=Record<string,string|boolean>;
export function parseDraft(p:VescParameter,draft:string|boolean){
if(p.type==='boolean')return {value:draft===true,error:null};
if(p.type==='string')return {value:String(draft),error:String(draft).length>(p.max_length??0)?'Слишком длинное значение.':null};
const scale=p.type==='number'?(p.editor_scale||1):1;
const value=Number(String(draft).replace(',','.'))/scale;
const error=String(draft).trim()===''||!Number.isFinite(value)?'Введите число.':
p.type!=='number'&&!Number.isInteger(value)?'Введите целое число.':
p.type==='enum'&&(value<0||value>=(p.options?.length??0))?'Выберите допустимое значение.':
p.type==='bitfield'&&(value<0||value>255)?'Битовая маска должна быть от 0 до 255.':
p.type!=='enum'&&p.type!=='bitfield'&&((p.min!==undefined&&value<p.min)||(p.max!==undefined&&value>p.max))?'Значение вне диапазона VESC Tool.':null;
return {value,error};
}
export function initialDraft(p:VescParameter):string|boolean{return p.type==='boolean'?Boolean(p.value):typeof p.value==='number'?String(p.value*(p.type==='number'?(p.editor_scale||1):1)):String(p.value);}
export function VescParameterEditor({parameter:p,value,onChange,disabled}:{parameter:VescParameter;value:string|boolean;onChange:(value:string|boolean)=>void;disabled:boolean}){
const label=(p.title||p.name)+(p.suffix?' · '+p.suffix:'');
if(p.type==='boolean')return <Checker label={label} checked={value===true} onChange={onChange} disabled={disabled}/>;
if(p.type==='enum')return <Select label={label} value={String(value)} options={(p.options??[]).map((label,i)=>({label,value:String(i)}))} onChange={onChange} disabled={disabled}/>;
const parsed=parseDraft(p,value),scale=p.type==='number'?(p.editor_scale||1):1;
return <TextField label={label} value={String(value)} onChange={event=>onChange(event.target.value)} disabled={disabled}
inputMode={p.type==='string'?'text':'decimal'} aria-invalid={!!parsed.error}
description={parsed.error??(p.min!==undefined&&p.max!==undefined?`${p.min*scale}…${p.max*scale}${p.suffix?' '+p.suffix:''}`:p.name)}/>;
}
@@ -0,0 +1,71 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Checker,Description,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {bytesBase64} from './editorFiles';
interface Frame {broker_status?:{mode:string;reads:number;pending:number;observed_at:string|null};blocked_codes?:number[];rendered:boolean;png?:string;width?:number;height?:number;observed_at:string;warnings?:string[];error?:string;discarded_commands?:number;qml_id?:string;standalone?:boolean}
type Input=Record<string,unknown>;
export function VescQmlPreview(props:ReadProps&{source:string;active?:boolean}){
const [frame,setFrame]=useState<Frame|null>(null),[busy,setBusy]=useState(false),[inputBusy,setInputBusy]=useState(false),[snapshot,setSnapshot]=useState(false),[broker,setBroker]=useState(false),[text,setText]=useState('');
const mounted=useRef(true),running=useRef(false),generation=useRef(0),session=useRef<string|null>(null),pointer=useRef<Input[]>([]);
const call=<T,>(action:string,parameters:Record<string,unknown>)=>perform<T>(props.transport,props.device,'vesc.qml.'+action,parameters,30000);
const canvas=useRef<HTMLImageElement>(null),queue=useRef<Input[]>([]);
const closer=useRef((id:string)=>{void call('close',{qml_id:id}).catch(()=>{});});closer.current=id=>{void call('close',{qml_id:id}).catch(()=>{});};
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;generation.current++;if(session.current)closer.current(session.current);session.current=null;};},[]);
useEffect(()=>{const old=session.current;session.current=null;if(old)closer.current(old);setFrame(null);generation.current++;pointer.current=[];queue.current=[];},[props.source,props.device.snapshot.context.session_id,props.active]);
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).qml_interactive_supported&&props.active!==false;
const inputDisabled=busy||props.blocked||!available;
const disabled=inputDisabled||inputBusy;
async function run(work:()=>Promise<Frame|null>){
if(running.current||disabled)return;
const revision=generation.current;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);
try{const value=await work();if(mounted.current&&revision===generation.current){setFrame(value);session.current=value?.qml_id??null;}else if(value?.qml_id)closer.current(value.qml_id);}
catch(e){if(mounted.current&&revision===generation.current){props.failure(e);const old=session.current;session.current=null;setFrame(null);if(old)closer.current(old);}}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
async function open(){await run(async()=>{
const data=new TextEncoder().encode(props.source);if(data.length>120*1024)throw new Error('QML принимает исходный код до 120 КБ.');
const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data))).map(v=>v.toString(16).padStart(2,'0')).join('');
const upload=await call<{upload_id:string;chunk_bytes:number}>('begin',{size:data.length,sha256});
if(upload.chunk_bytes!==16384)throw new Error('Неподдерживаемый размер фрагмента QML.');
for(let offset=0;offset<data.length;offset+=upload.chunk_bytes){if(!mounted.current)return null;await call('chunk',{upload_id:upload.upload_id,offset,data:bytesBase64(data.slice(offset,offset+upload.chunk_bytes))});}
return call<Frame>('open',{upload_id:upload.upload_id,snapshot:snapshot||broker,broker});
});}
function input(events:Input[]){
const id=session.current;if(!id||inputDisabled)return;
if(queue.current.length+events.length>128){props.failure(new Error('Очередь ввода QML заполнена. Дождитесь ответа приложения.'));return;}
queue.current.push(...events);if(running.current)return;
const revision=generation.current;running.current=true;setInputBusy(true);
void (async()=>{try{
do {const batch=queue.current.splice(0,32);const value=await call<Frame>('frame',{qml_id:id,events:batch});
if(!mounted.current||revision!==generation.current)return;setFrame(value);
}while(queue.current.length&&session.current===id);
}catch(e){if(mounted.current&&revision===generation.current){props.failure(e);session.current=null;queue.current=[];setFrame(null);closer.current(id);}}
finally{running.current=false;if(mounted.current)setInputBusy(false);}})();
}
useEffect(()=>{
const element=canvas.current;if(!element)return;
const wheel=(e:WheelEvent)=>{e.preventDefault();e.stopPropagation();if(inputDisabled)return;input([{kind:'wheel',...coordinates(element,e.clientX,e.clientY),delta:Math.max(-1200,Math.min(1200,Math.round(-e.deltaY)))}]);};
element.addEventListener('wheel',wheel,{passive:false});return()=>element.removeEventListener('wheel',wheel);
});
function coordinates(element:HTMLImageElement,x:number,y:number){const b=element.getBoundingClientRect();return {x:Math.max(0,Math.min(639,(x-b.left)/b.width*640)),y:Math.max(0,Math.min(479,(y-b.top)/b.height*480))};}
return <SettingsCard title="QML-интерфейс" description="Откройте интерфейс расширения и выберите источник данных. Чтение с контроллера выполняется при взаимодействии или обновлении кадра.">
<Checker label="Использовать снимок данных контроллера" checked={snapshot||broker} onChange={setSnapshot} disabled={disabled||!!session.current||broker}/>
<Checker label="Читать данные контроллера через брокер" checked={broker} disabled={disabled||!!session.current||!vescStatus(props.device).qml_broker_supported} onChange={setBroker}/>
<Description>{broker?'Доступны показания, параметры мотора и приложения, PPM, ADC, Nunchuk, IMU и BMS по USB. Не более двух чтений за кадр. Фонового опроса нет. Запись, CAN-переадресация, движение и запуск измерений заблокированы.':snapshot?'При открытии однократно читаются конфигурация и показания. Дальше приложение использует этот снимок.':'Интерфейс открывается без чтения данных контроллера. Показания и ответы оборудования отсутствуют.'} Сеанс завершается после минуты без взаимодействия или пяти минут работы.</Description>
<div className="sensor-actions"><Button disabled={disabled||!props.source.trim()} loading={busy} onClick={()=>void open()}>{session.current?'Открыть заново':'Открыть QML'}</Button><Button disabled={disabled||!session.current} onClick={()=>input([])}>Обновить кадр</Button><Button disabled={disabled||!session.current} onClick={()=>void run(async()=>{await call('close',{qml_id:session.current});return null;})}>Закрыть QML</Button></div>
{frame?.rendered&&frame.png&&<><img ref={canvas} src={`data:image/png;base64,${frame.png}`} width={frame.width} height={frame.height} style={{maxWidth:'100%',height:'auto',display:'block',touchAction:'none'}} tabIndex={0} draggable={false} aria-disabled={inputDisabled} aria-busy={inputBusy} alt="Интерактивный интерфейс QML. Нажатия и ввод работают внутри приложения."
onPointerDown={e=>{if(inputDisabled||e.button!==0)return;e.preventDefault();e.currentTarget.focus();e.currentTarget.setPointerCapture(e.pointerId);pointer.current=[{kind:'down',...coordinates(e.currentTarget,e.clientX,e.clientY)}];}}
onPointerMove={e=>{if(!pointer.current.length)return;const event={kind:'move',...coordinates(e.currentTarget,e.clientX,e.clientY)};if(pointer.current.length<30)pointer.current.push(event);else pointer.current[pointer.current.length-1]=event;}}
onPointerUp={e=>{if(!pointer.current.length)return;const events=[...pointer.current,{kind:'up',...coordinates(e.currentTarget,e.clientX,e.clientY)}];pointer.current=[];input(events);}}
onPointerCancel={()=>{pointer.current=[];}}
onKeyDown={e=>{if(inputDisabled)return;const keys=['Enter','Tab','Backspace','Delete','ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End','Escape'];if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='a'){e.preventDefault();e.stopPropagation();input([{kind:'key',key:'SelectAll'}]);}else if(keys.includes(e.key)){e.preventDefault();e.stopPropagation();input([{kind:'key',key:e.key}]);}else if(e.key.length===1&&!e.ctrlKey&&!e.metaKey){e.preventDefault();e.stopPropagation();input([{kind:'text',text:e.key}]);}}}/>
{!frame.standalone&&!frame.broker_status&&<Description>Снимок данных: {new Date(frame.observed_at).toLocaleString('ru-RU')}.</Description>}
{frame.broker_status&&<Description>Чтений: {frame.broker_status.reads} · В очереди: {frame.broker_status.pending}. {frame.broker_status.observed_at?`Последний ответ: ${new Date(frame.broker_status.observed_at).toLocaleString('ru-RU')}.`:'Приложение ещё не запросило данные.'}</Description>}
<TextField label="Текст для активного поля QML" value={text} disabled={disabled} onChange={e=>setText(e.target.value)} maxLength={1024}/><Button disabled={disabled||!text} onClick={()=>{input([{kind:'text',text}]);setText('');}}>Ввести текст</Button>
</>}
{!!frame?.discarded_commands&&<Description>Заблокировано запросов: {frame.discarded_commands}. {frame.blocked_codes?.length?`Коды: ${frame.blocked_codes.join(", ")}. `:""}Они не отправлялись. Запись настроек, запуск программ и управление выполняются в соответствующих разделах VESC.</Description>}
{!!frame?.warnings?.length&&<TextAreaField label="Сообщения Qt Quick" value={frame.warnings.join('\n')} rows={5} readOnly/>}
</SettingsCard>;
}
@@ -0,0 +1,44 @@
import {useEffect,useMemo,useState} from 'react';
import {Button,ComparisonTable,Description,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
import type {SampleRecord} from './sampleReview';
import {hallEventWindow,reviewRotorHall,type HallEvent} from './rotorHallReview';
const number=(n:number|null)=>n===null?'—':n.toLocaleString('ru-RU',{maximumFractionDigits:3});
export function VescRotorHallReview({records,from,to,onFocus}:{records:readonly (SampleRecord|null)[];from:number;to:number;onFocus:(window:{from:number;to:number;first:number;second:number})=>void}){
const [slot,setSlot]=useState('0'),[page,setPage]=useState(0),[details,setDetails]=useState(false);
const present=useMemo(()=>records.flatMap((record,i)=>record?[{record,slot:i,review:reviewRotorHall(record.points,from,to)}]:[]),[records,from,to]);
const selected=present.find(p=>p.slot===Number(slot))??present[0];
useEffect(()=>setPage(0),[records,from,to,slot]);
if(!selected)return null;
const {review,record}=selected,columns=present.map(p=>({id:String(p.slot),label:p.slot?'B':'A'}));
const focus=(event:HallEvent)=>onFocus(hallEventWindow(record.points,event));
const pages=Math.max(1,Math.ceil(review.events.length/10)),currentPage=Math.min(page,pages-1);
return <SettingsCard title="Ротор и код Hall · разбор выборки" description="Наблюдения по исходным отсчётам выбранного интервала. Фильтр токов не меняет этот разбор.">
<ComparisonTable density="compact" label="Ротор и Холлы" heading="Наблюдение" columns={columns} rows={[
{id:'count',label:'Отсчётов',cells:present.map(p=>p.review.count)},
{id:'states',label:'Коды 1–6',cells:present.map(p=>p.review.counts.slice(1,7).flatMap((n,i)=>n?[i+1]:[]).join(', ')||'Не наблюдались')},
{id:'reserved',label:'Отсчёты 0 / 7',cells:present.map(p=>`${p.review.counts[0]} / ${p.review.counts[7]}`)},
{id:'missing',label:'Нет кода Hall',cells:present.map(p=>p.review.missing)},
{id:'changes',label:'Смены кода',cells:present.map(p=>p.review.transitions)},
{id:'phase',label:'Отсчёты угла',cells:present.map(p=>p.review.phaseCount)},
{id:'phase-step',label:'Макс. шаг угла, °',cells:present.map(p=>number(p.review.phaseStep))},
{id:'current',label:'Макс. |ток|, А',cells:present.map(p=>number(p.review.peakCurrent))},
]}/>
<Description>На прошивке 5.02 это преобразованный код Hall, не уровни H1–H3. Разбор не определяет обрыв датчика или заклинивание. Пропуски и делитель частоты могут скрыть переходы; угол FOC не является измерением поворота вала.</Description>
{present.some(p=>p.record.complete!==true)&&<Description>Полнота записи не подтверждена; положение пропусков неизвестно.</Description>}
<Button variant="ghost" onClick={()=>setDetails(v=>!v)}>{details?'Скрыть подробности разбора':'Подробности разбора'}</Button>
{details&&<>
<Description>Это смены переданного кода между отсчётами. В штатной 5.02 он получен через таблицу коммутации BLDC; в FOC эта таблица может быть не инициализирована. Коды 0 и 7, изменение нескольких битов или постоянный код не доказывают неисправность. По этому полю нельзя посчитать переключения физических входов Холла.</Description>
<Description>На FOC прошивки 5.02 угол — электрическая фаза управления, с шагом около 1,44°. Он не подтверждает поворот вала; для других режимов смысл нужно сверять с прошивкой. Шаг угла — кратчайшая разность соседних отсчётов через 0°; движение более чем на 180° между ними не восстанавливается. Остановка или заклинивание по этой таблице не устанавливаются.</Description>
{present.some(p=>p.record.complete!==true)&&<Description>Полнота хотя бы одной записи не подтверждена. Положение потерь в буфере 5.02 неизвестно; время и соседство отсчётов нельзя считать непрерывной картиной события.</Description>}
</>}
{present.length>1&&<Select label="Подробности выборки" value={String(selected.slot)} onChange={setSlot} options={present.map(p=>({value:String(p.slot),label:p.slot?'B':'A'}))}/>}
{details&&<>
<ComparisonTable density="compact" label="Распределение кодов Hall" heading="Код" columns={[{id:'count',label:'Отсчётов'},{id:'span',label:'Макс. участок, мс'}]} rows={review.counts.map((n,i)=>({id:String(i),label:String(i),cells:[n,number(n?review.longest[i]:null)]}))}/>
<Description>Длина участка измеряется от первого до последнего соседнего отсчёта одного кода. Один отсчёт даёт 0 мс. Это не полное время пребывания ротора в секторе.</Description>
{!!review.halfTurns&&<Description>Найдено шагов ровно на 180°: {review.halfTurns}. Направление такого шага неоднозначно.</Description>}
</>}
<Description>{review.events.length?`Особенностей в интервале: ${review.events.length}. Выберите участок для графиков Холла, угла и тока.`:'В выбранном интервале перечисленные особенности не обнаружены. Это не проверка исправности датчиков или мотора.'}</Description>
{!!review.events.length&&<ResourceList aria-label="Участки для просмотра">{review.events.slice(currentPage*10,currentPage*10+10).map((event,i)=><li key={`${currentPage}-${i}`}><ResourceRow title={event.label} description={`${number(event.at)}–${number(event.end)} мс · отсчёты ${event.first+1}–${event.last+1} · макс. |ток| ${number(event.current)} А`} actions={<Button onClick={()=>focus(event)}>Показать участок</Button>}/></li>)}</ResourceList>}
{pages>1&&<div className="sensor-actions"><Button disabled={!currentPage} onClick={()=>setPage(currentPage-1)}>Предыдущие</Button><Description>{currentPage+1} / {pages}</Description><Button disabled={currentPage+1>=pages} onClick={()=>setPage(currentPage+1)}>Следующие</Button></div>}
</SettingsCard>;
}
@@ -0,0 +1,84 @@
import {useEffect,useMemo,useRef,useState} from 'react';
import {Button,ComparisonTable,Description,RangeControl,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {LOG_MAX_BYTES,spectrum} from './logAnalysis';
import {VescRotorHallReview} from './VescRotorHallReview';
import {sampleFields} from './samples';
import {SignalPlot} from './SignalPlot';
import {defaultSampleFilter,filterCoefficients,filteredSamplePoints,parseSampleRecord,sampleMeasurement,type SampleFilter,type SampleRecord} from './sampleReview';
const number=(value:number|null|undefined)=>value==null?'—':value.toLocaleString('ru-RU',{maximumFractionDigits:5});
const duration=(record:SampleRecord|null)=>record?.points.at(-1)?.at??0;
export function VescSampleAnalysis({live}:{live:SampleRecord|null}){
const [records,setRecords]=useState<[SampleRecord|null,SampleRecord|null]>([null,null]),[error,setError]=useState(''),[busy,setBusy]=useState(false);
const [signals,setSignals]=useState(['i1','hall']),[from,setFrom]=useState(0),[to,setTo]=useState(0),[cursor1,setCursor1]=useState(0),[cursor2,setCursor2]=useState(0);
const [filter,setFilter]=useState<SampleFilter>(defaultSampleFilter),[fft,setFft]=useState(false);
const inputs=useRef<(HTMLInputElement|null)[]>([]),revision=useRef(0),expiry=useRef<number[]>([0,0]),day=useRef(new Date().toISOString().slice(0,10));
const install=(record:SampleRecord,slot:number)=>{setRecords(old=>{const next:[SampleRecord|null,SampleRecord|null]=[...old];next[slot]=record;return next;});expiry.current[slot]=Date.now()+300000;setFrom(0);setFft(false);};
useEffect(()=>{if(live)install(live,0);},[live]);
useEffect(()=>{const timer=setInterval(()=>setRecords(old=>{const today=new Date().toISOString().slice(0,10),reset=today!==day.current;day.current=today;const next=old.map((r,i)=>r&&(reset||Date.now()>=expiry.current[i])?null:r) as typeof old;return next.some((r,i)=>r!==old[i])?next:old;}),1000);return()=>{clearInterval(timer);revision.current++;};},[]);
const end=Math.max(...records.map(duration));
useEffect(()=>{setFrom(0);setTo(end);setCursor1(0);setCursor2(end);},[end,records]);
async function open(file:File,slot:number){const request=++revision.current;setBusy(true);setError('');try{
if(file.size>LOG_MAX_BYTES)throw new Error('Максимальный размер файла — 4 МиБ.');
const record=parseSampleRecord(await file.text(),file.name);if(request===revision.current)install(record,slot);
}catch(e){if(request===revision.current)setError(e instanceof Error?e.message:'Не удалось прочитать выборку.');}finally{if(request===revision.current)setBusy(false);}}
const present=records.flatMap((r,i)=>r?[{record:r,slot:i}]:[]),coefficients=useMemo(()=>filterCoefficients(filter),[filter]);
const traces=useMemo(()=>records.map(r=>r?Object.fromEntries(signals.map(key=>[key,filteredSamplePoints(r.points,key,filter,coefficients)])):null),[records,signals,filter,coefficients]);
const fftResult=useMemo(()=>records.map((r,i)=>{if(!r||!fft)return null;if(r.complete===false)return {data:null,error:'FFT отключён: паспорт не подтверждает полный буфер.'};try{
const points=traces[i]![signals[0]].map(p=>({at:p.at,values:{[signals[0]]:p.value},gap:p.value===null}));
return {data:spectrum(points,signals[0],from,to),error:''};
}catch(e){return {data:null,error:e instanceof Error?e.message:'FFT недоступен.'};}}),[records,traces,signals,fft,from,to]);
const options=sampleFields.map(([value,label,unit])=>({value,label:(value==='i3'?'Ток фазы 3':label)+(unit?` · ${unit}`:'')}));
const setFilterValue=<K extends keyof SampleFilter>(key:K,value:SampleFilter[K])=>setFilter(old=>({...old,[key]:value}));
return <><SettingsCard title="Разбор осциллограмм" description="Откройте сохранённые выборки Sample Data или прочитайте полученный буфер. До двух файлов, общая относительная ось времени и измерения выбранного участка." actions={<StatusBadge>Локальный анализ</StatusBadge>}>
<div className="sensor-actions">{records.map((r,i)=><div key={i} className="sensor-actions"><input ref={el=>{inputs.current[i]=el;}} hidden type="file" accept=".json,.csv,application/json,text/csv" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void open(file,i);}}/><Button disabled={busy} onClick={()=>inputs.current[i]?.click()}>{r?'Заменить':'Открыть'} выборку {i?'B':'A'}</Button>{r&&<Button disabled={busy} onClick={()=>setRecords(old=>old.map((v,j)=>j===i?null:v) as typeof old)}>Закрыть {i?'B':'A'}</Button>}</div>)}</div>
{error&&<Description role="alert">{error}</Description>}
<Description>JSON с паспортом Mission Core или CSV Sample Data VESC Tool, до 4 МиБ и 2000 отсчётов на файл. Данные остаются в памяти этого окна не более пяти минут. Импорт ничего не запрашивает у контроллера.</Description>
{!!present.length&&<ComparisonTable density="compact" label="Паспорта выборок" heading="Выборка" columns={present.map(({slot})=>({id:String(slot),label:slot?'B':'A'}))} rows={[
{id:'file',label:'Источник',cells:present.map(({record:r})=>r.name)},
{id:'uuid',label:'UUID из паспорта',cells:present.map(({record:r})=>r.uuid??'Не указан')},
{id:'hardware',label:'Аппаратура / прошивка',cells:present.map(({record:r})=>`${r.hardware??'—'} / ${r.firmware??'—'}`)},
{id:'capture',label:'Захват',cells:present.map(({record:r})=>r.capture??'Не указан')},
{id:'session',label:'USB-сессия',cells:present.map(({record:r})=>r.session??'Не указана')},
{id:'state',label:'Полнота',cells:present.map(({record:r})=>r.status)},
{id:'size',label:'Отсчёты / длительность',cells:present.map(({record:r})=>`${r.points.length} / ${number(duration(r))} мс`)},
{id:'third',label:'Третий фазный ток',cells:present.map(({record:r})=>r.thirdMeasured===null?'Способ получения не указан':r.thirdMeasured?'Измеренный':'Расчётный')},
]}/>}
{!!present.length&&<Description>Паспорт взят из файла и не удостоверяет текущий подключённый VESC. Время — от начала каждого буфера; две записи не синхронизированы. У неполного буфера 5.02 положение потери неизвестно, поэтому его временная ось приблизительна.</Description>}
</SettingsCard>{!!present.length&&<>
<SettingsCard title="Сигналы и интервал" description="Выберите до четырёх сигналов. Графики A и B используют одинаковый интервал времени; шкала значений у каждого своя.">
{signals.map((key,i)=><Select key={i} label={`Сигнал ${i+1}`} value={key} options={options.filter(o=>o.value===key||!signals.includes(o.value))} onChange={value=>setSignals(old=>old.map((v,j)=>i===j?value:v))}/>)}
<div className="sensor-actions"><Button disabled={signals.length>=4} onClick={()=>{const next=options.find(o=>!signals.includes(o.value));if(next)setSignals(old=>[...old,next.value]);}}>Добавить сигнал</Button><Button disabled={signals.length<=1} onClick={()=>setSignals(old=>old.slice(0,-1))}>Убрать последний сигнал</Button></div>
<RangeControl label="Начало интервала, мс" min={0} max={end} step={.001} value={from} onChange={v=>{setFrom(Math.min(v,to));setCursor1(Math.max(cursor1,Math.min(v,to)));setCursor2(Math.max(cursor2,Math.min(v,to)));}}/>
<RangeControl label="Конец интервала, мс" min={0} max={end} step={.001} value={to} onChange={v=>{setTo(Math.max(v,from));setCursor1(Math.min(cursor1,Math.max(v,from)));setCursor2(Math.min(cursor2,Math.max(v,from)));}}/>
</SettingsCard>
<VescRotorHallReview records={records} from={from} to={to} onFocus={window=>{setSignals(['hall','phase_deg','current']);setFrom(window.from);setTo(window.to);setCursor1(window.first);setCursor2(window.second);setFft(false);}}/>
<SettingsCard title="Фильтр фазных токов" description="Фильтруются только I1, I2 и I3. Исходные отсчёты остаются неизменными; Холлы, угол и общий ток не сглаживаются.">
<Select label="Фильтр" value={filter.kind} options={[{value:'none',label:'Без фильтра'},{value:'fir',label:'FIR · VESC Tool'},{value:'mean',label:'Скользящее среднее'}]} onChange={v=>setFilterValue('kind',v as SampleFilter['kind'])}/>
{filter.kind!=='none'&&<><Select label="Количество коэффициентов" value={String(filter.bits)} options={Array.from({length:10},(_,i)=>({value:String(i+1),label:String(2**(i+1))}))} onChange={v=>setFilterValue('bits',+v)}/>
{filter.kind==='fir'&&<><RangeControl label="Частота среза / частота отсчётов" min={0} max={.5} step={.001} value={filter.cutoff} onChange={v=>setFilterValue('cutoff',v)}/><Select label="Окно Хэмминга" value={String(filter.hamming)} options={[{value:'true',label:'Включено'},{value:'false',label:'Выключено'}]} onChange={v=>setFilterValue('hamming',v==='true')}/></>}
<Select label="Компенсация задержки фильтра" value={String(filter.compensate)} options={[{value:'true',label:'Включена'},{value:'false',label:'Выключена'}]} onChange={v=>setFilterValue('compensate',v==='true')}/>
<Description>Коэффициенты и смещение соответствуют VESC Tool 7.00. Края без полного окна и неравномерные участки остаются пропусками. Если отсчётов недостаточно для фильтра, уменьшите его длину.</Description>
</>}
</SettingsCard>
<SettingsCard title="Курсоры измерения" description="Курсоры выбирают ближайший отсчёт без интерполяции. В таблицах указаны фактическое время, разность значений и интервал; за пределами записи и на пропусках значения отсутствуют.">
<RangeControl label="Курсор 1, мс" min={from} max={to} step={.001} value={cursor1} onChange={setCursor1}/><RangeControl label="Курсор 2, мс" min={from} max={to} step={.001} value={cursor2} onChange={setCursor2}/>
</SettingsCard>
{signals.map(key=>{const field=options.find(o=>o.value===key)!;const unit=sampleFields.find(f=>f[0]===key)![2];const measured=present.map(({slot})=>sampleMeasurement(traces[slot]![key],from,to,cursor1,cursor2));return <div className="sensor-content" key={key}>
{present.map(({slot})=><SignalPlot key={slot} title={`${slot?'B':'A'} · ${field.label}`} unit={unit} points={traces[slot]![key]} from={from} to={to} xUnit="мс" xScale={1} cursors={[cursor1,cursor2]} step={key==='hall'||key==='commutation'}/>)}
<SettingsCard title={`Измерения · ${field.label}`}><ComparisonTable density="compact" label={`Измерения ${field.label}`} heading="Параметр" columns={present.map(({slot})=>({id:String(slot),label:slot?'B':'A'}))} rows={[
{id:'count',label:'Отсчётов в интервале',cells:measured.map(m=>m.count)},
{id:'min',label:'Минимум',cells:measured.map(m=>number(m.min))},{id:'max',label:'Максимум',cells:measured.map(m=>number(m.max))},
...(['hall','commutation','phase_deg'].includes(key)?[]:[{id:'rms',label:'RMS',cells:measured.map(m=>number(m.rms))}]),
{id:'first',label:'Курсор 1 · мс / значение',cells:measured.map(m=>m.first?`${number(m.first.at)} / ${number(m.first.value)}`:'—')},
{id:'second',label:'Курсор 2 · мс / значение',cells:measured.map(m=>m.second?`${number(m.second.at)} / ${number(m.second.value)}`:'—')},
{id:'delta',label:'Δ значения (2 − 1)',cells:measured.map(m=>number(m.delta))},{id:'dt',label:'Δ времени, мс',cells:measured.map(m=>number(m.dt))},
]}/></SettingsCard>
</div>;})}
<SettingsCard title="FFT первого сигнала" description="Окно Ханна, среднее удаляется. Используются последние 32–1024 отсчёта интервала (степень двойки). Для фильтрованных токов выберите участок без краевых пропусков.">
<Button onClick={()=>setFft(v=>!v)}>{fft?'Скрыть FFT':'Показать FFT'}</Button>
{present.some(({record:r})=>r.complete===null)&&<Description>CSV не содержит подтверждения полноты. Его спектр — анализ представленных строк, а не доказательство отсутствия потерянных пакетов.</Description>}
{fft&&present.map(({slot})=>{const result=fftResult[slot];return <Description key={slot}>{slot?'B':'A'} · {result?.error||`${result?.data?.n} отсчётов · частота ${number(result?.data?.rate)} Гц · шаг ${number(result?.data?result.data.rate/result.data.n:null)} Гц · пик ${number(result?.data?.peak.hz)} Гц`}</Description>;})}
</SettingsCard>
{fftResult.map((r,i)=>r?.data?<SignalPlot key={i} title={`${i?'B':'A'} · Амплитудный спектр`} unit={sampleFields.find(f=>f[0]===signals[0])![2]} points={r.data.bins.map(p=>({at:p.hz,value:p.amplitude}))} from={0} to={r.data.rate/2} xUnit="Гц" xScale={1}/>:null)}
</>}</>;
}
@@ -0,0 +1,52 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {downloadText} from './editorFiles';
import {VescSampleAnalysis} from './VescSampleAnalysis';
import {liveSampleRecord,type SampleRecord} from './sampleReview';
import {samplePoints,sampleCsv,sampleStateLabel,type SampleState,type SampleRow} from './samples';
export function VescSampleData(props:ReadProps){
const [state,setState]=useState<SampleState|null>(null),[rows,setRows]=useState<SampleRow[]>([]),[busy,setBusy]=useState(false);
const [mode,setMode]=useState('1'),[count,setCount]=useState('600'),[decimation,setDecimation]=useState('1'),[timeout,setTimeoutValue]=useState('30');
const [live,setLive]=useState<SampleRecord|null>(null),[passport,setPassport]=useState('');
const generation=useRef(0),running=useRef(false),mounted=useRef(true),expires=useRef(0);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;generation.current++;};},[]);
useEffect(()=>{generation.current++;setState(null);setRows([]);setPassport('');setLive(null);},[props.device.snapshot.context.session_id]);
useEffect(()=>{const timer=setInterval(()=>{if(expires.current&&Date.now()>=expires.current){setRows([]);setState(null);setPassport('');setLive(null);expires.current=0;}},1000);return()=>clearInterval(timer);},[]);
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).sample_data_supported;
const disabled=busy||props.blocked||!available,active=state&&['armed','stored_wait','receiving'].includes(state.state);
const call=(action:string,p:Record<string,unknown>={})=>perform<SampleState>(props.transport,props.device,'vesc.samples.'+action,p,30000);
async function run(action:string,p:Record<string,unknown>={}){
if(disabled||running.current)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);const revision=generation.current;
try{
const value=await call(action,p);if(!mounted.current||revision!==generation.current)return;
setState(value);expires.current=Date.now()+Math.max(0,300000-(value.elapsed_ms??0));
if(action==='start'||action==='fetch'){setRows([]);setLive(null);setPassport('');}
if(action==='read'){
const all=[...(value.rows??[])];while(all.length<value.received){
if(!mounted.current||revision!==generation.current)return;
const page=await call('read',{capture_id:value.capture_id,offset:all.length});
if(page.capture_id!==value.capture_id||page.offset!==all.length||!page.rows?.length||page.received!==value.received)throw new Error('Буфер изменился. Прочитайте его заново.');
all.push(...page.rows);if(all.length>2000)throw new Error('Размер буфера превышен.');
}
samplePoints(all);if(mounted.current&&revision===generation.current){setRows(all);setLive(liveSampleRecord('Буфер контроллера',all,value,vescStatus(props.device).identity,props.device.snapshot.context.session_id));setPassport(JSON.stringify({schema:'missioncore.vesc.sample-data/v1',identity:vescStatus(props.device).identity,session:props.device.snapshot.context.session_id,state:value,rows:all},null,2));}
}
}catch(e){if(mounted.current&&revision===generation.current)props.failure(e);}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
const valid=Number.isInteger(+count)&&+count>=1&&+count<=2000&&Number.isInteger(+decimation)&&+decimation>=1&&+decimation<=255&&Number.isInteger(+timeout)&&+timeout>=2&&+timeout<=120;
return <div className="sensor-content"><SettingsCard title="Sample Data · осциллограмма" description="Штатная быстрая выборка фазных токов, напряжений, угла и состояний Холла. Захват не запускает мотор и не меняет его настройки." actions={<StatusBadge>{sampleStateLabel[state?.state??'idle']??state?.state}</StatusBadge>}>
<Select label="Режим захвата" value={mode} disabled={disabled||!!active} onChange={setMode} options={[['1','Сейчас'],['2','При запуске мотора'],['3','Триггер: запуск мотора'],['4','Триггер: ошибка контроллера'],['5','Запуск: сохранить в контроллере'],['6','Ошибка: сохранить в контроллере'],['7','Последний буфер контроллера']].map(([value,label])=>({value,label}))}/>
<div className="sensor-actions"><TextField label={+mode>=3&&+mode<=6?'Отсчётов до события':'Количество отсчётов'} type="number" min={1} max={2000} value={count} disabled={disabled||!!active||mode==='7'} onChange={e=>setCount(e.target.value)}/><TextField label="Делитель частоты" type="number" min={1} max={255} value={decimation} disabled={disabled||!!active} onChange={e=>setDecimation(e.target.value)}/><TextField label="Ожидание, с" type="number" min={2} max={120} value={timeout} disabled={disabled||!!active} onChange={e=>setTimeoutValue(e.target.value)}/></div>
<Description>Прошивка 5.02: до 2000 отсчётов; триггер возвращает весь буфер. Третий фазный ток вычисляется из первых двух. Сырые ADC и повтор отдельных пакетов недоступны. Время рассчитано по частоте в пакетах и указанному делителю.</Description>
{mode==='7'&&<Description>Укажите делитель, с которым был записан последний буфер. Контроллер не сообщает его возраст, UUID события и применённый делитель; принадлежность буфера новому событию не подтверждается.</Description>}
<div className="sensor-actions"><Button disabled={disabled||!!active||!valid} loading={busy} onClick={()=>void run('start',{mode:+mode,count:+count,decimation:+decimation,timeout_s:+timeout,raw:false})}>{mode==='7'?'Запросить последний буфер':'Начать захват'}</Button><Button disabled={disabled} onClick={()=>void run('status')}>Обновить состояние</Button><Button disabled={disabled||!active} onClick={()=>void run('stop',{capture_id:state!.capture_id})}>Остановить захват</Button>{state?.state==='stored_wait'&&<Button disabled={disabled} onClick={()=>void run('fetch',{capture_id:state.capture_id})}>Запросить сохранённый буфер</Button>}</div>
<Description>Захват включается только этой кнопкой. Максимальное ожидание — 120 секунд. Данные хранятся в памяти до пяти минут; экспорт выполняется отдельно. Триггер ошибки срабатывает на ошибку VESC: подзаедание без ошибки само по себе его не включает.</Description>
{state&&<Description>{state.received} / {state.expected||'неизвестно'} отсчётов. {state.error??''}{state.state==='incomplete'?' Выборка неполная: разрыв нельзя точно расположить во времени, FFT отключён.':''}</Description>}
<Button disabled={disabled||!!active||!state?.received||state.state==='expired'} onClick={()=>void run('read',{capture_id:state!.capture_id,offset:0})}>Показать полученную выборку</Button>
</SettingsCard>{!!rows.length&&<SettingsCard title="Экспорт полученной выборки" description="CSV для VESC Tool или JSON с UUID, USB-сессией и состоянием буфера.">
<div className="sensor-actions"><Button onClick={()=>downloadText('vesc-sample-data.csv',sampleCsv(rows),'text/csv')}>Скачать CSV</Button><Button onClick={()=>downloadText('vesc-sample-data.json',passport,'application/json')}>Скачать с паспортом выборки</Button></div>
</SettingsCard>}<VescSampleAnalysis live={live}/></div>;
}
+45
View File
@@ -0,0 +1,45 @@
import {Description} from '@nodedc/ui-react';
import {useState} from 'react';
import {Button,ResourceList,ResourceRow,Select,SettingsCard} from '@nodedc/ui-react';
import {useVescRead,type ReadProps} from './useVescRead';
import {vescStatus} from './model';
const tools=[{value:'adc',label:'Аналоговые входы ADC'},{value:'chuk',label:'Вход Nunchuk'},{value:'imu',label:'Инерциальный модуль IMU'}];
const fieldLabels:Record<string,string>={level_1:'ADC 1 · уровень',voltage_1_v:'ADC 1 · напряжение, В',level_2:'ADC 2 · уровень',voltage_2_v:'ADC 2 · напряжение, В',level:'Уровень входа',roll:'Крен, рад',pitch:'Тангаж, рад',yaw:'Курс, рад',accX:'Ускорение X, g',accY:'Ускорение Y, g',accZ:'Ускорение Z, g',gyroX:'Гироскоп X, °/с',gyroY:'Гироскоп Y, °/с',gyroZ:'Гироскоп Z, °/с',magX:'Магнитометр X',magY:'Магнитометр Y',magZ:'Магнитометр Z',q0:'Кватернион W',q1:'Кватернион X',q2:'Кватернион Y',q3:'Кватернион Z',vesc_id:'CAN ID',v_tot:'Напряжение батареи, В',v_charge:'Напряжение зарядки, В',i_in:'Ток батареи, А',i_in_ic:'Ток измерителя, А',ah_cnt:'Счётчик заряда, А·ч',ah_cnt_chg_total:'Всего заряжено, А·ч',ah_cnt_dis_total:'Всего разряжено, А·ч',wh_cnt_chg_total:'Энергия заряда всего, Вт·ч',wh_cnt_dis_total:'Энергия разряда всего, Вт·ч',wh_cnt:'Счётчик энергии, Вт·ч',temp_ic:'Температура измерителя, °C',humidity:'Влажность, %',pressure:'Давление, Па',temp_hum_sensor:'Температура датчика влажности, °C',temp_cells_highest:'Максимальная температура ячеек, °C',soc:'Доля заряда',soh:'Доля остаточной ёмкости',can_id:'CAN ID',data_version:'Версия данных BMS',status:'Статус BMS',v_cells:'Напряжения ячеек, В',temps:'Температуры, °C',is_balancing:'Балансировка ячеек'};
interface ToolRead {tool:string;state:'received'|'unsupported'|'no_response';observed_at:string;values:Record<string,unknown>}
function display(value:unknown):string {
if(Array.isArray(value))return value.length?value.map((v,i)=>`${i+1}: ${display(v)}`).join(' · '):'Не сообщается';
if(typeof value==='number')return value.toLocaleString('ru-RU',{maximumFractionDigits:5});
if(typeof value==='boolean')return value?'Да':'Нет';
return value===null||value===''?'Не сообщается':String(value);
}
function ToolValues(props:ReadProps&{tool:string}){
const read=useVescRead<ToolRead>(props,'vesc.tools.read',vescStatus(props.device).tools_read_supported===true);
return <SettingsCard title={tools.find(v=>v.value===props.tool)?.label} description="Снимок данных, декодированный ядром VESC Tool. Поддержка команды прошивкой не означает, что соответствующий модуль физически установлен."
actions={<Button disabled={!read.available||props.blocked||read.busy} loading={read.busy} onClick={()=>void read.read({tool:props.tool})}>Прочитать</Button>}>
<div className="sensor-content">
{!read.value?<Description>Данные ещё не прочитаны.</Description>:read.value.state==='unsupported'?<Description>Эта команда не поддерживается текущей прошивкой.</Description>:read.value.state==='no_response'?<Description>Ответ не получен. Проверьте наличие и подключение модуля.</Description>:<>
<Description>Прочитано {new Date(read.value.observed_at).toLocaleString('ru-RU')}. Нулевые значения сами по себе не подтверждают наличие или исправность датчика.</Description>
<ResourceList aria-label="Данные периферии VESC">{Object.entries(read.value.values).filter(([key])=>key!=='mask').map(([key,value])=><li key={key}><ResourceRow title={fieldLabels[key]??key} description={display(value)}/></li>)}</ResourceList>
</>}
</div>
</SettingsCard>;
}
export function VescTools(props:ReadProps){
const [tool,setTool]=useState('adc');
return <div className="sensor-content"><Select label="Периферия" value={tool} options={tools} onChange={setTool} disabled={props.blocked}/><ToolValues key={tool} {...props} tool={tool}/></div>;
}
const commands=[['hw_status','Аппаратные сведения'],['faults','История ошибок'],['fault','Текущая ошибка'],['ping','Проверка ответа'],['mem','Память'],['threads','Потоки прошивки'],['rpm','Электрические обороты'],['tacho','Счётчик оборотов'],['volt','Напряжение'],['uptime','Время работы'],['help','Справка прошивки']].map(([value,label])=>({value,label:`${label} · ${value}`}));
function TerminalResult(props:ReadProps&{command:string}){
const read=useVescRead<{text:string;observed_at:string}>(props,'vesc.terminal.read',vescStatus(props.device).terminal_read_supported===true);
return <SettingsCard title="Ответ терминала" description="Диагностические команды читают состояние прошивки. Команды, которые вращают мотор или изменяют устройство, здесь не выполняются."
actions={<Button disabled={!read.available||props.blocked||read.busy} loading={read.busy} onClick={()=>void read.read({command:props.command})}>Выполнить чтение</Button>}>
<div className="sensor-content">
{read.value?<><Description>Прочитано {new Date(read.value.observed_at).toLocaleString('ru-RU')}.</Description><pre className="vesc-diagnostic-output">{read.value.text}</pre></>:<Description>Выберите команду и запросите ответ.</Description>}
</div>
</SettingsCard>;
}
export function VescTerminal(props:ReadProps){
const [command,setCommand]=useState('hw_status');
return <div className="sensor-content"><Select label="Команда диагностики" value={command} options={commands} onChange={setCommand} disabled={props.blocked}/><TerminalResult key={command} {...props} command={command}/></div>;
}
+62
View File
@@ -0,0 +1,62 @@
import {Description} from '@nodedc/ui-react';
import {useEffect,useRef,useState} from 'react';
import {Button,Icon,IconButton,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {vescStatus} from './model';
import {metrics,traceCsv,traceView,VescTrace,type Metric} from './trends';
import {TraceObserver} from './traceObserver';
const number=(n:number|null)=>n===null?'Нет данных':n.toLocaleString(undefined,{maximumFractionDigits:3});
export function VescTrends({device,transport,enabled,active}:SensorDetailProps&{active:boolean}){
const identity=vescStatus(device).identity;
const trace=useRef(new VescTrace());const [now,setNow]=useState(()=>performance.now());
const [paused,setPaused]=useState(false),[expanded,setExpanded]=useState(false);
const [metric,setMetric]=useState<Metric>('input_voltage_v'),[windowSeconds,setWindow]=useState('60');
const uuid=identity?.uuid??'';
useEffect(()=>{
if(!active||paused||!enabled||!transport.liveTelemetry||!uuid){
trace.current.gap(performance.now());
const timer=setInterval(()=>{const at=performance.now();trace.current.prune(at);setNow(at);},1000);
return()=>clearInterval(timer);
}
const observer=new TraceObserver(transport.liveTelemetry,(frame,at,rtt)=>{
if(frame)trace.current.accept(frame,device.id,uuid,at,rtt);else trace.current.gap(at);setNow(at);
},at=>{trace.current.prune(at);if(at>=trace.current.freshUntil)trace.current.gap(at);setNow(at);});
return()=>observer.close();
},[active,paused,enabled,transport,device.id,uuid]);
// Paused/background views retain only bounded RAM and expire on their next view.
useEffect(()=>{if(active){const at=performance.now();trace.current.prune(at);setNow(at);}},[active]);
const point=trace.current.points.at(-1);
const end=paused?(point?.at??now):now;
const plotHeight=expanded?384:180;
const view=traceView(trace.current.points,metric,end-Number(windowSeconds)*1000,end,plotHeight);
const fresh=active&&!paused&&enabled&&now<trace.current.freshUntil;
const selected=metrics.find(([key])=>key===metric)!;
const state=!transport.liveTelemetry?'Просмотр недоступен':paused?'Сбор приостановлен':fresh?'Живые данные':'Нет свежих данных';
function download(){
if(!identity||!trace.current.points.some(p=>p.values))return;
const url=URL.createObjectURL(new Blob([traceCsv(trace.current.points,identity)],{type:'text/csv;charset=utf-8'}));
const a=document.createElement('a');a.href=url;a.download=`vesc-${uuid.replace(/[^a-fA-F0-9]/g,'').slice(0,24)}-${new Date().toISOString().replaceAll(':','-')}.csv`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
return <div className="sensor-content"><SettingsCard title="Графики показаний" description="Показания приходят из живой телеметрии. Пауза останавливает только сбор графика."
actions={<StatusBadge tone={fresh?'success':'neutral'}>{state}</StatusBadge>}>
<div className="sensor-actions">
<Select label="Величина VESC" value={metric} options={metrics.map(([value,label,unit])=>({value,label:label+(unit?` · ${unit}`:'')}))} onChange={setMetric}/>
<Select label="Интервал графика" value={windowSeconds} options={['10','30','60','300'].map(value=>({value,label:value==='300'?'5 минут':`${value} секунд`}))} onChange={setWindow}/>
<Button disabled={!transport.liveTelemetry} onClick={()=>{trace.current.gap(performance.now());setPaused(v=>!v);}}> {paused?'Продолжить сбор':'Пауза сбора'}</Button>
</div>
<div className="vesc-trend-toolbar nodedc-viewport-controls"><IconButton label={expanded?'Свернуть график':'Развернуть график'} onClick={()=>setExpanded(v=>!v)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>
<svg className={`vesc-trend-plot${expanded?' vesc-trend-plot--expanded':''}`} viewBox={`0 0 800 ${plotHeight+56}`} role="img" aria-label={`${selected[1]}, ${selected[2]}. ${view.count} измерений. Минимум ${number(view.min)}, максимум ${number(view.max)}. Разрывы означают отсутствие данных.`}>
{[0,.5,1].map(f=><g key={f}><line className="vesc-trend-grid" x1="64" x2="780" y1={20+f*plotHeight} y2={20+f*plotHeight}/><text x="56" y={24+f*plotHeight} textAnchor="end">{number(view.high-f*(view.high-view.low))}</text></g>)}
{view.segments.map((line,i)=>line.length===1?<circle key={i} className="vesc-trend-point" cx={line[0].x} cy={line[0].y} r="2"/>:<polyline key={i} className="vesc-trend-line" points={line.map(p=>`${p.x},${p.y}`).join(' ')}/>)}
<text x="64" y={plotHeight+47}>−{windowSeconds} с</text><text x="780" y={plotHeight+47} textAnchor="end">{paused?'Пауза':'Сейчас'}</text>
</svg>
{!view.count&&<Description role="status">В выбранном интервале нет измерений этой величины. Отсутствующие значения не заменяются нулями.</Description>}
<ResourceList aria-label="Статистика графика"><li><ResourceRow title={selected[1]} description={`${fresh&&point?.values?.[metric]!==undefined?'Текущее':'Последнее в интервале'}: ${number(view.last)} ${selected[2]}`}/></li>
<li><ResourceRow title="Выбранный интервал" description={`Минимум: ${number(view.min)} · максимум: ${number(view.max)} · среднее по измерениям: ${number(view.mean)} ${selected[2]} · ${view.count} измерений`}/></li></ResourceList>
<Description>Пропуски связи и смена USB-сеанса разделяют линию. Показаны полученные значения контроллера; отключённый температурный датчик может возвращать недостоверную температуру. Мощность питания рассчитана как напряжение × ток, PWM показан в процентах.</Description>
</SettingsCard><SettingsCard title="Выгрузка измерений" description="В памяти окна хранятся последние 5 минут, не более 1200 записей. После закрытия окна или переподключения контроллера сбор начинается заново. Данные автоматически истекают через 5 минут. CSV сохраняется только по вашей команде."
actions={<><Button disabled={!trace.current.points.some(p=>p.values)} onClick={download}>Скачать CSV</Button><Button disabled={!trace.current.points.length} onClick={()=>{trace.current.clear();setNow(performance.now());}}>Очистить график</Button></>}>
<Description>CSV содержит все доступные величины, UUID, время измерения на борту, USB-сеанс и отдельные строки разрывов. Частота отображения — до 2 Гц; короткие события между полученными измерениями могут не попасть в график.</Description>
</SettingsCard></div>;
}
+22
View File
@@ -0,0 +1,22 @@
export interface BmsTarget {can_id:number;uuid:string;hardware:string;major:number;minor:number;custom_configs?:number;hardware_type:number;test_firmware:number}
export interface BmsReading {state:string;observed_at:string;target?:BmsTarget;commands_supported?:boolean;source?:string;values?:Record<string,unknown>}
export interface BmsPreview {preview_id:string;expires_in_s:number;target:BmsTarget;command:string}
export const bmsCommands=[{value:'charge_enable',label:'Разрешить зарядку'},{value:'charge_disable',label:'Запретить зарядку'},
{value:'balance_enable',label:'Разрешить балансировку'},{value:'balance_disable',label:'Остановить балансировку'},
{value:'reset_ah',label:'Сбросить счётчик А·ч'},{value:'reset_wh',label:'Сбросить счётчик Вт·ч'},{value:'zero_current',label:'Калибровать ноль тока'}];
export function bmsNumber(v:unknown,digits=3,scale=1):string {
return typeof v==='number'&&Number.isFinite(v)?(v*scale).toLocaleString('ru-RU',{maximumFractionDigits:digits}):'Не сообщается';
}
export function bmsCells(values:Record<string,unknown>){
const cells=Array.isArray(values.v_cells)?values.v_cells.slice(0,96):[];
const balancing=Array.isArray(values.is_balancing)?values.is_balancing:[];
return cells.map((v,index)=>({index,voltage:typeof v==='number'&&Number.isFinite(v)?v:null,
balancing:typeof balancing[index]==='boolean'?balancing[index]:null}));
}
export function bmsCellSummary(values:Record<string,unknown>){
const cells=bmsCells(values),valid=cells.map(v=>v.voltage).filter((v):v is number=>v!==null);
if(!cells.length||valid.length!==cells.length)return null;
const min=Math.min(...valid),max=Math.max(...valid);return {min,max,spreadMv:(max-min)*1000};
}
export function bmsTemperature(v:unknown){return typeof v==='number'&&v>-280?bmsNumber(v,1)+' °C':'Не сообщается';}
export function bmsCanOptions(ids:unknown){return Array.isArray(ids)?Array.from(new Set(ids.filter((n):n is number=>Number.isInteger(n)&&n>=0&&n<=253))).sort((a,b)=>a-b).map(n=>({value:String(n),label:`CAN ${n}`})):[];}
@@ -0,0 +1,34 @@
export interface VescParameter {
name:string;title:string;description:string;suffix:string;transmittable:boolean;
editor_scale:number;type:'number'|'integer'|'bitfield'|'enum'|'boolean'|'string'|'undefined';
value:number|string|boolean;min?:number;max?:number;step?:number;decimals?:number;options?:string[];max_length?:number;
}
export interface VescConfig {
parameters:VescParameter[];groups:{name:string;subgroups:{name:string;parameters:string[]}[]}[];
xml:string;packet_sha256:string;signature:number;
}
export interface ConfigurationRead {observed_at:string;configuration:{motor:VescConfig;application:VescConfig}}
const names:Record<string,string>={general:'Общие',bldc:'BLDC',dc:'DC',foc:'FOC',pid:'Регуляторы PID',
'pid controllers':'Регуляторы PID','additional info':'Дополнительные сведения',current:'Ток',voltage:'Напряжение',rpm:'Обороты',wattage:'Мощность',temperature:'Температура',advanced:'Дополнительные',sensorless:'Без датчиков',sensors:'Датчики','hall sensors':'Датчики Холла',encoder:'Энкодер',hfi:'HFI',setup:'Установка',quality:'Качество',mapping:'Сопоставление входов','throttle curve':'Кривая газа','vesc remote':'VESC Remote',balance:'Балансировка',tune:'Регулировка',startup:'Запуск',tiltback:'Наклон',fault:'Ошибки','multi esc':'Несколько контроллеров',bms:'BMS',
additional_info:'Дополнительные сведения',ppm:'PPM',adc:'ADC',uart:'UART',nunchuk:'VESC Remote',nrf:'NRF',
pas:'PAS',imu:'IMU',gpd:'GPDrive',experiments:'Эксперименты'};
export function groupLabel(name:string){return names[name.toLowerCase()]??name;}
export function parameterValue(parameter:VescParameter):string{
const value=parameter.value;
if(parameter.type==='enum')return parameter.options?.[Number(value)]??String(value);
if(typeof value==='boolean')return value?'Включено':'Выключено';
if(typeof value==='number'){
const scale=Number.isFinite(parameter.editor_scale)&&parameter.editor_scale!==0?parameter.editor_scale:1;
return (value*scale).toLocaleString('ru-RU',{maximumFractionDigits:Math.min(12,Math.max(0,parameter.decimals??6))})+(parameter.suffix?' '+parameter.suffix:'');
}
return String(value);
}
export function groupedParameters(config:VescConfig,group:string,query:string,subgroup='all'){
const search=query.trim().toLocaleLowerCase();
if(search)return config.parameters.filter(p=>`${p.name} ${p.title}`.toLocaleLowerCase().includes(search));
if(group==='all')return config.parameters;
const selected=config.groups.find(item=>item.name===group);
const order=selected?.subgroups.filter(item=>subgroup==='all'||item.name===subgroup).flatMap(item=>item.parameters)??[];
const byName=new Map(config.parameters.map(parameter=>[parameter.name,parameter]));
return [...new Set(order)].flatMap(name=>{const parameter=byName.get(name);return parameter?[parameter]:[];});
}
@@ -0,0 +1,4 @@
// Configuration travels on the paced management lane. Its bounded request
// budget includes delivery, native read/write and verified result delivery.
// This does not renew a drive lease or retry an unconfirmed flash write.
export const CONFIGURATION_OPERATION_TIMEOUT_MS=180000;
@@ -0,0 +1,29 @@
import type {DriveProfile} from './model';
export type UsbRoute={kind:'usb';uuid:string};
export type CanRoute={kind:'can';uuid:string;adapter_id:string;channel:number;can_id:number;bitrate:number};
export type ControlRoute=UsbRoute|CanRoute;
export interface ControlTransportProfile {schema:'missioncore.vesc.control-transport/v1';revision:number;routes:Record<string,ControlRoute>}
export interface ControlEndpoint {device_id:string;uuid:string;route:ControlRoute;verified:boolean;session_id:string}
export interface ControlAdapter {id:string;label:string;online:boolean}
export const controlBitrates=[125000,250000,500000,1000000];
export function transportMode(routes:Record<string,ControlRoute>):'usb'|'can'|'mixed'{
const kinds=new Set(Object.values(routes).map(r=>r.kind));
return kinds.size===1?(kinds.has('can')?'can':'usb'):'mixed';
}
export function routeError(routes:Record<string,ControlRoute>,drive:DriveProfile):string|null{
const ids=Object.values(drive.bindings).map(b=>b.device_id);
if(!ids.length||ids.length!==Object.keys(routes).length)return 'Назначьте все моторы привода.';
const addresses=new Set<string>(),speeds=new Map<string,number>();
for(const b of Object.values(drive.bindings)){
const r=routes[b.device_id];
if(!r||r.uuid!==b.uuid)return 'Назначение мотора изменилось. Обновите настройки.';
if(r.kind==='can'){
if(!/^usbcan_[a-f0-9]{32}$/.test(r.adapter_id)||![0,1].includes(r.channel)||!Number.isInteger(r.can_id)||r.can_id<0||r.can_id>254||!controlBitrates.includes(r.bitrate))return 'Укажите адаптер, канал, CAN ID от 0 до 254 и скорость.';
const bus=`${r.adapter_id}:${r.channel}`,address=`${bus}:${r.can_id}`;
if(addresses.has(address))return 'Один CAN-адрес назначен нескольким моторам.';
if(speeds.has(bus)&&speeds.get(bus)!==r.bitrate)return 'На одном CAN-канале нужна одинаковая скорость.';
addresses.add(address);speeds.set(bus,r.bitrate);
}
}
return null;
}
@@ -0,0 +1,61 @@
/** 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')};
}
+21
View File
@@ -0,0 +1,21 @@
export function plainDescription(value:string){
const doc=new DOMParser().parseFromString(value,'text/html');doc.querySelectorAll('script,style,img,iframe').forEach(n=>n.remove());doc.querySelectorAll('br,p,li').forEach(n=>n.append(' '));return doc.body.textContent?.replace(/\s+/g,' ').trim()??'';
}
export function downloadText(name:string,text:string,type='text/plain'){
const url=URL.createObjectURL(new Blob([text],{type})),link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
export interface CodeProject {kind:'lisp'|'qml';source:string;imports:Record<string,string>;fullscreen:boolean}
export function validateProject(value:unknown,kind:'lisp'|'qml'):CodeProject{
if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Не удалось прочитать проект.');
const p=value as CodeProject;
if(p.kind!==kind||typeof p.source!=='string'||typeof p.fullscreen!=='boolean'||!p.imports||typeof p.imports!=='object'||Array.isArray(p.imports))throw new Error('Тип или содержимое проекта не подходит.');
if(new TextEncoder().encode(p.source).length>120*1024||p.source.includes('\0')||Object.keys(p.imports).length>32)throw new Error('Проект превышает ограничения VESC.');
let total=new TextEncoder().encode(p.source).length;
for(const [name,bytes] of Object.entries(p.imports)){
if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/.test(name)||typeof bytes!=='string'||bytes.length>164000)throw new Error('Недопустимое вложение проекта.');
let raw:string;try{raw=atob(bytes);}catch{throw new Error('Повреждено вложение проекта.');}if(btoa(raw)!==bytes)throw new Error('Некорректное кодирование вложения.');total+=raw.length;
}
if(total>120*1024||(kind==='qml'&&Object.keys(p.imports).length))throw new Error('Вложения превышают ограничения выбранного формата.');
return {kind,source:p.source,imports:{...p.imports},fullscreen:p.fullscreen};
}
export function bytesBase64(bytes:Uint8Array){let s='';for(const byte of bytes)s+=String.fromCharCode(byte);return btoa(s);}
@@ -0,0 +1,18 @@
export interface FirmwareImage {name:string;kind:string;bytes:number;sha256:string;hardware:string;target_version:string;source_bytes?:number;source_sha256?:string;format?:string;base_address?:number;hardware_limits?:boolean;swd?:SwdTarget;can_id?:number}
export interface FirmwarePreview {transfer_id:string;expires_in_s:number;image:FirmwareImage;identity:{uuid:string}}
export interface FirmwareCatalog {repository:string;commit:string;items:{id:string;name:string;version:string;hardware_limits:boolean;bytes:number}[]}
export function firmwareFileError(file:{name:string;size:number},kind:string,formats:readonly string[]):string|null {
const format=file.name.split('.').at(-1)?.toLowerCase();
if(!format||!formats.includes(format))return 'Выберите поддерживаемый файл BIN или Intel HEX.';
const limit=format==='hex'?8*1024*1024:kind==='bootloader'?65536:2*1024*1024;
return file.size<(format==='hex'?32:256)||file.size>limit?'Размер файла выходит за допустимые пределы: BIN до 2 МиБ, загрузчик BIN до 64 КиБ, HEX до 8 МиБ.':null;
}
export const firmwareVariant=(image:FirmwareCatalog['items'][number])=>`${image.version} · ${image.hardware_limits?'Стандартные аппаратные пределы':'Без аппаратных пределов'} · ${image.name}`;
export interface CanFirmwareTarget {can_id:number;uuid:string;hardware:string;major:number;minor:number;hardware_type:number;test_firmware:number;custom_configs:number}
export interface SwdTarget {target_code:number;pins:string;address:number;flash_bytes:number}
export const swdTargets=[
[1,'STM32F40x'],[2,'NRF51822 · 128K / 16K'],[3,'NRF51822 · 256K / 16K'],[4,'NRF51822 · 256K / 32K'],
[5,'NRF52832 · 256K / 32K'],[6,'NRF52832 · 256K / 64K'],[7,'NRF52832 · 512K / 64K'],[8,'NRF52840 · 1M / 256K'],
[9,'STM32F30x'],[10,'STM32L47x'],[11,'STM32G43'],[12,'STM32G47'],[13,'STM32G49']
].map(([value,label])=>({value:String(value),label:String(label)}));
+18
View File
@@ -0,0 +1,18 @@
import type {ConfigurationRead} from './configuration';
import {parameterValue} from './configuration';
/** FW 5.02 Sample Data calls mcpwm_read_hall_phase(), a lookup-table output.
* Its three bits are NOT H1/H2/H3. Never infer connection or input edges from it.
* Configuration is saved intent, not a physical sensor-presence detector.
*/
export function hallConfiguration(value:ConfigurationRead|null){
const parameters=value?.configuration.motor.parameters??[];
const get=(name:string)=>parameters.find(p=>p.name===name);
const label=(name:string)=>{const p=get(name);return p?parameterValue(p):'Не прочитано';};
const motor=get('motor_type'),port=get('m_sensor_port_mode'),mode=get('foc_sensor_mode');
const usesHall=motor?.value===2&&port?.value===0&&mode?.value===2;
return {motor:label('motor_type'),port:label('m_sensor_port_mode'),mode:label('foc_sensor_mode'),
use:!motor||!port||!mode?'Не прочитано':motor.value!==2?'См. параметры выбранного типа мотора':usesHall?'Холлы выбраны в настройках FOC':'Холлы не выбраны в настройках FOC',
// No supported raw-input transport is admitted. Null is not a logical zero.
inputs:[null,null,null] as readonly null[],transitions:[null,null,null] as readonly null[]};
}
+123
View File
@@ -0,0 +1,123 @@
/** 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<string,number|null>;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<string,[string,string]>={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;i<text.length;i++){
const ch=text[i];
if(quoted){if(ch==='"'){if(text[i+1]==='"'){cell+='"';i++;}else{quoted=false;closed=true;}}else cell+=ch;}
else if(ch===delimiter)field();
else if(ch==='\n'||ch==='\r'){if(ch==='\r'&&text[i+1]==='\n')i++;record();}
else if(ch==='"'&&!cell&&!closed)quoted=true;
else if(closed)fail('Некорректные кавычки CSV.');
else cell+=ch;
if(cell.length>4096)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<string>(),canIds=new Set<string>();let session='',previous=-Infinity,offset=0,start:number|undefined;
const points:LogPoint[]=[];
for(let i=1;i<records.length;i++){
const row=records[i];if(row.length!==header.length)fail(`Число колонок изменилось в строке ${i+1}.`);
const clock=numeric(row[timeIndex],i+1);if(clock===null||clock<0)fail(`Нет времени измерения в строке ${i+1}.`);
if(rt&&clock!>=86400000)fail('Время ms_today выходит за пределы суток.');
let at=clock!*timeScale+offset,rollover=false;
if(at<previous){if(rt&&previous-offset>18*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<string,number|null>={};
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<string,[string,string]>={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<n;i++){const w=.5*(1-Math.cos(2*Math.PI*i/(n-1)));gain+=w;real[i]=(data[i].values[key]!-mean)*w;}
for(let i=1,j=0;i<n;i++){let bit=n>>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i<j)[real[i],real[j]]=[real[j],real[i]];}
for(let length=2;length<=n;length*=2){const angle=-2*Math.PI/length;
for(let start=0;start<n;start+=length)for(let j=0;j<length/2;j++){
const a=start+j,b=a+length/2,c=Math.cos(angle*j),s=Math.sin(angle*j),r=real[b]*c-imag[b]*s,im=real[b]*s+imag[b]*c;
real[b]=real[a]-r;imag[b]=imag[a]-im;real[a]+=r;imag[a]+=im;
}
}
const rate=1000/dt,bins=Array.from({length:n/2+1},(_,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};
}
+16 -2
View File
@@ -1,3 +1,4 @@
import type {ControlAdapter,ControlEndpoint,ControlTransportProfile} from "./controlTransport";
import type {Sensor} from '../../../../packages/sensor-ui/src/contracts';
export interface VescIdentity {uuid:string;hardware:string;version:string;test_firmware:number|null;hardware_type:number|null}
@@ -8,13 +9,22 @@ export function drivePositions(layout:DriveProfile['layout']):Record<string,stri
? {'left.1':'Левый передний','left.2':'Левый задний','right.1':'Правый передний','right.2':'Правый задний'}
: {'left.1':'Левый','right.1':'Правый'};
}
export interface VescFirmwareState {state:string;progress?:number;operation_id?:string;before_backup_id?:string;image?:{name:string;sha256:string;swd?:{target_code:number;pins:string;address:number;flash_bytes:number};can_id?:number}}
export interface VescStatus {
board_settings_supported?:boolean;
group_test_supported?:boolean;
package_pending?:boolean; code_pending?:boolean; code_execution_pending?:boolean; bms_configuration_pending?:boolean;
tools_read_supported?:boolean; terminal_read_supported?:boolean;
firmware_update_supported?:boolean; firmware_update?:VescFirmwareState;
connected?:boolean; telemetry_ready?:boolean;
configuration_edit_supported?:boolean; configuration_pending?:boolean;
configuration_read_supported?:boolean; diagnostics_read_supported?:boolean;
engine?:{version:string;commit:string;contract?:{rpc_version:number;profile_sha256:string;firmware_targets?:string[];firmware_formats?:string[];firmware_profiles:{major:number;minor:number;hardware_type:number}[];methods:string[]}};
sample_data_supported?:boolean; qml_preview_supported?:boolean; qml_interactive_supported?:boolean; qml_broker_supported?:boolean; board_settings_supported?:boolean;
group_test_supported?:boolean; test_active?:boolean;
link_check_supported?:boolean;
foc_calibration?:{min_power_loss_w:number;max_power_loss_w:number;interruptible:boolean};
speed_limits?:{min_erpm:number;max_erpm:number;duration_basis:string;reverse_supported?:boolean;standstill_confirmation_required?:boolean};
hall_measurement?:{current_a:number;interruptible:boolean;standstill_confirmation_required?:boolean};
control_transport?:ControlTransportProfile; control_endpoints?:ControlEndpoint[]; control_adapters?:ControlAdapter[];
drive_profile?:DriveProfile;
test_limits?:{min_current_a:number;max_current_a:number;min_duration_s:number;max_duration_s:number;current_ramp_a_per_s?:number;continuous_current?:boolean;max_erpm?:number;max_duty?:number;stall_current_a?:number;stall_timeout_s?:number};
identity:VescIdentity|null; readable:boolean; message:string|null; telemetry:VescTelemetry|null;
@@ -50,7 +60,11 @@ export function vescLabel(device:Sensor,fresh:boolean):{label:string;tone:'neutr
if(!fresh||!device.online)return {label:'Нет связи',tone:'neutral'};
if(!device.prepared)return {label:'Требуется подготовка',tone:'neutral'};
if(!status.identity)return {label:'Не определён',tone:'warning'};
if(status.firmware_update?.state==='uploading')return {label:'Загрузка прошивки',tone:'warning'};
if(status.firmware_update&&['awaiting_identity','unknown'].includes(status.firmware_update.state))return {label:'Требуется проверка прошивки',tone:'warning'};
if(status.connected===false)return {label:'Восстановление связи',tone:'warning'};
if(!status.readable)return {label:'Прошивка не поддерживается',tone:'warning'};
if(status.telemetry_ready===false)return {label:'Ожидание данных',tone:'neutral'};
return {label:'Готов к чтению',tone:'success'};
}
+1 -1
View File
@@ -5,5 +5,5 @@ import {vescLabel} from './model';
export const vescSensorUi:SensorUiContribution={
kind:'vesc.controller',Detail:VescDetail,BoardSettings:VescBoardSettings,icon:'activity',retainOffline:true,
supportsPreparation:true,supportsRenaming:true,detailLabel:'Настройка VESC',status:vescLabel,
supportsPreparation:true,supportsRenaming:true,settingsInDetail:true,detailPresentation:'modal',detailLabel:'Настройка VESC',status:vescLabel,
};
@@ -0,0 +1,41 @@
/** Offline observations of original Sample Data. No motor/transport authority.
* FW5.02 mc_interface.c: Phase is mcpwm_foc_get_phase(), Hall is mcpwm_read_hall_phase(), a transformed
* commutation code, NOT the three raw GPIO inputs. Neither proves mechanical shaft movement.
*/
import type {LogPoint} from './logAnalysis';
export interface HallEvent {kind:'code'|'missing'|'change';first:number;last:number;at:number;end:number;label:string;current:number|null}
export interface HallReview {count:number;counts:number[];missing:number;transitions:number;longest:number[];phaseCount:number;phaseStep:number|null;halfTurns:number;peakCurrent:number|null;events:HallEvent[]}
const finite=(v:unknown):v is number=>typeof v==='number'&&Number.isFinite(v);
const hall=(p:LogPoint)=>!p.gap&&finite(p.values.hall)&&Number.isInteger(p.values.hall)&&p.values.hall>=0&&p.values.hall<=7?p.values.hall:null;
const phase=(p:LogPoint)=>!p.gap&&finite(p.values.phase_deg)&&p.values.phase_deg>=0&&p.values.phase_deg<=360?p.values.phase_deg:null;
export function wrappedPhaseStep(a:number,b:number){return ((b-a+540)%360)-180;}
export function reviewRotorHall(points:readonly LogPoint[],from:number,to:number):HallReview {
if(points.length>2000||!finite(from)||!finite(to)||from>to)throw new Error('Неверный интервал Sample Data.');
let previous=-Infinity;
for(const p of points){if(!finite(p.at)||p.at<=previous)throw new Error('Нарушен порядок времени Sample Data.');previous=p.at;}
const out:HallReview={count:0,counts:Array(8).fill(0),missing:0,transitions:0,longest:Array(8).fill(0),phaseCount:0,phaseStep:null,halfTurns:0,peakCurrent:null,events:[]};
let prior:{p:LogPoint;h:number|null;angle:number|null;index:number}|null=null,runStart=0;
for(let index=0;index<points.length;index++){
const p=points[index];if(p.at<from||p.at>to)continue;
out.count++;const h=hall(p),angle=phase(p),current=!p.gap&&finite(p.values.current)?p.values.current:null;
if(current!==null)out.peakCurrent=Math.max(out.peakCurrent??0,Math.abs(current));
if(h===null)out.missing++;else out.counts[h]++;
if(angle!==null){out.phaseCount++;if(prior&&prior.angle!==null){const step=Math.abs(wrappedPhaseStep(prior.angle,angle));out.phaseStep=Math.max(out.phaseStep??0,step);if(Math.abs(step-180)<1e-9)out.halfTurns++;}}
if(h!==null){if(!prior||prior.h!==h)runStart=p.at;out.longest[h]=Math.max(out.longest[h],p.at-runStart);}
if(h===null||h===0||h===7){
const kind=h===null?'missing':'code',last=out.events.at(-1);
const label=h===null?'Нет кода Hall в выборке':`Код Hall ${h}`;
if(last&&last.kind===kind&&last.label===label&&last.last===index-1){last.last=index;last.end=p.at;if(current!==null)last.current=Math.max(last.current??0,Math.abs(current));}
else out.events.push({kind,first:index,last:index,at:p.at,end:p.at,label,current:current===null?null:Math.abs(current)});
}
if(h!==null&&prior?.h!=null&&h!==prior.h){
out.transitions++;
out.events.push({kind:'change',first:prior.index,last:index,at:prior.p.at,end:p.at,label:`Код Hall: ${prior.h} → ${h}`,current:[prior.p.values.current,current].filter(finite).reduce<number|null>((peak,n)=>Math.max(peak??0,Math.abs(n)),null)});
}
prior={p,h,angle,index};
}
return out;
}
export function hallEventWindow(points:readonly LogPoint[],event:HallEvent){
return {from:points[Math.max(0,event.first-5)].at,to:points[Math.min(points.length-1,event.last+5)].at,first:event.at,second:event.end};
}
+70
View File
@@ -0,0 +1,70 @@
/** Offline Sample Data review; no transport, persistence or controller authority. */
import {LOG_MAX_BYTES,parseVescLog,type LogPoint} from './logAnalysis';
import {sampleFields,samplePoints,sampleStateLabel,type SampleRow,type SampleState} from './samples';
import type {VescIdentity} from './model';
export interface SampleRecord {
name:string;points:LogPoint[];uuid:string|null;hardware:string|null;firmware:string|null;
session:string|null;capture:string|null;status:string;complete:boolean|null;thirdMeasured:boolean|null;
}
function fail(message:string):never {throw new Error(message);}
function object(v:unknown):Record<string,unknown>{return v!==null&&typeof v==='object'&&!Array.isArray(v)?v as Record<string,unknown>:fail('Повреждён паспорт выборки.');}
function text(v:unknown,max=160):string|null {if(v===null||v===undefined||v==='')return null;if(typeof v!=='string'||v.length>max||/[\x00-\x1f]/.test(v))return fail('Некорректное поле паспорта.');return v;}
function integer(v:unknown,min:number,max:number):number {return typeof v==='number'&&Number.isInteger(v)&&v>=min&&v<=max?v:fail('Некорректные счётчики выборки.');}
const keys:Record<string,string>={I1:'i1',I2:'i2',I3:'i3',I_tot:'current',V1:'v1',V2:'v2',V3:'v3',V_zero:'v0',Phase:'phase_deg',Hall:'hall',Commutation:'commutation',F_sw:'switching_hz'};
export function liveSampleRecord(name:string,rows:SampleRow[],state:SampleState,identity:VescIdentity|null|undefined,session:string|null|undefined):SampleRecord {
return {name,points:samplePoints(rows),uuid:identity?.uuid??null,hardware:identity?.hardware??null,firmware:identity?.version??null,session:session??null,capture:state.capture_id,status:sampleStateLabel[state.state]??state.state,complete:state.state==='complete',thirdMeasured:rows.every(r=>r.third_current_measured)};
}
export function parseSampleRecord(source:string,name:string):SampleRecord {
if(source.length>LOG_MAX_BYTES||new TextEncoder().encode(source).length>LOG_MAX_BYTES)fail('Максимальный размер файла — 4 МиБ.');
source=source.replace(/^\uFEFF/,'').trim();
if(!source.startsWith('{')){
const log=parseVescLog(source);if(log.format!=='VESC Tool · Sample Data')fail('Здесь нужен CSV Sample Data. Обычные журналы открываются в разделе «Анализ журналов и FFT».');
return {name,points:log.points.map(p=>({...p,values:Object.fromEntries(Object.entries(p.values).map(([k,v])=>[keys[k],v]))})),uuid:null,hardware:null,firmware:null,session:null,capture:null,status:'CSV: полнота и источник не подтверждены',complete:null,thirdMeasured:null};
}
const data=object(JSON.parse(source));if(data.schema!=='missioncore.vesc.sample-data/v1')fail('Неизвестная версия паспорта Sample Data.');
const state=object(data.state),id=data.identity==null?{}:object(data.identity);
if(!Array.isArray(data.rows)||!data.rows.length||data.rows.length>2000)fail('Выборка должна содержать 1–2000 отсчётов.');
const rows=data.rows.map((value,i)=>{
const r=object(value);if(r.index!==i||typeof r.dt_s!=='number'||!Number.isFinite(r.dt_s)||r.dt_s<=0||r.dt_s>1||typeof r.indexed!=='boolean'||typeof r.third_current_measured!=='boolean')fail('Повреждены порядок или шаг времени выборки.');
for(const [key] of sampleFields)if(typeof r[key]!=='number'||!Number.isFinite(r[key])||Math.abs(r[key] as number)>1e15)fail('Повреждены числовые значения выборки.');
integer(r.hall,0,7);integer(r.commutation,0,7);if((r.switching_hz as number)<=0)fail('Неверная частота выборки.');
return Object.fromEntries(['index','dt_s','indexed','third_current_measured',...sampleFields.map(f=>f[0])].map(k=>[k,r[k]])) as unknown as SampleRow;
});
const received=integer(state.received,1,2000),expected=integer(state.expected,0,2000),malformed=integer(state.malformed,0,1e9);
const label=text(state.state);if(!label||!Object.hasOwn(sampleStateLabel,label))fail('Неизвестное состояние выборки.');
if(received!==rows.length||label==='complete'&&(received!==expected||malformed!==0))fail('Паспорт не соответствует полученным отсчётам.');
integer(state.mode,1,7);integer(state.count,1,2000);integer(state.decimation,1,255);
const uuid=text(id.uuid);if(uuid&&!/^[a-f\d]{24}$/i.test(uuid))fail('UUID должен содержать 24 шестнадцатеричных символа.');
return {name,points:samplePoints(rows),uuid,hardware:text(id.hardware),firmware:text(id.version),session:text(data.session),capture:text(state.capture_id),status:sampleStateLabel[label],complete:label==='complete',thirdMeasured:rows.every(r=>r.third_current_measured)};
}
export interface SampleFilter {kind:'none'|'mean'|'fir';bits:number;cutoff:number;hamming:boolean;compensate:boolean}
export const defaultSampleFilter:SampleFilter={kind:'none',bits:6,cutoff:.05,hamming:true,compensate:true};
/** Tool 7.00 DigitalFiltering::generateFirFilter frequency bins, real inverse DFT,
* fftshift and Hamming. This direct bounded DFT avoids a second FFT dependency. */
export function filterCoefficients(filter:SampleFilter):number[]{
if(filter.kind==='none')return [];
if(!['mean','fir'].includes(filter.kind)||!Number.isInteger(filter.bits)||filter.bits<1||filter.bits>10||!Number.isFinite(filter.cutoff)||filter.cutoff<0||filter.cutoff>.5)fail('Недопустимые параметры фильтра.');
const n=2**filter.bits;if(filter.kind==='mean')return Array(n).fill(1/n);
const pass=Math.floor(n*filter.cutoff);
return Array.from({length:n},(_,j)=>{const k=(j+n/2)%n;let sum=0;for(let i=0;i<pass;i++)sum+=Math.cos(2*Math.PI*k*i/n)+Math.cos(2*Math.PI*k*(n-i-1)/n);return sum/n*(filter.hamming ? 0.54-0.46*Math.cos(2*Math.PI*j/(n-1)):1);});
}
export function filteredSamplePoints(points:readonly LogPoint[],key:string,filter:SampleFilter,coefficients=filterCoefficients(filter)):{at:number;value:number|null}[]{
const values=points.map(p=>({at:p.at,value:p.gap?null:p.values[key]??null}));
if(filter.kind==='none'||!['i1','i2','i3'].includes(key))return values;
const taps=coefficients.length,shift=filter.compensate?taps/2:taps;
// Same valid convolution positions as Tool. Tool zero-pads unavailable edges;
// Core retains them as gaps so a zero current is never invented.
const result=values.map(p=>({...p,value:null as number|null}));
for(let i=0;i<values.length-taps;i++){
const dt=values[i+1].at-values[i].at;let value=0,valid=dt>0;
for(let j=0;j<taps;j++){const p=values[i+j];if(p.value===null||j>0&&Math.abs(p.at-values[i+j-1].at-dt)>dt*.01){valid=false;break;}value+=p.value*coefficients[j];}
if(valid)result[i+shift].value=value;
}
return result;
}
export function sampleMeasurement(points:readonly {at:number;value:number|null}[],from:number,to:number,cursor1:number,cursor2:number){
const interval=points.filter(p=>p.at>=from&&p.at<=to),valid=interval.filter((p):p is {at:number;value:number}=>p.value!==null&&Number.isFinite(p.value));
const nearest=(at:number)=>{if(!interval.length||at<interval[0].at||at>interval.at(-1)!.at)return null;const p=interval.reduce((a,b)=>Math.abs(a.at-at)<=Math.abs(b.at-at)?a:b);return p.value===null?null:p;};
const first=nearest(cursor1),second=nearest(cursor2);
return {count:valid.length,min:valid.length?Math.min(...valid.map(p=>p.value)):null,max:valid.length?Math.max(...valid.map(p=>p.value)):null,rms:valid.length?Math.sqrt(valid.reduce((sum,p)=>sum+p.value**2,0)/valid.length):null,first,second,delta:first&&second?second.value!-first.value!:null,dt:first&&second?second.at-first.at:null};
}
+15
View File
@@ -0,0 +1,15 @@
import type {LogPoint} from './logAnalysis';
export interface SampleRow {index:number;i1:number;i2:number;i3:number;v1:number;v2:number;v3:number;v0:number;current:number;switching_hz:number;commutation:number;hall:number;phase_deg:number;dt_s:number;indexed:boolean;third_current_measured:boolean}
export interface SampleState {capture_id:string;state:string;received:number;expected:number;mode:number;count:number;decimation:number;malformed:number;error?:string;rows?:SampleRow[];offset?:number;elapsed_ms:number;provenance:string}
export const sampleFields=[['i1','Ток фазы 1','А'],['i2','Ток фазы 2','А'],['i3','Ток фазы 3 (расчёт)','А'],['current','Ток мотора','А'],['v1','Напряжение фазы 1','В'],['v2','Напряжение фазы 2','В'],['v3','Напряжение фазы 3','В'],['v0','Нулевая точка','В'],['hall','Код Hall из выборки',''],['commutation','Шаг коммутации',''],['phase_deg','Угол фазы (электрический)','°'],['switching_hz','Частота выборки до делителя','Гц']] as const;
export function samplePoints(rows:SampleRow[]):LogPoint[]{
if(rows.length>2000)throw new Error('Буфер превышает 2000 отсчётов.');
let at=0;return rows.map((r,i)=>{
if(r.index!==i||!Number.isFinite(r.dt_s)||r.dt_s<=0||sampleFields.some(([key])=>!Number.isFinite(r[key])))throw new Error('Повреждён порядок или значения выборки.');
const point={at,values:Object.fromEntries(sampleFields.map(([key])=>[key,r[key]])),gap:false};at+=r.dt_s*1000;return point;
});
}
export function sampleCsv(rows:SampleRow[]){
const points=samplePoints(rows);return 'T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase;Hall;Commutation;F_sw\n'+rows.map((r,i)=>[points[i].at/1000,r.i1,r.i2,r.i3,r.v1,r.v2,r.v3,r.current,r.v0,r.phase_deg,r.hall,r.commutation,r.switching_hz].join(';')).join('\n');
}
export const sampleStateLabel:Record<string,string>={idle:'Захват не запускался',armed:'Ожидание выборки',stored_wait:'Ожидание события; буфер на контроллере',receiving:'Получение выборки',complete:'Все ожидаемые отсчёты получены',incomplete:'Неполная выборка',timeout:'Срок ожидания истёк',cancelled:'Захват остановлен',unverified:'Последний буфер; событие не подтверждено',expired:'Буфер истёк'};
@@ -0,0 +1,25 @@
import type {SensorLiveFrame} from '../../../../packages/sensor-ui/src/contracts';
/** One abortable read at a time; no command path and no queued catch-up reads. */
export class TraceObserver {
private closed=false;private busy=false;private abort:AbortController|undefined;
private timer:ReturnType<typeof setInterval>;
constructor(private read:(signal:AbortSignal)=>Promise<SensorLiveFrame>,
private receive:(frame:SensorLiveFrame|null,now:number,roundTripMs:number)=>void,
private tick:(now:number)=>void,private visible:()=>boolean=()=>!document.hidden,
private clock:()=>number=()=>performance.now()){
this.timer=setInterval(()=>this.step(),500);this.step();
}
private step(){
if(this.closed)return;this.tick(this.clock());
if(!this.visible()){this.abort?.abort();this.receive(null,this.clock(),0);return;}
if(this.busy)return;
this.busy=true;const abort=new AbortController();this.abort=abort;const started=this.clock();
const deadline=setTimeout(()=>abort.abort(),1200);
Promise.resolve().then(()=>this.read(abort.signal)).then(frame=>{
if(!this.closed&&!abort.signal.aborted&&this.visible())this.receive(frame,this.clock(),this.clock()-started);
}).catch(()=>{if(!this.closed)this.receive(null,this.clock(),0);})
.finally(()=>{clearTimeout(deadline);this.busy=false;if(this.abort===abort)this.abort=undefined;});
}
close(){this.closed=true;clearInterval(this.timer);this.abort?.abort();}
}
+80
View File
@@ -0,0 +1,80 @@
import type {SensorLiveFrame} from '../../../../packages/sensor-ui/src/contracts';
export const TRACE_MS=300000,TRACE_LIMIT=1200,FRESH_MS=1500;
export const metrics=[
['input_voltage_v','Напряжение питания','В'],['input_current_a','Ток питания','А'],
['motor_current_a','Ток мотора','А'],['input_power_w','Мощность питания','Вт'],
['duty','Заполнение PWM','%'],['erpm','Электрические обороты','ERPM'],
['mos_temperature_c','Температура контроллера','°C'],['motor_temperature_c','Температура мотора','°C'],
['mos1_c','Датчик MOS 1','°C'],['mos2_c','Датчик MOS 2','°C'],['mos3_c','Датчик MOS 3','°C'],
['id_current_a','Ток FOC по оси d','А'],['iq_current_a','Ток FOC по оси q','А'],
['vd_v','Напряжение FOC по оси d','В'],['vq_v','Напряжение FOC по оси q','В'],
['position_deg','Положение ротора','°'],['tachometer','Счётчик тахометра',''],
['tachometer_abs','Абсолютный счётчик тахометра',''],['amp_hours','Расход заряда','А·ч'],
['amp_hours_charged','Возвращённый заряд','А·ч'],['watt_hours','Расход энергии','Вт·ч'],
['watt_hours_charged','Возвращённая энергия','Вт·ч'],['fault_code','Код ошибки',''],
] as const;
export type Metric=typeof metrics[number][0];
export interface TracePoint {at:number;source:string;session:string;sample:number;utc:string;values:Partial<Record<Metric,number>>|null}
export class VescTrace {
points:TracePoint[]=[];
private source='';private session='';private sample=-Infinity;private offset=0;
private freshAt=-Infinity;private day='';
get freshUntil(){return this.freshAt+FRESH_MS;}
clear(){this.points=[];this.source='';this.session='';this.sample=-Infinity;this.freshAt=-Infinity;}
prune(now:number,day=new Date().toISOString().slice(0,10)){
if(this.day&&this.day!==day)this.clear();this.day=day;
this.points=this.points.filter(p=>p.at>=now-TRACE_MS).slice(-TRACE_LIMIT);
}
gap(now:number){
this.freshAt=-Infinity;
if(this.points.at(-1)?.values)this.points.push({at:now,source:this.source,session:this.session,sample:this.sample,utc:'',values:null});
this.prune(now);
}
accept(frame:SensorLiveFrame,id:string,uuid:string,now:number,roundTripMs:number):boolean{
const matches=frame.devices?.filter(d=>d.id===id)??[];
const p=matches.length===1?matches[0]:undefined;
if(!frame.fresh||!frame.instance||!p||p.uuid?.toLowerCase()!==uuid.toLowerCase()||!p.session_id||
!Number.isFinite(p.sample_time_ms)||p.sample_time_ms<0||!Number.isFinite(p.age_ms)||p.age_ms<0||
!Number.isFinite(roundTripMs)||roundTripMs<0||p.age_ms+roundTripMs>=FRESH_MS||!Number.isFinite(Date.parse(p.observed_at))){this.gap(now);return false;}
const changed=frame.instance!==this.source||p.session_id!==this.session;
if(!changed&&p.sample_time_ms<=this.sample){if(now>=this.freshUntil)this.gap(now);return false;}
if(changed){this.gap(now);this.offset=now-p.age_ms-roundTripMs-p.sample_time_ms;}
let at=p.sample_time_ms+this.offset;
// Monotonic source time owns spacing. Arrival delay cannot extend freshness
// or turn a duplicate, reordered frame, reset or reconnect into continuity.
if(at>(now+FRESH_MS)||at<now-TRACE_MS){this.gap(now);this.offset=now-p.age_ms-roundTripMs-p.sample_time_ms;at=p.sample_time_ms+this.offset;}
if(this.points.at(-1)?.values&&at-this.points.at(-1)!.at>FRESH_MS)this.gap(at-FRESH_MS);
at=Math.max(at,this.points.at(-1)?.at??at);
const values:Partial<Record<Metric,number>>={};
for(const [key] of metrics){const value=p.values?.[key];if(typeof value==='number'&&Number.isFinite(value))values[key]=key==='duty'?value*100:value;}
if(values.input_current_a!==undefined&&values.input_voltage_v!==undefined){const watts=values.input_current_a*values.input_voltage_v;if(Number.isFinite(watts))values.input_power_w=watts;}
if(!Object.keys(values).length){this.gap(now);return false;}
this.source=frame.instance;this.session=p.session_id;this.sample=p.sample_time_ms;this.freshAt=now-p.age_ms-roundTripMs;
this.points.push({at,source:this.source,session:this.session,sample:this.sample,utc:p.observed_at,values});this.prune(now);return true;
}
}
export function traceView(points:readonly TracePoint[],metric:Metric,from:number,to:number,height=180){
const visible=points.filter(p=>p.at>=from&&p.at<=to),values=visible.flatMap(p=>p.values?.[metric]===undefined?[]:[p.values[metric]!]);
const min=values.length?Math.min(...values):null,max=values.length?Math.max(...values):null;
const mean=values.length?values.reduce((sum,n)=>sum+n/values.length,0):null;
const spread=min===null||max===null?1:Math.max((max-min)*.1,Math.abs(max)*.01,.001);
const low=(min??0)-spread,high=(max??0)+spread;
const segments:{x:number;y:number}[][]=[];let line:{x:number;y:number}[]=[];
for(const point of visible){const v=point.values?.[metric];if(v===undefined){if(line.length)segments.push(line);line=[];continue;}
line.push({x:64+((point.at-from)/Math.max(1,to-from))*716,y:20+(1-(v-low)/(high-low))*height});
}
if(line.length)segments.push(line);
return {segments,min,max,mean,low,high,count:values.length,last:values.at(-1)??null};
}
const csvCell=(v:string|number)=>typeof v==='number'?String(v):'"'+(/^[\s]*[=+@-]/.test(v)?"'"+v:v).replaceAll('"','""')+'"';
export function traceCsv(points:readonly TracePoint[],identity:{uuid:string;hardware:string;version:string}){
const header=['plot_elapsed_s','sample_utc','source_instance','usb_session','source_monotonic_ms','state','uuid','hardware','firmware',...metrics.map(([key,,unit])=>`${key} [${unit}]`)];
const start=points[0]?.at??0;
return '\uFEFF'+[header.map(csvCell).join(','),...points.map(p=>[
(p.at-start)/1000,p.utc,p.source,p.session,p.sample,p.values?'sample':'gap',identity.uuid,identity.hardware,identity.version,
...metrics.map(([key])=>p.values?.[key]??''),
].map(csvCell).join(','))].join('\r\n')+'\r\n';
}
@@ -0,0 +1,38 @@
import {useEffect,useRef,useState} from 'react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {CONFIGURATION_OPERATION_TIMEOUT_MS} from './configurationOperation';
export interface ConfigChange {kind:'motor'|'application';name:string;title:string;before:number|string|boolean;after:number|string|boolean;suffix:string;editor_scale:number}
export interface ConfigPreview {preview_id:string;expires_in_s:number;identity:{uuid:string};changes:ConfigChange[]}
export interface ConfigResult {outcome:string;verified:boolean;message?:string;before_backup_id?:string;after_backup_id?:string}
export function useVescEditor(props:ReadProps){
const [preview,setPreview]=useState<ConfigPreview|null>(null),[result,setResult]=useState<ConfigResult|null>(null),[busy,setBusy]=useState(false);
const running=useRef(false),mounted=useRef(true);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const available=props.enabled&&props.device.online&&props.device.verified&&vescStatus(props.device).configuration_edit_supported===true;
async function execute<T>(action:string,parameters:Record<string,unknown>,timeout=CONFIGURATION_OPERATION_TIMEOUT_MS):Promise<T|null>{
if(running.current||props.blocked||!available)return null;
running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);
try{return await perform<T>(props.transport,props.device,action,parameters,timeout);}
catch(error){if(mounted.current)props.failure(error);return null;}
finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}
}
async function prepare(parameters:Record<string,unknown>){
setPreview(null);setResult(null);
const value=await execute<ConfigPreview>('vesc.configuration.preview',parameters);
if(mounted.current)setPreview(value);
}
async function apply(){
if(!preview)return;
const id=preview.preview_id;setPreview(null);
const value=await execute<ConfigResult>('vesc.configuration.apply',{preview_id:id,rig_clear:true,inputs_isolated:true});
if(mounted.current){setResult(value);await props.refresh();}
}
async function reconcile(){
const value=await execute<ConfigResult>('vesc.configuration.reconcile',{});
if(mounted.current){setResult(value);await props.refresh();}
}
return {preview,result,busy,available,prepare,apply,reconcile,clear:()=>{setPreview(null);setResult(null);}};
}
+23
View File
@@ -0,0 +1,23 @@
import {useEffect,useRef,useState} from 'react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {vescStatus} from './model';
import {CONFIGURATION_OPERATION_TIMEOUT_MS} from './configurationOperation';
export type ReadProps=SensorDetailProps&{blocked:boolean;onBusyChange:(busy:boolean)=>void};
export function useVescRead<T>(props:ReadProps,action:string,supported=true){
const {device,transport,enabled,failure,blocked,onBusyChange}=props;
const [value,setValue]=useState<T|null>(null),[busy,setBusy]=useState(false);
const running=useRef(false),mounted=useRef(true);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const available=enabled&&device.online&&device.verified&&vescStatus(device).readable&&supported;
async function read(parameters:Record<string,unknown>={}){
if(running.current||blocked||!available)return;
running.current=true;setBusy(true);onBusyChange(true);failure(null);
const timeout=action==='vesc.configuration.read'?CONFIGURATION_OPERATION_TIMEOUT_MS:30000;
try{const result=await perform<T>(transport,device,action,parameters,timeout);if(mounted.current)setValue(result);}
catch(error){if(mounted.current)failure(error);}
finally{running.current=false;onBusyChange(false);if(mounted.current)setBusy(false);}
}
return {value,busy,available,read};
}
+15
View File
@@ -0,0 +1,15 @@
.vesc-diagnostic-output {white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:var(--nodedc-font-size-sm);line-height:1.5}
.vesc-parameter-title {overflow-wrap:anywhere}
/* VESC data renderer; grid strokes convey numerical scale, not card decoration. */
.vesc-trend-toolbar {display:flex;justify-content:flex-end}
.vesc-trend-plot {display:block;width:100%;height:236px;overflow:visible}
.vesc-trend-plot--expanded {height:440px}
.vesc-trend-plot text {fill:var(--nodedc-text-muted);font:inherit;font-size:var(--nodedc-font-size-sm)}
.vesc-trend-grid {stroke:var(--nodedc-text-muted);stroke-opacity:.25;stroke-width:1}
.vesc-trend-line {fill:none;stroke:rgb(var(--nodedc-accent-rgb));stroke-width:2;vector-effect:non-scaling-stroke}
.vesc-trend-point {fill:rgb(var(--nodedc-accent-rgb))}
/* Measurement cursors are plot annotations, not UI borders. */
.vesc-trend-cursor {stroke:var(--nodedc-text-muted);stroke-width:1;stroke-dasharray:4 4;vector-effect:non-scaling-stroke}
+53
View File
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "tools_native.h"
#include "engine_profile.h"
static QJsonObject canIdentity(const FW_RX_PARAMS &p, int id) {
return {{"can_id",id},{"uuid",QString::fromLatin1(p.uuid.toHex())},{"hardware",p.hw},
{"major",p.major},{"minor",p.minor},{"hardware_type",int(p.hwType)},{"test_firmware",p.isTestFw},{"custom_configs",p.customConfigNum}};
}
static bool bmsCommandsSupported(const FW_RX_PARAMS &p) {
if(p.hwType!=HW_TYPE_VESC_BMS || p.isTestFw!=0)return false;
for(const auto &v:engineProfile().value("bms_profiles").toArray()) {
const auto profile=v.toObject();
if(p.major==profile.value("major").toInt() && p.minor==profile.value("minor").toInt())return true;
}
return false;
}
// Use the original temporary route. Neither the local schema nor the local UUID
// is replaced by the CAN reply; restore the route even when a check throws.
class NativeCanTarget {
VescInterface &vesc;
bool &remote;
public:
NativeCanTarget(VescInterface &v, bool &flag, int id):vesc(v),remote(flag) {
require(id>=0 && id<=253,"Invalid unicast CAN target");
require(!remote && !v.commands()->getSendCan() && !v.isIgnoringCanChanges(),"CAN route already owned");
remote=true;vesc.canTmpOverride(true,id);
}
~NativeCanTarget(){vesc.canTmpOverrideEnd();remote=false;}
FW_RX_PARAMS identify() {
FW_RX_PARAMS p;
require(Utility::getFwVersionBlocking(&vesc,&p,1500),"CAN target did not identify");
require(p.uuid.size()==12 && p.uuid!=QByteArray(12,'\0') && p.hw.size()>0 && p.hw.size()<=64,"CAN identity incomplete");
return p;
}
};
static void sendBmsCommand(Commands *cmd, const QString &action) {
const QMap<QString,int> codes{{"charge_enable",COMM_BMS_SET_CHARGE_ALLOWED},
{"charge_disable",COMM_BMS_SET_CHARGE_ALLOWED},{"balance_enable",COMM_BMS_FORCE_BALANCE},
{"balance_disable",COMM_BMS_FORCE_BALANCE},{"reset_ah",COMM_BMS_RESET_COUNTERS},
{"reset_wh",COMM_BMS_RESET_COUNTERS},{"zero_current",COMM_BMS_ZERO_CURRENT_OFFSET}};
require(codes.contains(action),"Unknown BMS operation");
require(cmd->getSendCan() && cmd->getCanSendId()>=0 && cmd->getCanSendId()<=253,"BMS needs an exact CAN route");
require(cmd->getLimitedCompatibilityCommands().contains(codes.value(action)),"BMS command unsupported by transport firmware");
if(action=="charge_enable" || action=="charge_disable")cmd->bmsSetChargeAllowed(action=="charge_enable");
else if(action=="balance_enable" || action=="balance_disable")cmd->bmsForceBalance(action=="balance_enable");
else if(action=="reset_ah" || action=="reset_wh")cmd->bmsResetCounters(action=="reset_ah",action=="reset_wh");
else cmd->bmsZeroCurrentOffset();
}
static void requireSameCanIdentity(const FW_RX_PARAMS &a, const FW_RX_PARAMS &b) {
require(a.uuid==b.uuid && a.hw==b.hw && a.major==b.major && a.minor==b.minor && a.hwType==b.hwType && a.isTestFw==b.isTestFw,
"CAN target identity changed");
}
+168
View File
@@ -0,0 +1,168 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <functional>
#include "custom_native.h"
#include "codeloader.h"
#include <QTemporaryDir>
// CodeLoader owns file formats. Only explicit uploaded attachments can be read;
// no package-store lookup, host path fallback or automatic QML execution.
class NativeCode {
public:
static bool supported(const FW_RX_PARAMS &p) {
return p.major==6 && p.minor==0 && p.hwType==HW_TYPE_VESC && p.isTestFw==0;
}
static QList<QPair<QString,QString>> imports(const QString &source) {
QList<QPair<QString,QString>> out; QSet<QString> tags;
for(auto line:source.split('\n')) {
while(line.startsWith(' '))line.remove(0,1);
while(line.startsWith("( "))line.remove(1,1);
if(!line.startsWith("(import ",Qt::CaseInsensitive))continue;
auto match=QRegularExpression("^\\(import +\"([A-Za-z0-9][A-Za-z0-9_.-]{0,95})\" +'?([A-Za-z_][A-Za-z0-9_-]{0,63})\\) *\\r?(?:;.*)?$",QRegularExpression::CaseInsensitiveOption).match(line);
require(match.hasMatch(),"Imports must name an attached flat file and a unique tag");
require(!tags.contains(match.captured(2)) && out.size()<32,"Duplicate or excessive imports");
tags.insert(match.captured(2));out.append(qMakePair(match.captured(1),match.captured(2)));
}
return out;
}
static QByteArray pack(const QJsonObject &project) {
const auto kind=project.value("kind").toString(),source=project.value("source").toString();
require((kind=="lisp"||kind=="qml") && project.value("source").isString(),"Code kind/source required");
require(!source.contains(QChar(0)) && source.toUtf8().size()<=120*1024,"Code source exceeds bound");
CodeLoader loader;VByteArray content;
if(kind=="qml") {
require(project.value("imports").toObject().isEmpty(),"QML attachments are not embedded by this firmware format");
content.vbAppendUint16(project.value("fullscreen").toBool()?2:1);content.append(loader.qmlCompress(source));
} else {
QTemporaryDir directory;require(directory.isValid(),"Cannot allocate bounded import directory");
const auto files=project.value("imports").toObject();require(files.size()<=32,"Too many imported files");
QSet<QString> wanted;int total=source.toUtf8().size();
for(const auto &item:imports(source))wanted.insert(item.first);
require(wanted.size()==files.size(),"Import attachment inventory differs from source");
for(const auto &name:wanted) {
require(files.value(name).isString(),"Missing attached import");
const auto encoded=files.value(name).toString().toLatin1();
const auto bytes=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
require(bytes.toBase64()==encoded,"Invalid imported file encoding");
total+=bytes.size();require(total<=120*1024,"Code and imports exceed flash bound");
QFile file(directory.filePath(name));require(file.open(QIODevice::WriteOnly|QIODevice::NewOnly),"Cannot stage import");
require(file.write(bytes)==bytes.size(),"Incomplete import staging");file.close();
}
content=loader.lispPackImports(source,directory.path(),false);
require(content.size()>=5,"Upstream Lisp pack failed");
}
VByteArray data;data.vbAppendUint32(content.size()-2);
data.vbAppendUint16(Packet::crc16(reinterpret_cast<const unsigned char*>(content.constData()),content.size()));data.append(content);
require(data.size()<=120*1024,"Packed code exceeds flash bound");return data;
}
static QByteArray image(const QJsonObject &req) {
const auto encoded=req.value("image").toString().toLatin1();
const auto data=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
require(data.toBase64()==encoded && data.size()>=8 && data.size()<=120*1024,"Invalid code image encoding or size");
VByteArray header(data.left(8));const auto length=header.vbPopFrontUint32();const auto crc=header.vbPopFrontUint16();const auto flags=header.vbPopFrontUint16();
require(length==quint32(data.size()-8) && crc==Packet::crc16(reinterpret_cast<const unsigned char*>(data.constData()+6),data.size()-6),"Invalid code image header");
const auto kind=req.value("kind").toString();require(kind=="lisp"?flags==0:kind=="qml"&&(flags==1||flags==2),"Code flags do not match kind");
return data;
}
static QJsonObject decode(const QString &kind,const QByteArray &data) {
QJsonObject result{{"kind",kind},{"sha256",sha256(data)},{"bytes",data.size()},{"payload",QString::fromLatin1(data.toBase64())}};
if(data.isEmpty()){result.insert("source","");result.insert("imports",QJsonObject{});return result;}
if(kind=="lisp") {
const int end=data.indexOf('\0');require(end>0 && end+3<=data.size(),"Invalid Lisp source boundary");
VByteArray table(data.mid(end+1));int count=table.vbPopFrontInt16();require(count>=0&&count<=32,"Invalid Lisp import count");
int tableEnd=end+3;QList<QPair<int,int>> ranges;QSet<QString> names;
for(int i=0;i<count;i++) {
const int n=table.indexOf('\0');require(n>0&&n<=64&&n+9<=table.size(),"Invalid Lisp import table");
const auto name=table.vbPopFrontString();int offset=table.vbPopFrontInt32(),length=table.vbPopFrontInt32();
require(!names.contains(name)&&offset>=0&&length>0&&offset<=data.size()-length&&data[offset+length-1]=='\0',"Invalid Lisp import range");
names.insert(name);ranges.append(qMakePair(offset,length));tableEnd+=n+9;
}
int previous=tableEnd;for(const auto &range:ranges){require(range.first>=previous,"Overlapping Lisp import range");previous=range.first+range.second;}
CodeLoader loader;const auto unpacked=loader.lispUnpackImports(data);QJsonObject files;
QStringList lines=unpacked.first.split('\n');
for(auto &line:lines) {
auto trimmed=line.trimmed();if(!trimmed.startsWith("(import ",Qt::CaseInsensitive))continue;
auto match=QRegularExpression("^\\(import +\"([^\"]+)\" +'?([A-Za-z_][A-Za-z0-9_-]{0,63})\\) *\\r?(?:;.*)?$",QRegularExpression::CaseInsensitiveOption).match(trimmed);
require(match.hasMatch(),"Lisp import cannot be reconstructed");const auto path=match.captured(1),tag=match.captured(2);
const bool flat=QRegularExpression("^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$").match(path).hasMatch();const auto name=flat?path:"import_"+tag+".bin";
bool found=false;for(const auto &file:unpacked.second)if(file.first==tag){const auto encoded=QString::fromLatin1(file.second.toBase64());require(!files.contains(name)||files.value(name).toString()==encoded,"Conflicting Lisp attachment");files.insert(name,encoded);found=true;break;}
require(found,"Lisp attachment is missing");if(!flat)line.replace("\""+path+"\"","\""+name+"\"");
}
result.insert("source",lines.join('\n'));result.insert("imports",files);
} else {
require(data.size()>=5 && qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(data.constData()))<=512*1024,"QML decompression bound exceeded");
const auto xml=qUncompress(data);require(!xml.isEmpty(),"Invalid compressed QML");
QString source=QString::fromUtf8(xml);const QString prefix="import Vedder.vesc.vescinterface 1.0;import \"qrc:/mobile\";";
if(source.startsWith(prefix))source.remove(0,prefix.size());
result.insert("source",source);result.insert("imports",QJsonObject{});
}
return result;
}
static QByteArray read(Commands *cmd,const QString &kind) {
require(kind=="lisp"||kind=="qml"||kind=="qml_hw","Unknown code kind");
QByteArray data;int total=-1;QElapsedTimer elapsed;elapsed.start();
do {
require(elapsed.elapsed()<25000,"Code read deadline exceeded");
const int offset=data.size(),amount=total<0?0:qMin(400,total-offset);
int receivedTotal=-1;QByteArray chunk;bool invalid=false;
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){
auto reply=[&,finish](int length,int at,QByteArray bytes){if(at!=offset)return;invalid=length<0||length>128*1024||bytes.size()!=amount||(total>=0&&length!=total)||at+bytes.size()>length;receivedTotal=length;chunk=bytes;finish();};
if(kind=="lisp")QObject::connect(cmd,&Commands::lispReadCodeRx,owner,reply);
else if(kind=="qml")QObject::connect(cmd,&Commands::qmluiAppRx,owner,reply);
else QObject::connect(cmd,&Commands::qmluiHwRx,owner,reply);
},[&]{if(kind=="lisp")cmd->lispReadCode(amount,offset);else if(kind=="qml")cmd->qmlUiAppGet(amount,offset);else cmd->qmlUiHwGet(amount,offset);});
require(!invalid,"Code fragment mismatch");total=receivedTotal;data.append(chunk);
}while(data.size()<total);
return data;
}
static void idle(Commands *cmd) {
MC_VALUES v;unsigned int mask=0;
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::valuesReceived,owner,[&,finish](MC_VALUES got,unsigned int m){v=got;mask=m;finish();});},[&]{cmd->getValues();});
require((mask&0xFC)==0xFC && std::isfinite(v.current_motor)&&std::abs(v.current_motor)<=.5&&std::isfinite(v.current_in)&&std::abs(v.current_in)<=.5&&std::isfinite(v.duty_now)&&std::abs(v.duty_now)<=.001&&std::isfinite(v.rpm)&&std::abs(v.rpm)<1,"Code operation requires idle drive");
}
static void running(Commands *cmd,bool run) {
bool ok=false;NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::lispRunningResRx,owner,[&,finish](bool result){ok=result;finish();});},[&]{cmd->lispSetRunning(run);},3500);require(ok,"Lisp state change rejected");
}
static QJsonObject run(VescInterface &vesc,const FW_RX_PARAMS &identity,const QJsonObject &req) {
const auto method=req.value("method").toString(),kind=req.value("kind").toString();auto cmd=vesc.commands();
require(supported(identity),"Code tools are supported for the reviewed VESC firmware 6.00 profile");
require(!cmd->getSendCan(),"Code tools require a direct USB target");
if(method=="code_snapshot") {const auto data=read(cmd,kind);return {{"payload",QString::fromLatin1(data.toBase64())},{"sha256",sha256(data)},{"bytes",data.size()},{"fullscreen",kind=="qml"&&identity.qmlAppFullscreen}};}
if(method=="code_read") {
const auto data=(kind=="qml_hw"&&!identity.hasQmlHw)?QByteArray():read(cmd,kind);auto value=decode(kind,data);
value.insert("project",QJsonObject{{"kind",kind=="qml_hw"?"qml":kind},{"source",value.value("source")},{"imports",value.value("imports")},{"fullscreen",kind=="qml"?identity.qmlAppFullscreen:kind=="qml_hw"?identity.qmlHwFullscreen:false}});return value;
}
if(method=="code_stats") {
LISP_STATS value;NativeCustom::wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::lispStatsRx,owner,[&,finish](LISP_STATS v){value=v;finish();});},[&]{cmd->lispGetStats(true);});
auto out=toolNumbers(value);QJsonObject bindings;for(const auto &v:value.number_bindings)bindings.insert(v.first,v.second);out.insert("bindings",bindings);return out;
}
if(method=="code_control") {
const auto command=req.value("command").toString();require(command=="start"||command=="stop"||command=="repl","Unknown Lisp control");
if(command!="stop")idle(cmd);
if(command!="repl"){running(cmd,command=="start");return {{"acknowledged",true},{"command",command}};}
const auto text=req.value("text").toString();require(!text.isEmpty()&&text.toUtf8().size()<=1024&&!text.contains(QChar(0)),"Invalid REPL request");
QString output;QObject owner;QEventLoop loop;QTimer timeout;timeout.setSingleShot(true);
QObject::connect(cmd,&Commands::lispPrintReceived,&owner,[&](QString line){if(output.toUtf8().size()<30000)output+=line.left(4096)+"\n";});
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);timeout.start(2000);cmd->lispSendReplCmd(text);loop.exec();
return {{"sent",true},{"acknowledged",false},{"output",output},{"command",command}};
}
require(method=="code_write","Unknown code operation");
const bool erase=req.value("erase").toBool();require(kind=="lisp"||kind=="qml","Hardware QML is read-only");
const auto desired=erase?QByteArray():image(req);
require(req.value("baseline").toString()==sha256(read(cmd,kind)),"Code changed after preview");
if(kind=="qml")require(req.value("baseline_fullscreen").toBool()==identity.qmlAppFullscreen,"QML flags changed after preview");idle(cmd);
bool ok=false;
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){auto reply=[&,finish](bool value){ok=value;finish();};if(kind=="lisp")QObject::connect(cmd,&Commands::lispEraseCodeRx,owner,reply);else QObject::connect(cmd,&Commands::eraseQmluiResReceived,owner,reply);},[&]{if(kind=="lisp")cmd->lispEraseCode(desired.size());else cmd->qmlUiErase(desired.size());},7000);
require(ok,"Code erase rejected");QElapsedTimer elapsed;elapsed.start();
for(int offset=0;offset<desired.size();offset+=384){
require(elapsed.elapsed()<60000,"Code upload deadline exceeded");bool acknowledged=false;
NativeCustom::wait([&](QObject *owner,std::function<void()> finish){auto reply=[&,finish](bool value,quint32 at){if(at!=quint32(offset))return;acknowledged=value;finish();};if(kind=="lisp")QObject::connect(cmd,&Commands::lispWriteCodeRx,owner,reply);else QObject::connect(cmd,&Commands::writeQmluiResReceived,owner,reply);},[&]{if(kind=="lisp")cmd->lispWriteCode(desired.mid(offset,384),offset);else cmd->qmlUiWrite(desired.mid(offset,384),offset);},2000);
require(acknowledged,"Code write rejected");
}
require(read(cmd,kind)==(erase?QByteArray():desired.mid(8)),"Code readback mismatch");
FW_RX_PARAMS after;require(Utility::getFwVersionBlocking(&vesc,&after,2000),"Code identity readback missing");requireSameCanIdentity(identity,after);
if(kind=="qml")require(after.hasQmlApp==!erase && (erase || after.qmlAppFullscreen==(quint8(desired[7])==2)),"QML flags readback differs");
// Upload never starts Lisp or creates a QML engine/view.
return {{"verified",true},{"running_requested",false}};
}
};
+141
View File
@@ -0,0 +1,141 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "config_export.h"
#include <cmath>
#include <QSet>
static QJsonValue configValue(const ConfigParam &p) {
switch (p.type) {
case CFG_T_DOUBLE: return p.valDouble;
case CFG_T_INT: case CFG_T_ENUM: case CFG_T_BITFIELD: return p.valInt;
case CFG_T_BOOL: return bool(p.valInt);
case CFG_T_QSTRING: return p.valString;
default: return QJsonValue();
}
}
static void validateEdit(const ConfigParam &p, const QJsonValue &v) {
if (p.type == CFG_T_BOOL) { require(v.isBool(), "Expected a boolean parameter"); return; }
if (p.type == CFG_T_QSTRING) {
require(v.isString() && v.toString().size() <= p.maxLen, "String parameter exceeds its native bound"); return;
}
require(v.isDouble() && std::isfinite(v.toDouble()), "Expected a finite number");
const double n = v.toDouble();
if (p.type == CFG_T_DOUBLE) require(n >= p.minDouble && n <= p.maxDouble, "Number outside native parameter bounds");
else {
require(std::trunc(n) == n && n >= -2147483648.0 && n <= 2147483647.0, "Expected a bounded integer");
if (p.type == CFG_T_ENUM) require(n >= 0 && n < p.enumNames.size(), "Unknown native enum value");
else if (p.type == CFG_T_BITFIELD) require(n >= 0 && n <= 255, "Invalid bitfield value");
else { require(p.type == CFG_T_INT, "Unsupported parameter type"); require(n >= p.minInt && n <= p.maxInt, "Integer outside native parameter bounds"); }
}
}
static void updateEdit(ConfigParams *config, const QString &name, const QJsonValue &v) {
require(config->hasParam(name), "Unknown parameter name");
const auto p = config->getParamCopy(name);
require(p.transmittable && config->getSerializeOrder().contains(name), "Parameter is not transmitted by this firmware");
validateEdit(p, v);
switch (p.type) {
case CFG_T_DOUBLE: config->updateParamDouble(name, v.toDouble()); break;
case CFG_T_INT: case CFG_T_BITFIELD: config->updateParamInt(name, v.toInt()); break;
case CFG_T_ENUM: config->updateParamEnum(name, v.toInt()); break;
case CFG_T_BOOL: config->updateParamBool(name, v.toBool()); break;
case CFG_T_QSTRING: config->updateParamString(name, v.toString()); break;
default: throw std::runtime_error("Unsupported parameter editor");
}
}
static QByteArray configPacket(ConfigParams *config, int code) {
VByteArray raw; raw.vbAppendInt8(code); config->serialize(raw); return raw;
}
static void loadExactConfig(ConfigParams *config, const QByteArray &packet, int code) {
const auto shape = configPacket(config, code);
require(packet.size() == shape.size() && packet.size() > 5 && quint8(packet[0]) == code,
"Configuration packet shape mismatch");
VByteArray raw(packet.mid(1));
require(config->deSerialize(raw) && raw.isEmpty(), "Native configuration decoder rejected payload");
require(configPacket(config, code) == packet, "Configuration packet is not byte-exact");
}
// Validate the flat value document before handing it to upstream setXML. Never
// import a parameter-definition/schema document or silently ignore unknown tags.
static void validateConfigXml(ConfigParams *config, const QString &xml, const QString &root) {
require(!xml.isEmpty() && xml.toUtf8().size() <= 32768, "XML exceeds import bound");
QXmlStreamReader reader(xml);
QSet<QString> seen;
int depth = 0; bool rooted = false;
while (!reader.atEnd()) {
const auto token = reader.readNext();
require(token != QXmlStreamReader::DTD && token != QXmlStreamReader::EntityReference,
"XML entities and DTD are not accepted");
if (token == QXmlStreamReader::StartElement) {
++depth;
if (depth == 1) { require(!rooted && reader.name() == root, "Wrong configuration XML root"); rooted = true; continue; }
require(depth == 2, "Nested XML values are not accepted");
const auto name = reader.name().toString();
if(name=="ConfigVersion" && config->getStoreConfigVersion()) {
require(!seen.contains(name),"Duplicate XML version");seen.insert(name);
require(reader.readElementText(QXmlStreamReader::ErrorOnUnexpectedElement)==QString::number(VT_CONFIG_VERSION),"XML configuration version differs");--depth;continue;
}
require(config->hasParam(name) && !seen.contains(name), "Unknown or duplicate XML parameter");
seen.insert(name);
const auto p = config->getParamCopy(name);
const auto text = reader.readElementText(QXmlStreamReader::ErrorOnUnexpectedElement);
require(!reader.hasError(), "Malformed XML parameter");
--depth;
bool ok = true;
if (p.type == CFG_T_QSTRING) {
if (p.transmittable) require(text.size() <= p.maxLen, "XML string exceeds parameter bound");
else require(text == p.valString, "XML changes non-transmitted metadata");
}
else if (p.type == CFG_T_BOOL) require(text == "0" || text == "1", "Invalid XML boolean");
else {
const auto n = text.toDouble(&ok);
require(ok && std::isfinite(n), "Invalid XML number");
if (p.type != CFG_T_DOUBLE) require(std::trunc(n) == n, "Invalid XML integer");
}
} else if (token == QXmlStreamReader::EndElement) --depth;
}
require(!reader.hasError() && rooted && depth == 0 && !seen.isEmpty(), "Incomplete configuration XML");
}
static QJsonObject prepareConfig(ConfigParams *before, const QJsonObject &source, int code, const QString &root) {
ConfigParams candidate; candidate = *before;
require(source.size() == 1, "One configuration source is required");
if (source.contains("changes")) {
require(source.value("changes").isObject(), "Changes must be an object");
const auto changes = source.value("changes").toObject();
require(changes.size() <= 512, "Too many changed parameters");
for (auto i = changes.begin(); i != changes.end(); ++i) updateEdit(&candidate, i.key(), i.value());
} else if (source.contains("xml")) {
require(source.value("xml").isString(), "XML must be a string");
const auto xml = source.value("xml").toString();
validateConfigXml(before, xml, root);
QXmlStreamReader reader(xml);
require(candidate.setXML(reader, root), "Upstream rejected XML configuration");
} else if (source.contains("payload")) {
const auto encoded = source.value("payload").toString().toLatin1();
const auto bytes = QByteArray::fromBase64(encoded, QByteArray::AbortOnBase64DecodingErrors);
require(bytes.toBase64() == encoded, "Invalid backup encoding");
loadExactConfig(&candidate, bytes, code);
} else throw std::runtime_error("Unsupported configuration source");
for (const auto &name : candidate.getParamOrder()) {
const auto p = candidate.getParamCopy(name);
if (configValue(p) == configValue(before->getParamCopy(name))) continue;
require(p.transmittable && candidate.getSerializeOrder().contains(name), "XML changes a non-transmitted value");
validateEdit(p, configValue(p));
}
const auto packet = configPacket(&candidate, code);
// Show actual representable values, including native wire quantization.
loadExactConfig(&candidate, packet, code);
QJsonArray changes;
for (const auto &name : candidate.getSerializeOrder()) {
const auto p = candidate.getParamCopy(name), old = before->getParamCopy(name);
if (configValue(p) != configValue(old)) changes.append(QJsonObject{
{"name", name}, {"title", p.longName}, {"before", configValue(old)}, {"after", configValue(p)},
{"suffix", p.suffix}, {"editor_scale", p.editorScale}});
}
return {{"before_sha256", sha256(configPacket(before, code))}, {"after_sha256", sha256(packet)},
{"payload", QString::fromLatin1(packet.toBase64())}, {"changes", changes}};
}
+100
View File
@@ -0,0 +1,100 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <functional>
#include "config_edit.h"
#include "bms_native.h"
#include <QElapsedTimer>
#include <QTimer>
#include <QtEndian>
// All protocol serialization/decoding remains in upstream Commands/ConfigParams.
// Replies are correlated by configuration index and exact offset; no write retry.
class NativeCustom {
public:
template<class Setup, class Send> static void wait(Setup setup, Send send, int ms=1800) {
QEventLoop loop; QTimer timeout; QObject owner; bool done=false;
timeout.setSingleShot(true);
std::function<void()> finish=[&] {done=true;loop.quit();};
setup(&owner,finish);
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);
timeout.start(ms);send();if(!done)loop.exec();
require(done,"Custom configuration reply timed out");
}
static void schema(ConfigParams &config,const QByteArray &compressed) {
require(compressed.size()>=5 && compressed.size()<=65536,"Custom schema size invalid");
const auto size=qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(compressed.constData()));
require(size>0 && size<=512*1024,"Custom schema decompression bound exceeded");
const auto xml=qUncompress(compressed);
require(xml.size()==int(size),"Custom schema compression invalid");
QXmlStreamReader scan(xml);int elements=0;
while(!scan.atEnd()){auto t=scan.readNext();require(t!=QXmlStreamReader::DTD && t!=QXmlStreamReader::EntityReference,"Custom schema entities forbidden");if(t==QXmlStreamReader::StartElement)require(++elements<=16000,"Custom schema too complex");}
require(!scan.hasError(),"Malformed custom schema");
require(config.loadCompressedParamsXml(compressed),"Upstream rejected custom schema");
require(config.getParamOrder().size()>0 && config.getParamOrder().size()<=512 && config.getSerializeOrder().size()<=512,"Custom parameter count invalid");
for(const auto &name:config.getSerializeOrder()) {
auto p=config.getParamCopy(name);
require(QRegularExpression("^[A-Za-z_][A-Za-z0-9_]{0,95}$").match(name).hasMatch(),"Custom parameter name invalid");
if(p.type==CFG_T_QSTRING)require(p.maxLen>=0 && p.maxLen<=1024,"Custom string size invalid");
require(p.enumNames.size()<=256,"Custom enum too large");
}
}
static QByteArray getSchema(Commands *cmd,int index) {
QByteArray data;int total=-1;QElapsedTimer elapsed;elapsed.start();
do {
require(elapsed.elapsed()<20000,"Custom schema read deadline");
const int offset=data.size(),amount=total<0?10:qMin(400,total-offset);
int receivedTotal=-1;QByteArray chunk;bool invalid=false;
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigChunkRx,owner,[&,finish](int id,int length,int at,QByteArray bytes){
if(id!=index || at!=offset)return;
invalid=length<1||length>65536||bytes.isEmpty()||bytes.size()>amount||at+bytes.size()>length||(total>=0&&length!=total);
receivedTotal=length;chunk=bytes;finish();
});},[&]{cmd->customConfigGetChunk(index,amount,offset);});
require(!invalid,"Custom schema fragment mismatch");total=receivedTotal;data.append(chunk);
}while(data.size()<total);
return data;
}
static QByteArray read(Commands *cmd,ConfigParams *config,int index,bool defaults=false) {
QByteArray bytes;
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigRx,owner,[&,finish](int id,QByteArray data){if(id==index){bytes=data;finish();}});},[&]{cmd->customConfigGet(index,defaults);});
require(bytes.size()>4 && bytes.size()<=16384,"Custom configuration size invalid");
// The adapter prefix is a local archive type tag; Commands owns the wire index.
QByteArray packet(1,char(COMM_GET_CUSTOM_CONFIG));packet.append(bytes);
loadExactConfig(config,packet,COMM_GET_CUSTOM_CONFIG);return packet;
}
static QJsonObject run(VescInterface &vesc,bool &remote,const QJsonObject &req) {
const auto method=req.value("method").toString();
const auto id=req.value("can_id"),ix=req.value("index");
require(id.isDouble()&&id.toDouble()==id.toInt(-1)&&id.toInt()>=0&&id.toInt()<=253,"Exact CAN address required");
require(ix.isDouble()&&ix.toDouble()==ix.toInt(-1)&&ix.toInt()>=0&&ix.toInt()<8,"Custom configuration index invalid");
NativeCanTarget route(vesc,remote,id.toInt());const auto target=route.identify();
require(bmsCommandsSupported(target) && ix.toInt()<target.customConfigNum,"BMS configuration profile unavailable");
const auto identity=canIdentity(target,id.toInt());
if(req.contains("target"))require(req.value("target").toObject()==identity,"BMS identity changed");
auto cmd=vesc.commands();
require(cmd->getLimitedCompatibilityCommands().contains(COMM_GET_CUSTOM_CONFIG_XML),"Transport does not support custom configuration");
const auto compressed=getSchema(cmd,ix.toInt());ConfigParams config;schema(config,compressed);
const auto before=read(cmd,&config,ix.toInt());
QJsonObject result{{"target",identity},{"index",ix},{"schema_sha256",sha256(compressed)},
{"schema",QString::fromLatin1(compressed.toBase64())},{"payload",QString::fromLatin1(before.toBase64())},
{"configuration",exportConfig(&config,before,"CustomConfiguration")}};
if(method=="custom_preview"||method=="custom_apply") {
require(req.value("schema_sha256").toString()==sha256(compressed) && req.value("baseline").toString()==sha256(before),"BMS configuration changed since read");
QJsonObject source=req.value("source").toObject();
if(req.value("defaults").toBool()) {ConfigParams defaults;defaults=config;source={{"payload",QString::fromLatin1(read(cmd,&defaults,ix.toInt(),true).toBase64())}};}
auto candidate=prepareConfig(&config,source,COMM_GET_CUSTOM_CONFIG,"CustomConfiguration");
result.insert("candidate",candidate);
if(method=="custom_apply") {
require(req.value("after_sha256")==candidate.value("after_sha256"),"BMS preview changed");
requireSameCanIdentity(target,route.identify());
const auto desired=QByteArray::fromBase64(candidate.value("payload").toString().toLatin1());
if(desired!=before) {
loadExactConfig(&config,desired,COMM_GET_CUSTOM_CONFIG);
wait([&](QObject *owner,std::function<void()> finish){QObject::connect(cmd,&Commands::customConfigAckReceived,owner,[=](int index){if(index==ix.toInt())finish();});},[&]{cmd->customConfigSet(ix.toInt(),&config);},3500);
require(read(cmd,&config,ix.toInt())==desired,"BMS configuration readback differs");
}
result.insert("verified",true);
}
}
requireSameCanIdentity(target,route.identify());return result;
}
};
+280 -12
View File
@@ -1,10 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Private per-device JSON process adapter. Every wire operation is upstream.
#include "config_export.h"
#include "config_edit.h"
#include "firmware_native.h"
#include "tools_native.h"
#include "bms_native.h"
#include "custom_native.h"
#include "code_native.h"
#include "package_native.h"
#include "engine_profile.h"
#include "sample_data.h"
#include "qml_broker.h"
#include <QEventLoop>
#include <QElapsedTimer>
#include <QSocketNotifier>
#include <QSerialPort>
#include <QTcpSocket>
#include <QTimer>
#include <QFileInfo>
#include <cmath>
@@ -27,6 +37,9 @@ public:
class Engine {
public:
VescInterface vesc;
FirmwareUpload firmwareUpload;
NativeSamples samples;
bool firmwareQualified = false;
Packet *packet;
FW_RX_PARAMS identity;
bool procedureRunning = false;
@@ -34,12 +47,34 @@ public:
QJsonObject procedure;
bool queryRunning = false;
bool allowHardware = false;
bool canBridge = false;
bool remoteQuery = false;
QByteArray lastMotor, lastApplication, lastHall;
QTimer outputWatchdog;
QElapsedTimer controlClock;
qint64 lastLease = -1, lastOutput = -1;
int watchdogTrips = 0, leaseCount = 0, outputCount = 0;
QString outputKind = "none";
QJsonObject controlDiagnostics() const {
const auto now = controlClock.elapsed();
return {{"watchdog_trips", watchdogTrips}, {"lease_count", leaseCount},
{"output_count", outputCount}, {"output_kind", outputKind},
{"lease_age_ms", lastLease < 0 ? -1 : now-lastLease},
{"output_age_ms", lastOutput < 0 ? -1 : now-lastOutput},
{"watchdog_active", outputWatchdog.isActive()}};
}
void recordOutput(const QString &kind) {
outputKind=kind; lastOutput=controlClock.elapsed(); ++outputCount;
}
Engine() {
controlClock.start();
samples.attach(vesc.commands());
vesc.setLoadQmlUiOnConnect(false);
vesc.setIgnoreCustomConfigs(true);
outputWatchdog.setSingleShot(true);
QObject::connect(&outputWatchdog, &QTimer::timeout, [&] {
++watchdogTrips; recordOutput("watchdog_release");
if (allowHardware && vesc.isPortConnected() && !procedureRunning) {
vesc.commands()->setCurrent(0);
try { flush(); } catch (...) {}
@@ -49,7 +84,7 @@ public:
packet = vesc.findChild<Packet *>();
require(packet, "Upstream packet transport missing");
QObject::connect(vesc.commands(), &Commands::fwVersionReceived,
[&](FW_RX_PARAMS value) { identity = value; });
[&](FW_RX_PARAMS value) { if(!remoteQuery) identity = value; });
QObject::connect(packet, &Packet::packetReceived, [&](QByteArray &raw) {
if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_MCCONF) lastMotor = raw;
if (!raw.isEmpty() && quint8(raw[0]) == COMM_GET_APPCONF) lastApplication = raw;
@@ -57,6 +92,19 @@ public:
});
}
void openCan(int port) {
require(port > 0 && port <= 65535, "Invalid private bridge port");
canBridge = true;
vesc.connectTcp("127.0.0.1", port);
QElapsedTimer timer; timer.start();
while (!vesc.isPortConnected() && timer.elapsed() < 1500)
QCoreApplication::processEvents(QEventLoop::AllEvents, 5);
require(vesc.isPortConnected(), "Private CAN bridge did not connect");
allowHardware = true;
query(COMM_FW_VERSION, 3000);
firmwareQualified = nativeFirmwareQualified(identity.major, identity.minor, identity.hwType, identity.isTestFw, identity.customConfigNum);
}
void open(const QString &port) {
require(QRegularExpression("^/dev/ttyACM[0-9]+$").match(port).hasMatch(), "Unsupported USB path");
struct stat st;
@@ -70,9 +118,7 @@ public:
"Serial port is already owned");
allowHardware = true;
query(COMM_FW_VERSION, 3000);
require(identity.major == 5 && identity.minor == 2 && identity.hwType == HW_TYPE_VESC
&& identity.isTestFw == 0 && identity.customConfigNum == 0,
"Native hardware acceptance currently admits stable FW 5.02 only");
firmwareQualified = nativeFirmwareQualified(identity.major, identity.minor, identity.hwType, identity.isTestFw, identity.customConfigNum);
}
QByteArray exchange(int command, int timeoutMs, const std::function<void()> &send) {
@@ -155,6 +201,38 @@ public:
return raw;
}
QJsonObject diagnostic(const QString &command) {
require(QStringList{"hw_status", "faults", "fault", "ping", "mem", "threads", "rpm", "tacho", "volt", "uptime", "help"}.contains(command), "Unsupported diagnostic command");
require(allowHardware && vesc.isPortConnected() && !procedureRunning && !queryRunning,
"Diagnostic unavailable during another operation");
queryRunning = true;
struct Reset { bool &flag; ~Reset() { flag = false; } } reset{queryRunning};
QEventLoop loop;
QTimer deadline, quiet;
deadline.setSingleShot(true); quiet.setSingleShot(true);
QObject observer;
QStringList lines;
int bytes = 0;
bool overflow = false, timedOut = false;
QObject::connect(vesc.commands(), &Commands::printReceived, &observer, [&](QString text) {
bytes += text.toUtf8().size();
if (bytes > 32768 || lines.size() >= 512) { overflow = true; loop.quit(); return; }
lines.append(text);
quiet.start(200);
});
QObject::connect(&deadline, &QTimer::timeout, &observer, [&] { timedOut = true; loop.quit(); });
QObject::connect(&quiet, &QTimer::timeout, &observer, [&] { loop.quit(); });
deadline.start(3000);
// Match the upstream Terminal page. FW 5.02 routes print packets through
// the blocking-command reply callback; SYNC does not establish it.
vesc.commands()->sendTerminalCmd(command);
flush();
loop.exec();
require(!overflow && !timedOut && !lines.isEmpty(), "Incomplete diagnostic response");
return {{"command", command}, {"text", lines.join("\n")},
{"completion", "200ms-print-quiescence"}};
}
QByteArray configurationPacket(ConfigParams *config, int code) {
VByteArray raw; raw.vbAppendInt8(code); config->serialize(raw); return raw;
}
@@ -241,6 +319,23 @@ public:
}
void flush() {
if (canBridge) {
// A TCP write alone cannot confirm SDK acceptance. This private
// FIFO marker is acknowledged only after preceding CAN sends.
bool acknowledged = false;
QEventLoop loop; QTimer timer; timer.setSingleShot(true);
QObject observer;
const QByteArray marker = QByteArray::fromHex("ff4d434252");
QObject::connect(packet, &Packet::packetReceived, &observer, [&](QByteArray &data) {
if (data == marker) { acknowledged = true; loop.quit(); }
});
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
QByteArray request = marker; packet->sendPacket(request);
timer.start(60);
if (!acknowledged) loop.exec();
require(acknowledged && vesc.isPortConnected(), "CAN write not confirmed");
return;
}
auto serial = vesc.findChild<QSerialPort *>();
require(serial && serial->isOpen(), "Serial transport closed");
serial->flush();
@@ -250,18 +345,65 @@ public:
QJsonObject dispatch(const QJsonObject &request) {
const auto method = request.value("method").toString();
if (method == "engine") return {{"version", "7.00"}, {"commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"},
{"connected", vesc.isPortConnected()}, {"hardware_enabled", allowHardware},
if (method == "engine") return {{"version", QString::number(VT_VERSION, 'f', 2)},
{"commit", engineProfile().value("upstream").toObject().value("commit")},
{"contract", engineProfile().value("contract")},
{"connected", vesc.isPortConnected()}, {"hardware_enabled", allowHardware}, {"firmware_admitted", firmwareQualified},
{"legacy_power_loss_correction", vesc.commands()->getMaxPowerLossBug()}};
require(allowHardware && vesc.isPortConnected(), "Native device is not connected");
if (method == "package_unpack") return NativePackage::inspect(request);
if (method == "code_pack") {const auto data=NativeCode::pack(request.value("project").toObject());return {{"image",QString::fromLatin1(data.toBase64())},{"sha256",sha256(data)},{"bytes",data.size()}};}
require(allowHardware, "Native hardware operations are disabled");
if (method == "firmware_status") return firmwareUpload.state;
if (method == "firmware_cancel") {
require(firmwareUpload.running, "No active upload");
firmwareUpload.cancel(vesc); return {{"cancel_requested", true}};
}
require(!firmwareUpload.running, "Firmware upload owns this controller");
require(!remoteQuery, "CAN target operation owns this controller");
require(vesc.isPortConnected(), "Native device is not connected");
if (method == "sample_start" || method == "sample_status" || method == "sample_fetch" || method == "sample_stop" || method == "sample_read") {
require(firmwareQualified && identity.major==5 && identity.minor==2,"Sample Data profile unsupported");
if(method=="sample_start" && (procedureRunning || procedureUncertain))
return {{"accepted",false},{"reason","Motor measurement is active"}};
auto result=samples.run(method,request);
if(method=="sample_start" || method=="sample_stop" || method=="sample_fetch")flush();
return result;
}
if(samples.active() && QStringList{"firmware_start","firmware_target","firmware_snapshot","custom_read","custom_preview","custom_apply","bms_read","configuration_apply","foc_start","hall_start","code_write","code_control","bms_command"}.contains(method))
throw std::runtime_error("Stop Sample Data before changing the controller");
if (method == "code_snapshot" || method == "code_read" || method == "code_write" || method == "code_control" || method == "code_stats") {
require(!queryRunning && !procedureRunning && !procedureUncertain && !outputWatchdog.isActive(), "Controller operation already active");
query(COMM_FW_VERSION,2000);const auto before=identity;
auto result=NativeCode::run(vesc,identity,request);
query(COMM_FW_VERSION,2000);requireSameCanIdentity(before,identity);return result;
}
// Unknown firmware is identity-only, so a post-update UUID/version can
// be observed without silently admitting an unqualified config schema.
if (!firmwareQualified) {
require(method == "query" && request.value("command").toInt(-1) == COMM_FW_VERSION,
"Firmware supports identification only in this engine release");
}
if (method == "qml_read") {
require(!procedureRunning&&!procedureUncertain&&!samples.active()&&!outputWatchdog.isActive(),"Controller is busy");
auto intent=request.value("intent").toObject();validateQmlRead(intent);
int code=intent.value("command").toInt();auto cmd=vesc.commands();
require(qmlReadSupported(cmd,code),"QML read unsupported by firmware");
QByteArray raw;
if(code==32)raw=exchange(code,1000,[=]{cmd->getDecodedAdc();});
else if(code==33)raw=exchange(code,1000,[=]{cmd->getDecodedChuk();});
else if(code==65)raw=exchange(code,1000,[=]{cmd->getImuData(intent.value("mask").toInt());});
else if(code==96)raw=exchange(code,1000,[=]{cmd->bmsGetValues();});
else raw=query(code,1000);
return {{"payload",QString::fromLatin1(raw.toBase64())}};
}
if (method == "query") return {{"payload", QString::fromLatin1(query(
int(number(request, "command", 0, 255)), int(number(request, "timeout_ms", 20, 8000))).toBase64())}};
if (method == "procedure_result") return {{"running", procedureRunning}, {"uncertain", procedureUncertain}, {"result", procedure}};
if (method == "lease") {
require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller");
vesc.commands()->disableAppOutput(250, false); flush(); outputWatchdog.start(200); return {};
vesc.commands()->disableAppOutput(250, false); flush(); lastLease=controlClock.elapsed(); ++leaseCount; outputWatchdog.start(200); return {};
}
if (method == "release") { vesc.commands()->setCurrent(0); flush(); return {}; }
if (method == "release") { vesc.commands()->setCurrent(0); flush(); recordOutput("release"); return {}; }
require(!procedureRunning && !procedureUncertain, "Native procedure owns this controller");
if (method == "current") {
require(outputWatchdog.isActive(), "Output lease expired");
@@ -270,6 +412,29 @@ public:
vesc.commands()->setCurrent(current); flush(); return {};
}
if (method == "rpm") { require(outputWatchdog.isActive(), "Output lease expired"); vesc.commands()->setRpm(int(number(request, "erpm", -3000, 3000))); flush(); return {}; }
if (method == "duty" || method == "duty_limited") {
require(outputWatchdog.isActive(), "Output lease expired");
require(!lastMotor.isEmpty() && !lastApplication.isEmpty(), "Read configurations before driving");
auto mc = vesc.mcConfig();
require(vesc.appConfig()->getParamEnum("app_ppm_conf.ctrl_type") == 4, "PPM Duty Cycle profile required");
const auto limit = mc->getParamDouble("l_max_duty");
require(std::isfinite(limit) && limit > 0 && limit <= 1, "Invalid configured duty limit");
const auto current = mc->getParamDouble("l_current_max") * mc->getParamDouble("l_current_max_scale");
const auto braking = -mc->getParamDouble("l_current_min") * mc->getParamDouble("l_current_min_scale");
// Legacy duty RPC retains its original bounded contract. Remote
// driving supplies the operator's request end to end, and may
// only use scales within the controller's configured envelope.
const auto requested = method == "duty" ? 30.0 : request.value("current_a").toDouble(-1);
require(std::isfinite(requested) && requested >= .5, "Invalid requested current ceiling");
for (const auto &key : {"l_current_max_scale", "l_current_min_scale"})
require(mc->getParamDouble(key) > 0 && mc->getParamDouble(key) <= 1, "Invalid configured current scale");
require(std::isfinite(current) && current > 0 && current <= requested + .001 &&
std::isfinite(braking) && braking > 0 && braking <= requested + .001, "Apply the requested current ceiling first");
auto duty = number(request, "duty", -limit, limit);
if (method == "duty" && std::abs(duty) < 0.00001) vesc.commands()->setCurrent(0);
else vesc.commands()->setDutyCycle(duty);
flush(); recordOutput("duty"); return {};
}
if (method == "limits") {
auto p = request.value("parameters").toObject();
MCCONF_TEMP conf;
@@ -289,12 +454,111 @@ public:
});
require(ack.size() == 1, "Invalid native limits ACK"); return {};
}
if (method == "firmware_start") {
require(!outputWatchdog.isActive(), "Output lease is active");
query(COMM_FW_VERSION, 2000);
return firmwareUpload.start(vesc, request, identity, remoteQuery);
}
if (method == "firmware_target" || method == "firmware_snapshot" || (method == "firmware_begin" && request.contains("can_id"))) {
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
const double id=number(request,"can_id",0,253);require(id==int(id),"Integral CAN address required");
NativeCanTarget route(vesc,remoteQuery,int(id));const auto target=route.identify();
const bool admitted=nativeFirmwareQualified(target.major,target.minor,target.hwType,target.isTestFw,target.customConfigNum);
if(method=="firmware_target")return {{"target",canIdentity(target,int(id))},{"admitted",admitted}};
require(admitted,"CAN firmware schema not qualified");
if(method=="firmware_begin")return firmwareUpload.stage(method,request,target);
require(request.value("target").toObject()==canIdentity(target,int(id)),"CAN target changed since selection");
// Decode with the admitted schema, then restore local configuration
// and packet baselines even on a failed remote read.
ConfigParams mc,app;mc=*vesc.mcConfig();app=*vesc.appConfig();
struct Restore { Engine &e;ConfigParams &mc,&app;QByteArray motor,application;
~Restore(){*e.vesc.mcConfig()=mc;*e.vesc.appConfig()=app;e.lastMotor=motor;e.lastApplication=application;}
} restore{*this,mc,app,lastMotor,lastApplication};
QJsonObject packets;
for(int code:{COMM_GET_MCCONF,COMM_GET_APPCONF,COMM_GET_VALUES,COMM_GET_DECODED_PPM})
packets.insert(QString::number(code),QString::fromLatin1(query(code,2000).toBase64()));
requireSameCanIdentity(target,route.identify());
return {{"target",canIdentity(target,int(id))},{"packets",packets}};
}
if (method == "firmware_begin" || method == "firmware_chunk" || method == "firmware_seal")
return firmwareUpload.stage(method, request, identity);
if (method == "custom_read" || method == "custom_preview" || method == "custom_apply") {
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
require(QStringList{"custom_read","custom_preview","custom_apply"}.contains(method), "Unknown custom operation");
return NativeCustom::run(vesc,remoteQuery,request);
}
if (method == "bms_read" || method == "bms_command") {
require(!queryRunning && !outputWatchdog.isActive(), "Controller operation already active");
const double idNumber=number(request,"can_id",0,253);
require(idNumber==int(idNumber),"Integral CAN address required");
const int id=int(idNumber);
NativeCanTarget route(vesc,remoteQuery,id);
const auto target=route.identify();
const auto targetJson=canIdentity(target,id);
if(method == "bms_read") {
if(target.hwType!=HW_TYPE_VESC_BMS)
return {{"state","not_bms"},{"target",targetJson},{"commands_supported",false}};
auto value=readNativeTool(vesc,"bms");
requireSameCanIdentity(target,route.identify());
if(bmsCommandsSupported(target) && value.value("state")=="received")
require(value.value("values").toObject().value("can_id").toInt(-1)==id,"BMS reply CAN address differs");
value.insert("target",targetJson);
value.insert("source","direct_can");
value.insert("commands_supported",bmsCommandsSupported(target));
return value;
}
require(bmsCommandsSupported(target),"BMS firmware control profile unsupported");
require(request.value("target").toObject()==targetJson,"BMS target changed after preview");
bool emitted=false; QObject observer;
QObject::connect(vesc.commands(),&Commands::dataToSend,&observer,[&](QByteArray &raw){
if(raw.size()>=3 && quint8(raw[0])==COMM_FORWARD_CAN && quint8(raw[1])==id)emitted=true;
});
sendBmsCommand(vesc.commands(),request.value("command").toString());
require(emitted,"BMS command not emitted");flush();
return {{"sent",true},{"acknowledged",false},{"target",targetJson}};
}
if (method == "device_tool") return readNativeTool(vesc, request.value("tool").toString());
if (method == "diagnostic") return diagnostic(request.value("command").toString());
if (method == "configuration") {
auto motor = query(COMM_GET_MCCONF, 2000);
auto application = query(COMM_GET_APPCONF, 2000);
return {{"motor", exportConfig(vesc.mcConfig(), motor, "MCConfiguration")},
{"application", exportConfig(vesc.appConfig(), application, "APPConfiguration")}};
}
if (method == "configuration_preview") {
query(COMM_GET_MCCONF, 2000); query(COMM_GET_APPCONF, 2000);
const auto sources = request.value("sources").toObject();
require(!sources.isEmpty() && sources.size() <= 2, "Configuration source is empty");
QJsonObject result;
for (auto i = sources.begin(); i != sources.end(); ++i) {
require(i.key() == "motor" || i.key() == "application", "Invalid configuration kind");
const bool motor = i.key() == "motor";
result.insert(i.key(), prepareConfig(motor ? vesc.mcConfig() : vesc.appConfig(), i.value().toObject(),
motor ? COMM_GET_MCCONF : COMM_GET_APPCONF, motor ? "MCConfiguration" : "APPConfiguration"));
}
return {{"configs", result}, {"baseline", QJsonObject{{"motor", sha256(lastMotor)}, {"application", sha256(lastApplication)}}}};
}
if (method == "configuration_apply") {
const auto kind = request.value("kind").toString();
require(kind == "motor" || kind == "application", "Invalid configuration kind");
const bool motor = kind == "motor";
const int get = motor ? COMM_GET_MCCONF : COMM_GET_APPCONF;
const int set = motor ? COMM_SET_MCCONF : COMM_SET_APPCONF;
const auto actual = query(get, 2000);
require(sha256(actual) == request.value("before_sha256").toString(), "Configuration changed since preview");
auto config = motor ? vesc.mcConfig() : vesc.appConfig();
const auto candidate = prepareConfig(config, {{"payload", request.value("payload")}}, get,
motor ? "MCConfiguration" : "APPConfiguration");
const auto desired = QByteArray::fromBase64(candidate.value("payload").toString().toLatin1());
require(candidate.value("after_sha256") == request.value("after_sha256"), "Preview content changed");
if (actual == desired) return {{"verified", true}, {"changed", false}};
loadExactConfig(config, desired, get);
require(exchange(set, 3000, [&] {
if (motor) vesc.commands()->setMcconf(false); else vesc.commands()->setAppConf();
}).size() == 1, "Configuration write acknowledgement invalid");
require(query(get, 3000) == desired, "Written configuration differs from preview");
return {{"verified", true}, {"changed", true}};
}
if (method == "foc_start") {
const auto loss = number(request, "max_power_loss_w", 10, 150);
require(!lastMotor.isEmpty() && !lastApplication.isEmpty(), "Read configurations before calibration");
@@ -335,7 +599,10 @@ int main(int argc, char **argv) {
require(argc == 2, "One exact serial port or --offline argument is required");
Engine engine;
const QString port = QString::fromLocal8Bit(argv[1]);
if (port != "--offline") engine.open(port);
if (port.startsWith("--can-bridge=")) {
bool valid = false; int number = port.mid(13).toInt(&valid);
require(valid, "Invalid private CAN bridge argument"); engine.openCan(number);
} else if (port != "--offline") engine.open(port);
QFile output; output.open(stdout, QIODevice::WriteOnly);
auto write = [&](const QJsonObject &value) {
output.write(QJsonDocument(value).toJson(QJsonDocument::Compact) + '\n'); output.flush();
@@ -349,7 +616,7 @@ int main(int argc, char **argv) {
if (size == 0) { application.quit(); return; }
if (size < 0) return;
buffer.append(chunk, int(size));
if (buffer.size() > 65536) { application.exit(2); return; }
if (buffer.size() > 2*1024*1024) { application.exit(2); return; }
int end;
while ((end = buffer.indexOf('\n')) >= 0) {
auto raw = buffer.left(end); buffer.remove(0, end + 1);
@@ -364,6 +631,7 @@ int main(int argc, char **argv) {
response.insert("ok", false); response.insert("error", e.what());
response.insert("diagnostics", e.diagnostics);
} catch (const std::exception &e) { response.insert("ok", false); response.insert("error", e.what()); }
response.insert("control", engine.controlDiagnostics());
write(response);
}
});
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "config_export.h"
#include <QtEndian>
// Transport/file bounds and STM32 vector sanity, not a signature or a board-ID
// proof. Hardware and target version remain operator declarations for raw BIN.
static QJsonObject inspectFirmwareImage(const QByteArray &raw, const QString &kind) {
require(kind == "firmware" || kind == "bootloader", "Unknown image kind");
const int bound = kind == "bootloader" ? 65536 : 2 * 1024 * 1024;
require(raw.size() >= 256 && raw.size() <= bound, "Image size outside the supported bound");
// This upload profile accepts raw STM32 BIN only. Encoded/compressed/Intel
// HEX files must be deliberately converted by their owning Tool first.
const auto sp = qFromLittleEndian<quint32>(raw.constData());
const auto reset = qFromLittleEndian<quint32>(raw.constData() + 4);
require(sp >= 0x20000000 && sp <= 0x20040000 && (sp & 3) == 0,
"Raw STM32 image has an invalid initial stack pointer");
require((reset & 1) && reset >= 0x08000001 && reset < 0x08200000,
"Raw STM32 image has an invalid reset vector");
// fwUpload owns normalization. Require that it leaves this raw image intact
// so the reviewed hash describes exactly the bytes passed to the uploader.
require(Packet::crc16(reinterpret_cast<const unsigned char *>(raw.constData()+6), raw.size()-6) != qFromBigEndian<quint16>(raw.constData()+4), "Wrapped firmware is not a raw BIN image");
return {{"kind", kind}, {"bytes", raw.size()}, {"sha256", sha256(raw)},
{"format", "raw-stm32-bin"}, {"board_identity_embedded", false}};
}
+101
View File
@@ -0,0 +1,101 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "firmware_source.h"
#include "bms_native.h"
#include "swd_native.h"
#include <memory>
#include <QElapsedTimer>
#include <QTimer>
class FirmwareUpload {
QByteArray image;
QJsonObject manifest;
QElapsedTimer age;
bool sealed = false;
public:
bool running = false;
bool consumed = false;
bool cancelRequested = false;
void cancel(VescInterface &v){cancelRequested=true;v.fwUploadCancel();v.swdCancel();}
QJsonObject state{{"state", "empty"}, {"progress", 0}};
QJsonObject stage(const QString &method, const QJsonObject &p, const FW_RX_PARAMS &identity) {
require(!running, "Firmware upload owns the controller");
if (method == "firmware_begin") {
require(!p.contains("swd") || (!p.contains("can_id") && p.value("kind")=="firmware"), "SWD cannot share a CAN route or bootloader mode");
require(p.value("hardware").toString() == identity.hw && identity.hwType == HW_TYPE_VESC,
"Declared hardware does not match this controller");
require(p.value("uuid").toString().toLower() == QString::fromLatin1(identity.uuid.toHex()),
"Firmware target UUID changed");
const int size = p.value("bytes").toInt(-1);
const auto format = p.value("format").toString("bin");
require(format == "bin" || format == "hex", "Unsupported image format");
require(size >= (format == "hex" ? 32 : 256) && size <= (format == "hex" ? 8 : 2) * 1024 * 1024, "Image size outside bound");
require(QRegularExpression("^[0-9a-f]{64}$").match(p.value("sha256").toString()).hasMatch(), "Invalid image digest");
require(p.value("kind") == "firmware" || p.value("kind") == "bootloader", "Invalid image kind");
image.clear(); manifest = p; sealed = consumed = false; age.start();
state = {{"state", "staging"}, {"progress", 0}};
return {{"offset", 0}};
}
require(age.isValid() && age.elapsed() < 600000 && !consumed, "Staged image expired or consumed");
if (method == "firmware_chunk") {
require(!sealed && p.value("offset").toInt(-1) == image.size(), "Image offset changed");
const auto text = p.value("data").toString().toLatin1();
const auto data = QByteArray::fromBase64(text);
require(data.toBase64() == text && !data.isEmpty() && data.size() <= 32768,
"Invalid image chunk");
require(image.size() + data.size() <= manifest.value("bytes").toInt(), "Image exceeds declared size");
image.append(data); return {{"offset", image.size()}};
}
require(method == "firmware_seal", "Unknown staging operation");
require(image.size() == manifest.value("bytes").toInt() && sha256(image) == manifest.value("sha256").toString(),
"Image size or digest changed");
const auto range=manifest.contains("swd")?swdRange(manifest.value("swd").toObject()):QPair<quint32,int>{0,0};
auto source = inspectFirmwareSource(image, manifest.value("kind").toString(), manifest.value("format").toString("bin"),range.first,range.second);
image = source.image;
auto info = source.info;
manifest.insert("sha256", info.value("sha256"));
manifest.insert("bytes", image.size());
sealed = true; state = {{"state", "ready"}, {"progress", 0}};
return info;
}
QJsonObject start(VescInterface &vesc, const QJsonObject &p, const FW_RX_PARAMS &identity, bool &remoteQuery) {
require(!running && !consumed && sealed && age.elapsed() < 600000, "No fresh sealed image");
std::shared_ptr<NativeCanTarget> route;
FW_RX_PARAMS target=identity;
if(manifest.contains("can_id")) {
route=std::make_shared<NativeCanTarget>(vesc,remoteQuery,manifest.value("can_id").toInt(-1));
target=route->identify();
require(nativeFirmwareQualified(target.major,target.minor,target.hwType,target.isTestFw,target.customConfigNum),"CAN firmware schema not qualified");
}
require(p.value("sha256") == manifest.value("sha256") && manifest.value("hardware") == target.hw &&
manifest.value("uuid") == QString::fromLatin1(target.uuid.toHex()), "Firmware target changed");
cancelRequested=false;consumed = running = true; state = {{"state", "uploading"}, {"progress", 0}};
// The original upload runs nested Qt event loops; the private input
// notifier remains available for status/cancel only. No second owner.
QTimer::singleShot(0, [&vesc, this, route] {
QTimer bound; bound.setSingleShot(true);
QObject::connect(&bound, &QTimer::timeout, [&] { cancel(vesc); });
QObject observer;
QObject::connect(&vesc, &VescInterface::fwUploadStatus, &observer,
[&](const QString &message, double progress, bool) {
state.insert("message", message.left(512));
state.insert("progress", qBound(0.0, progress, 1.0));
});
bound.start(240000);
bool ok = false;
try {
require(!cancelRequested,"Upload cancelled before start");
if(manifest.contains("swd")) {
const auto result=uploadSwd(vesc,manifest.value("swd").toObject(),image,cancelRequested);
for(auto i=result.begin();i!=result.end();++i)state.insert(i.key(),i.value());ok=true;
} else ok = vesc.fwUpload(image, manifest.value("kind") == "bootloader", false, true, false);
}
catch (...) { state.insert("message", "Upload exception; outcome unknown"); }
image.clear(); sealed = false; running = false;
state.insert("state", ok ? "uploaded" : "unknown");
state.insert("upload_confirmed", ok);
if (ok) state.insert("progress", 1);
});
return state;
}
};
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "firmware_image.h"
#include "hexfile.h"
#include <QTemporaryFile>
#include <QMap>
#include <algorithm>
struct FirmwareSource { QByteArray image; QJsonObject info; };
// Validate the container strictly before passing it to the original HexFile
// reader. In particular, upstream's permissive fromHex must not silently omit
// junk, duplicate addresses, out-of-order overlapping records or sparse bombs.
static FirmwareSource inspectFirmwareSource(const QByteArray &source, const QString &kind, const QString &format, quint32 swdBase=0, int swdLimit=0) {
require(format == "bin" || format == "hex", "Use BIN or Intel HEX");
require(source.size() >= (format == "hex" ? 32 : 256) && source.size() <= (format == "hex" ? 8 : 2) * 1024 * 1024,
"Source file exceeds its bound");
QByteArray image = source;
quint32 base = swdLimit ? swdBase : kind == "bootloader" ? 0x080E0000 : 0x08000000;
const int limit=swdLimit ? swdLimit : kind == "bootloader" ? 65536 : 2*1024*1024;
require(limit>0 && limit<=2*1024*1024,"Invalid flash span");
int segments = 1;
if (format == "hex") {
QMap<quint32,quint32> ranges;
quint32 offset = 0; bool eof = false; int count = 0;
for (auto line : source.split('\n')) {
if (line.endsWith('\r')) line.chop(1);
if (line.isEmpty()) continue;
require(!eof && ++count <= 131074 && line.size() <= 521,
"HEX has trailing records or too many records");
require(QRegularExpression("^:[0-9A-Fa-f]+$").match(QString::fromLatin1(line)).hasMatch()
&& line.size() % 2 == 1, "Invalid HEX characters");
const auto record = QByteArray::fromHex(line.mid(1));
require(record.size() >= 5 && record.size() == 5 + quint8(record[0]), "Invalid HEX record length");
unsigned sum = 0; for (unsigned char c : record) sum += c;
require((sum & 255) == 0, "Invalid HEX checksum");
const int length = quint8(record[0]), type = quint8(record[3]);
const quint32 address = (quint8(record[1]) << 8) | quint8(record[2]);
if (type == 0) {
require(length > 0 && address + length <= 65536, "HEX record crosses address window");
// HexFile uses OR for these parts. Reject ambiguous segment
// combinations rather than reinterpret the upstream output.
require((offset & address) == 0, "Ambiguous HEX segment address");
const quint64 start = quint64(offset) + address, end = start + length;
require(start >= base && end <= quint64(base) + limit,
"HEX address does not belong to the selected image kind");
auto next = ranges.lowerBound(quint32(start));
require(next == ranges.end() || next.key() >= end, "Overlapping HEX records");
if (next != ranges.begin()) { auto prev = next; --prev; require(prev.value() <= start, "Overlapping HEX records"); }
ranges.insert(quint32(start), quint32(end));
} else if (type == 1) {
require(length == 0 && address == 0, "Invalid HEX EOF"); eof = true;
} else if (type == 2 || type == 4) {
require(length == 2 && address == 0, "Invalid HEX address record");
offset = quint32((quint8(record[4]) << 8) | quint8(record[5])) << (type == 2 ? 4 : 16);
} else if (type == 3 || type == 5) {
require(length == 4 && address == 0, "Invalid HEX entry point");
} else require(false, "Unsupported HEX record type");
}
require(eof && !ranges.isEmpty() && ranges.firstKey() == base, "HEX is truncated or has the wrong base address");
QTemporaryFile file;
require(file.open() && file.write(source) == source.size() && file.flush(), "Cannot inspect HEX source");
QMap<quint32,QByteArray> blocks;
require(HexFile::parseFile(file.fileName(), blocks) && !blocks.isEmpty(), "Original VESC Tool rejected HEX");
const auto size = quint64(ranges.last()) - base;
require(size >= 256 && size <= limit, "HEX span exceeds bound");
image = QByteArray(int(size), char(0xFF)); segments = blocks.size();
quint64 sourceBytes = 0, parsedBytes = 0;
for (auto it=ranges.begin();it!=ranges.end();++it) sourceBytes += it.value()-it.key();
for (auto it=blocks.begin();it!=blocks.end();++it) {
require(it.key() >= base && quint64(it.key())+it.value().size() <= quint64(base)+size,
"Original HEX reader returned an invalid address");
std::copy(it.value().begin(), it.value().end(), image.begin()+int(it.key()-base)); parsedBytes += it.value().size();
}
require(parsedBytes == sourceBytes, "Original HEX reader changed the data coverage");
}
require(image.size()<=limit,"Image exceeds selected flash span");
auto info = swdLimit ? QJsonObject{{"sha256",sha256(image)},{"bytes",image.size()}} : inspectFirmwareImage(image, kind);
info.insert("source_format", format); info.insert("source_bytes", source.size());
info.insert("source_sha256", sha256(source)); info.insert("base_address", double(base));
info.insert("segments", segments);
return {image, info};
}
+97 -6
View File
@@ -1,7 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Mission Core adapter to the unmodified VESC Tool engine. No hardware transport
// is admitted by this executable. Input is one archived snapshot on stdin.
#include "config_export.h"
#include "config_edit.h"
#include "firmware_source.h"
#include "bms_native.h"
#include "swd_native.h"
#include "code_native.h"
#include "package_native.h"
#include "engine_profile.h"
#include "sample_data.h"
#include "qml_broker.h"
#include <QEventLoop>
int main(int argc, char **argv) {
// This application never calls connectSerial/connectTcp/connectBle or starts
@@ -11,13 +20,14 @@ int main(int argc, char **argv) {
QCoreApplication::setOrganizationName("MissionCore");
QCoreApplication::setApplicationName("VescToolOfflineAdapter");
QJsonObject result{{"schema", "missioncore.vesc.native-offline/v1"},
{"upstream_commit", "01d5f10901116c311e3fb84d5a1541f663d3ce20"},
{"upstream_commit", engineProfile().value("upstream").toObject().value("commit")},
{"upstream_version", QString::number(VT_VERSION, 'f', 2)},
{"hardware_access", false}};
try {
require(argc == 1, "No command-line transport or operation arguments are accepted");
QFile input; require(input.open(stdin, QIODevice::ReadOnly), "Cannot read input");
const auto raw = input.read(1024 * 1024 + 1);
QByteArray raw;
while(raw.size()<=1024*1024){const auto part=input.read(4096);if(part.isEmpty())break;raw.append(part);}
require(!raw.isEmpty() && raw.size() <= 1024 * 1024, "Archive input is empty or too large");
QJsonParseError parse;
auto document = QJsonDocument::fromJson(raw, &parse);
@@ -33,15 +43,21 @@ int main(int argc, char **argv) {
const auto uuid = identity.value("uuid").toString();
require(QRegularExpression("^[0-9a-fA-F]{24}$").match(uuid).hasMatch(), "Invalid archived UUID");
fw.uuid = QByteArray::fromHex(uuid.toLatin1());
require(fw.major == 5 && fw.minor == 2 && fw.isTestFw == 0 && fw.customConfigNum == 0
&& identity.value("hardware_type").toInt(-1) == 0,
"Offline acceptance currently admits stable firmware 5.02 only");
require(nativeFirmwareQualified(fw.major, fw.minor, identity.value("hardware_type").toInt(-1), fw.isTestFw, fw.customConfigNum),
"Firmware archive is not admitted by this engine release profile");
VescInterface vesc;
require(Utility::configLoadLatest(&vesc), "Bundled upstream configuration resources missing");
auto *commands = vesc.commands();
// Replay the archived identity through the real firmware negotiation
// signal. The real engine selects bundled schemas and compatibility.
commands->fwVersionReceived(fw);
for(int code=0;code<256;++code) {
QByteArray raw(1,char(code));if(code==65)raw.append(QByteArray::fromHex("01ff"));
auto intent=qmlReadIntent(raw);require(intent.isEmpty()!=qmlReadCode(code),"Read classifier failed");
if(!intent.isEmpty()){validateQmlRead(intent);require(qmlReadSupported(commands,code),"Qualified firmware read rejected");}
raw.append(char(0));require(qmlReadIntent(raw).isEmpty(),"Read classifier accepted trailing data");
}
require(!vesc.isPortConnected(), "Offline adapter unexpectedly connected");
require(vesc.mcConfig()->getSerializeOrder().size() > 0, "Native schema not selected");
bool failed = false;
@@ -82,6 +98,81 @@ int main(int argc, char **argv) {
commands->setRpm(-3000);
require(rpmExamples.size() == 2 && !vesc.isPortConnected(), "Offline signed RPM serialization failed");
result.insert("offline_signed_rpm_examples_base64", rpmExamples);
if(archive.contains("sample_test")) {
const auto test=archive.value("sample_test").toObject();
if(test.contains("packet"))result.insert("sample",decodeSample(QByteArray::fromBase64(test.value("packet").toString().toLatin1()),0,test.value("decimation").toInt(1)));
QJsonArray sent;QObject observer;
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &p){sent.append(QString::fromLatin1(p.toBase64()));});
NativeSamples samples;samples.attach(commands);
auto state=samples.start({{"mode",test.value("mode").toInt(1)},{"count",2},{"decimation",3},{"timeout_s",2},{"raw",false}});
for(const auto &p:test.value("packets").toArray())samples.receive(QByteArray::fromBase64(p.toString().toLatin1()));
if(test.value("wait_timeout").toBool()) {QEventLoop wait;QTimer::singleShot(2200,&wait,&QEventLoop::quit);wait.exec();}
result.insert("sample_state",samples.run("sample_read",{{"capture_id",state.value("capture_id")},{"offset",0}}));
samples.run("sample_stop",{{"capture_id",state.value("capture_id")}});
result.insert("sample_commands",sent);
}
if (archive.contains("edit")) {
const auto edit = archive.value("edit").toObject();
const auto kind = edit.value("kind").toString();
require(kind == "motor" || kind == "application", "Unknown edit kind");
const bool mc = kind == "motor";
result.insert("edit", prepareConfig(mc ? vesc.mcConfig() : vesc.appConfig(), edit.value("source").toObject(),
mc ? COMM_GET_MCCONF : COMM_GET_APPCONF, mc ? "MCConfiguration" : "APPConfiguration"));
}
if (archive.contains("firmware_image")) {
const auto image = archive.value("firmware_image").toObject();
result.insert("firmware_image", inspectFirmwareSource(QByteArray::fromBase64(image.value("data").toString().toLatin1()), image.value("kind").toString(), image.value("format").toString("bin")).info);
}
if(archive.contains("swd_image")) {
const auto p=archive.value("swd_image").toObject();const auto range=swdRange(p.value("target").toObject());
const auto data=QByteArray::fromBase64(p.value("data").toString().toLatin1());
result.insert("swd_image",inspectFirmwareSource(data,"firmware",p.value("format").toString("bin"),range.first,range.second).info);
}
if(archive.contains("can_route")) {
bool remote=false;QByteArray sent;QObject observer;
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &data){sent=data;});
try { NativeCanTarget route(vesc,remote,archive.value("can_route").toInt(-1));commands->getFwVersion();throw std::runtime_error("synthetic read failure"); }
catch(const std::exception&){}
require(!remote && !commands->getSendCan() && !vesc.isIgnoringCanChanges(),"CAN route leaked after failure");
require(sent.size()==3 && quint8(sent[0])==COMM_FORWARD_CAN && quint8(sent[1])==7 && quint8(sent[2])==COMM_FW_VERSION,"CAN read was not unicast");
result.insert("can_route",true);
}
if(archive.contains("bms_command")) {
const auto p=archive.value("bms_command").toObject();
const double id=p.value("can_id").toDouble(-1);require(id==int(id),"Integral CAN address required");
bool remote=false; QByteArray sent;
QObject observer;
QObject::connect(commands,&Commands::dataToSend,&observer,[&](QByteArray &data){sent=data;});
{
NativeCanTarget route(vesc,remote,int(id));
sendBmsCommand(commands,p.value("command").toString());
}
require(!remote && !commands->getSendCan() && !vesc.isIgnoringCanChanges(),"CAN route did not restore");
FW_RX_PARAMS bms; bms.major=6;bms.minor=0;bms.hwType=HW_TYPE_VESC_BMS;bms.isTestFw=0;
require(bmsCommandsSupported(bms),"Reviewed BMS protocol missing");
bms.hwType=HW_TYPE_VESC;require(!bmsCommandsSupported(bms),"Motor must not become BMS");
bms.hwType=HW_TYPE_VESC_BMS;bms.major=99;require(!bmsCommandsSupported(bms),"Unknown BMS firmware admitted");
result.insert("bms_command",QJsonObject{{"packet_hex",QString::fromLatin1(sent.toHex())},{"route_restored",true}});
}
if(archive.contains("custom_schema")) {
const auto xml=QByteArray::fromBase64(archive.value("custom_schema").toString().toLatin1());ConfigParams custom;
NativeCustom::schema(custom,qCompress(xml));const auto packet=configPacket(&custom,COMM_GET_CUSTOM_CONFIG);
loadExactConfig(&custom,packet,COMM_GET_CUSTOM_CONFIG);
result.insert("custom_configuration",exportConfig(&custom,packet,"CustomConfiguration"));
if(archive.contains("custom_edit"))result.insert("custom_edit",prepareConfig(&custom,archive.value("custom_edit").toObject(),COMM_GET_CUSTOM_CONFIG,"CustomConfiguration"));
}
if(archive.contains("package")) result.insert("package",NativePackage::inspect(archive.value("package").toObject()));
if(archive.contains("code_project")) {
const auto project=archive.value("code_project").toObject();const auto packed=NativeCode::pack(project);
const auto checked=NativeCode::image({{"kind",project.value("kind")},{"image",QString::fromLatin1(packed.toBase64())}});
require(checked==packed,"Code frame validation mismatch");auto decoded=NativeCode::decode(project.value("kind").toString(),packed.mid(8));
require(decoded.value("source")==project.value("source") && decoded.value("imports").toObject()==project.value("imports").toObject(),"Code source/import roundtrip differs");result.insert("code",decoded);
}
if(archive.contains("code_image")) NativeCode::image(archive.value("code_image").toObject());
if(archive.contains("code_decode")) {const auto value=archive.value("code_decode").toObject();NativeCode::decode(value.value("kind").toString(),QByteArray::fromBase64(value.value("payload").toString().toLatin1()));}
FW_RX_PARAMS codeFw;codeFw.major=6;codeFw.minor=0;codeFw.hwType=HW_TYPE_VESC;codeFw.isTestFw=0;
require(NativeCode::supported(codeFw),"Code firmware profile missing");codeFw.minor=1;require(!NativeCode::supported(codeFw),"Unknown code firmware admitted");
codeFw.major=5;codeFw.minor=2;require(!NativeCode::supported(codeFw),"FW5.02 cannot run Lisp/QML");
result.insert("archive_sha256", sha256(raw));
result.insert("ok", true);
} catch (const std::exception &error) {
+102
View File
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "code_native.h"
#include <QJSEngine>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <zlib.h>
class NativePackage {
public:
static QByteArray unpackBounded(const QByteArray &data) {
require(data.size()>=5&&data.size()<=1024*1024,"Package size exceeds bound");
auto size=qFromBigEndian<quint32>(reinterpret_cast<const uchar*>(data.constData()));
require(size>0&&size<=4*1024*1024,"Expanded package exceeds bound");
QByteArray raw(int(size),'\0');z_stream z{};require(inflateInit(&z)==Z_OK,"Cannot inspect package compression");
z.next_in=reinterpret_cast<Bytef*>(const_cast<char*>(data.constData()+4));z.avail_in=data.size()-4;
z.next_out=reinterpret_cast<Bytef*>(raw.data());z.avail_out=size;const auto code=inflate(&z,Z_FINISH);
const bool valid=code==Z_STREAM_END&&z.total_out==size&&z.avail_in==0;inflateEnd(&z);require(valid,"Invalid package compression");
require(raw.startsWith(QByteArray("VESC Packet\0",12)),"Invalid VESC package magic");
int at=12;QSet<QByteArray> fields;
while(at<raw.size()) {
int end=raw.indexOf('\0',at);require(end>at&&end-at<=64&&end+5<=raw.size(),"Invalid package field");
const auto name=raw.mid(at,end-at);const auto length=qFromBigEndian<qint32>(reinterpret_cast<const uchar*>(raw.constData()+end+1));at=end+5;
require(!fields.contains(name)&&fields.size()<32&&length>=0&&length<=raw.size()-at,"Duplicate/truncated package field");fields.insert(name);
if(name=="qmlIsFullscreen")require(length==1&&(raw[at]==0||raw[at]==1),"Invalid QML flag");
at+=length;
}
return raw;
}
// Evaluate only the descriptor's pure compatibility function. A bare JS
// engine has no Qt/QObject, USB, filesystem, network or application bridge.
// QML object creation and Component.onCompleted are never evaluated.
static QJsonValue compatible(const QString &descriptor,const QJsonObject &identity) {
if(descriptor.isEmpty())return QJsonValue(QJsonValue::Null);
if(descriptor.size()>16384)return QJsonValue(QJsonValue::Null);
auto match=QRegularExpression("function\\s+isCompatible\\s*\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\)\\s*\\{").match(descriptor);
if(!match.hasMatch())return QJsonValue(QJsonValue::Null);
int end=match.capturedEnd(),depth=1;QChar quote;bool line=false,block=false,escape=false;
for(;end<descriptor.size()&&depth;end++) {
auto c=descriptor[end],next=end+1<descriptor.size()?descriptor[end+1]:QChar();
if(line){if(c=='\n')line=false;continue;}if(block){if(c=='*'&&next=='/'){block=false;end++;}continue;}
if(!quote.isNull()){if(escape){escape=false;continue;}if(c=='\\'){escape=true;continue;}if(c==quote)quote=QChar();continue;}
if(c=='`')return QJsonValue(QJsonValue::Null);
if(c=='/'&&next=='/'){line=true;end++;continue;}if(c=='/'&&next=='*'){block=true;end++;continue;}
if(c=='\''||c=='"'){quote=c;continue;}if(c=='{')depth++;if(c=='}')depth--;
}
if(depth)return QJsonValue(QJsonValue::Null);
QJSEngine engine;auto fw=engine.newObject();
for(auto it=identity.begin();it!=identity.end();++it)fw.setProperty(it.key(),engine.toScriptValue(it.value().toVariant()));
fw.setProperty("hw",identity.value("hardware").toString());fw.setProperty("fwName",identity.value("firmware_name").toString());
const int type=identity.value("hardware_type").toInt(-1);
const auto typeName=type==0?"VESC":type==1?"VESC BMS":type==2?"Custom Module":"Unknown";
auto name=engine.newObject();name.setProperty("name",typeName);engine.globalObject().setProperty("_hwType",name);
fw.setProperty("hwTypeStr",engine.evaluate("(function(){return _hwType.name;})"));
std::mutex mutex;std::condition_variable condition;bool done=false;
std::thread timer([&]{std::unique_lock<std::mutex> lock(mutex);if(!condition.wait_for(lock,std::chrono::milliseconds(250),[&]{return done;}))engine.setInterrupted(true);});
auto fn=engine.evaluate("("+descriptor.mid(match.capturedStart(),end-match.capturedStart())+")");
auto result=fn.isCallable()?fn.call({fw}):QJSValue();
{std::lock_guard<std::mutex> lock(mutex);done=true;}condition.notify_one();timer.join();
if(engine.isInterrupted()||!result.isBool())return QJsonValue(QJsonValue::Null);
return result.toBool();
}
static QByteArray image(const QByteArray &content) {
if(content.isEmpty())return {};
require(content.size()>=2,"Code flags missing");VByteArray out;out.vbAppendUint32(content.size()-2);
out.vbAppendUint16(Packet::crc16(reinterpret_cast<const unsigned char*>(content.constData()),content.size()));out.append(content);return out;
}
static QJsonObject library(const QByteArray &content) {
require(content.size()>=5&&content.size()<=512*1024&&content.startsWith(QByteArray(2,'\0')), "Invalid library Lisp content");
const auto data=content.mid(2);const int end=data.indexOf('\0');require(end>0&&end+3<=data.size(),"Invalid library source");
VByteArray table(data.mid(end+1));const auto count=table.vbPopFrontInt16();require(count>=0&&count<500,"Invalid library import count");
int tableEnd=end+3;QList<QPair<int,int>> ranges;QSet<QString> names;
for(int i=0;i<count;i++) {
const int n=table.indexOf('\0');require(n>0&&n<=64&&n+9<=table.size(),"Invalid library tag");
const auto tag=table.vbPopFrontString();int offset=table.vbPopFrontInt32(),length=table.vbPopFrontInt32();
require(!names.contains(tag)&&offset>=0&&length>0&&offset<=data.size()-length&&data[offset+length-1]=='\0',"Invalid library range");
names.insert(tag);ranges.append(qMakePair(offset,length));tableEnd+=n+9;
}
int previous=tableEnd;for(auto range:ranges){require(range.first>=previous,"Overlapping library range");previous=range.first+range.second;}
CodeLoader loader;const auto parts=loader.lispUnpackImports(content);QJsonObject imports;
for(auto part:parts.second)imports.insert(part.first,QString::fromLatin1(part.second.toBase64()));
return {{"source",parts.first},{"imports",imports}};
}
static QJsonObject inspect(const QJsonObject &request) {
const auto encoded=request.value("data").toString().toLatin1();const auto data=QByteArray::fromBase64(encoded,QByteArray::AbortOnBase64DecodingErrors);
require(data.toBase64()==encoded,"Invalid package encoding");unpackBounded(data);
CodeLoader loader;const auto pkg=loader.unpackVescPackage(data);require(pkg.loadOk&&!pkg.name.isEmpty()&&pkg.name.size()<=256,"Package metadata missing");
auto lisp=image(pkg.lispData);VByteArray qml;
if(!pkg.qmlFile.isEmpty()){qml.vbAppendUint16(pkg.qmlIsFullscreen?2:1);qml.append(loader.qmlCompress(pkg.qmlFile));}
const auto qmlImage=image(qml);const bool fits=lisp.size()<=120*1024&&qmlImage.size()<=120*1024&&pkg.qmlFile.toUtf8().size()<=500*1024;
if(!lisp.isEmpty())require(pkg.lispData.startsWith(QByteArray(2,'\0')),"Unknown Lisp flags");
// Dependencies are already embedded by the upstream package builder.
// Original bytes are retained, including native libraries and alignment.
QJsonObject result{{"name",pkg.name},{"sha256",sha256(data)},{"description",pkg.description_md.left(65536)},
{"compatible",compatible(pkg.pkgDescQml,request.value("identity").toObject())},{"fits",fits},
{"lisp_bytes",lisp.size()},{"qml_bytes",qmlImage.size()},{"qml_source",pkg.qmlFile.toUtf8().size()<=120*1024?QJsonValue(pkg.qmlFile):QJsonValue()},
{"images",QJsonObject{{"lisp",fits?QString::fromLatin1(lisp.toBase64()):QString()},{"qml",fits?QString::fromLatin1(qmlImage.toBase64()):QString()}}}};
if(request.value("export_library").toBool())result.insert("library",library(pkg.lispData));
return result;
}
};
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "config_export.h"
#include <QSet>
#include <QMap>
// Decode intent only. No raw QML payload is ever passed to a device transport.
static bool qmlReadCode(int code) {
return QList<int>{0,4,14,17,31,32,33,65,96}.contains(code);
}
// Identification is outside the upstream limited-mode list. Configuration
// admission belongs to the exact schema already qualified by the engine.
static bool qmlReadSupported(Commands *commands, int code) {
return qmlReadCode(code) && (code==0||code==14||code==17||
commands->getLimitedCompatibilityCommands().contains(code));
}
static QJsonObject qmlReadIntent(const QByteArray &raw) {
if(raw.isEmpty())return {};
const int code=quint8(raw[0]);
if(!qmlReadCode(code)||raw.size()!=(code==65?3:1))return {};
QJsonObject out{{"command",code}};
if(code==65)out.insert("mask",(quint8(raw[1])<<8)|quint8(raw[2]));
return out;
}
static void validateQmlRead(const QJsonObject &intent) {
const auto value=intent.value("command");const int code=value.toInt(-1);
require(value.isDouble()&&value.toDouble()==code&&qmlReadCode(code),"QML read is not admitted");
require(intent.size()==(code==65?2:1),"Invalid QML read shape");
if(code==65){const auto mask=intent.value("mask");require(mask.isDouble()&&mask.toDouble()==mask.toInt(-1)&&mask.toInt(-1)>=0&&mask.toInt(-1)<=65535,"Invalid IMU read mask");}
}
class QmlReadQueue {
public:
bool enabled;int blocked=0;QMap<int,QJsonObject> pending;QSet<int> blockedCodes;
explicit QmlReadQueue(bool live):enabled(live){}
void capture(const QByteArray &raw) {
auto intent=qmlReadIntent(raw);
if(!enabled||intent.isEmpty()) {
if(blocked<1000000)++blocked;
if(blockedCodes.size()<32&&!raw.isEmpty())blockedCodes.insert(quint8(raw[0]));
return;
}
pending.insert(intent.value("command").toInt(),intent);
}
QJsonArray take() {QJsonArray out;for(const auto &intent:pending)out.append(intent);pending.clear();return out;}
QJsonArray rejected() const {QJsonArray out;for(int code:blockedCodes)out.append(code);return out;}
};
+37
View File
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QMouseEvent>
#include <QKeyEvent>
#include <QWheelEvent>
#include <QInputMethodEvent>
#include <QSocketNotifier>
static void qmlInput(QQuickWindow &window,const QJsonArray &events) {
require(events.size()<=32,"Too many input events");
for(const auto &value:events){
require(value.isObject(),"Invalid input event");auto e=value.toObject();auto kind=e.value("kind").toString();
if(kind=="down" || kind=="up" || kind=="move" || kind=="wheel") {
double x=e.value("x").toDouble(-1),y=e.value("y").toDouble(-1);
require(std::isfinite(x)&&std::isfinite(y)&&x>=0&&x<640&&y>=0&&y<480,"Invalid input coordinates");
QPointF p(x,y);
if(kind=="wheel"){
int delta=e.value("delta").toInt();require(std::abs(delta)<=1200,"Invalid wheel input");
QWheelEvent ev(p,p,QPoint(),QPoint(0,delta),Qt::NoButton,Qt::NoModifier,Qt::NoScrollPhase,false);QCoreApplication::sendEvent(&window,&ev);
}else{
auto type=kind=="down"?QEvent::MouseButtonPress:kind=="up"?QEvent::MouseButtonRelease:QEvent::MouseMove;
QMouseEvent ev(type,p,p,p,kind=="move"?Qt::NoButton:Qt::LeftButton,kind=="up"?Qt::NoButton:Qt::LeftButton,Qt::NoModifier);
QCoreApplication::sendEvent(&window,&ev);
}
}else if(kind=="text"){
auto text=e.value("text").toString();require(text.size()<=1024&&!text.contains(QChar(0)),"Invalid text input");
QInputMethodEvent ev;ev.setCommitString(text);
auto focus=window.activeFocusItem();if(focus)QCoreApplication::sendEvent(focus,&ev);
}else if(kind=="key"){
const QMap<QString,int> keys{{"Enter",Qt::Key_Return},{"Tab",Qt::Key_Tab},{"Backspace",Qt::Key_Backspace},{"Delete",Qt::Key_Delete},{"ArrowLeft",Qt::Key_Left},{"ArrowRight",Qt::Key_Right},{"ArrowUp",Qt::Key_Up},{"ArrowDown",Qt::Key_Down},{"Home",Qt::Key_Home},{"End",Qt::Key_End},{"Escape",Qt::Key_Escape},{"SelectAll",Qt::Key_A}};
auto name=e.value("key").toString();require(keys.contains(name),"Unsupported QML key");
auto modifiers=name=="SelectAll"?Qt::ControlModifier:Qt::NoModifier;
QKeyEvent down(QEvent::KeyPress,keys[name],modifiers),up(QEvent::KeyRelease,keys[name],modifiers);
QCoreApplication::sendEvent(&window,&down);QCoreApplication::sendEvent(&window,&up);
}else throw std::runtime_error("Unknown QML input event");
}
}
+170
View File
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Real Qt Quick preview using the pinned upstream Tool resources/objects.
// This executable never receives a device path or a transport connection.
#include "config_export.h"
#include <sys/stat.h>
#include "qml_sandbox.h"
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
#include <QQmlError>
#include <QQuickWindow>
#include <QQuickRenderControl>
#include <QQuickItem>
#include <QBuffer>
#include <QFontDatabase>
#include <QTimer>
#include <QEventLoop>
#include <QElapsedTimer>
#include <QDir>
#include <QFileInfo>
#include <QQuickStyle>
#include <memory>
#include <sys/socket.h>
#include "qml_interactive.h"
#include "qml_broker.h"
#include "qml_vesc_interface.h"
static QStringList messages;
static void boundedMessage(QtMsgType, const QMessageLogContext&, const QString &message) {
if(messages.size()<12) messages.append(message.left(320));
}
int main(int argc,char **argv) {
QJsonObject result{{"schema","missioncore.vesc.qml-preview/v1"},{"hardware_access",false},{"snapshot_only",true}};
try {
require(argc==1,"QML preview accepts stdin only");
QFile input; require(input.open(stdin,QIODevice::ReadOnly),"Cannot read preview");
QByteArray raw; while(raw.size()<=512*1024){auto p=input.read(1);if(p.isEmpty()||p=="\n")break;raw+=p;}
require(!raw.isEmpty()&&raw.size()<=512*1024,"Preview input exceeds limit");
auto doc=QJsonDocument::fromJson(raw);require(doc.isObject(),"Invalid preview input");
auto request=doc.object();const bool interactive=request.value("interactive").toBool();
const bool standalone=request.value("standalone").toBool();
const bool broker=request.value("broker").toBool();
require(!broker||(interactive&&!standalone),"Broker requires an interactive controller context");
result.insert("broker",broker);result.insert("snapshot_only",!broker);
auto source=request.value("source").toString().toUtf8();
require(!source.trimmed().isEmpty()&&source.size()<=120*1024&&!source.contains('\0'),"Invalid QML source size");
int width=request.value("width").toInt(),height=request.value("height").toInt();
require(width>=320&&width<=960&&height>=240&&height<=720,"Invalid preview dimensions");
rlimit memory{512ULL*1024*1024,512ULL*1024*1024}, cpu{interactive?12UL:3UL,interactive?12UL:3UL}, files{64,64}, core{0,0};
require(!setrlimit(RLIMIT_AS,&memory)&&!setrlimit(RLIMIT_CPU,&cpu)&&!setrlimit(RLIMIT_NOFILE,&files)&&!setrlimit(RLIMIT_CORE,&core),"Cannot bound QML process");
const QString root=QFileInfo(QString::fromLocal8Bit(argv[0])).absoluteDir().absoluteFilePath("..");
qputenv("QT_QPA_PLATFORM","offscreen");qputenv("QT_QUICK_BACKEND","software");
qputenv("QT_QUICK_CONTROLS_STYLE","Material");qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME","Dark");
qputenv("QML_DISABLE_DISK_CACHE","1");qputenv("QV4_FORCE_INTERPRETER","1");
qputenv("QT_QPA_FONTDIR",(root+"/fonts").toUtf8());
qInstallMessageHandler(boundedMessage);
// Confinement precedes QApplication, VescInterface and all user QML.
confineQml(QDir(root).canonicalPath());
int denied=open("/etc/passwd",O_RDONLY|O_CLOEXEC);if(denied>=0)close(denied);
require(denied<0,"QML filesystem boundary failed");
int sock=socket(AF_INET,SOCK_STREAM,0);if(sock>=0)close(sock);
require(sock<0&&errno==EPERM,"QML network boundary failed");
char *noArgs[]={nullptr};syscall(SYS_execve,"/mission-core-qml-no-executable",noArgs,noArgs);
require(errno==EPERM,"QML execution boundary failed");
result.insert("sandbox_verified",true);
QApplication app(argc,argv);
QFontDatabase::addApplicationFont(":/res/fonts/Roboto/Roboto-Regular.ttf");
app.setFont(QFont("Roboto",12));
QCoreApplication::setOrganizationName("MissionCore");
QCoreApplication::setApplicationName("VescQmlPreview");
qmlRegisterType<Commands>("Vedder.vesc.commands",1,0,"Commands");
qmlRegisterType<ConfigParams>("Vedder.vesc.configparams",1,0,"ConfigParams");
qmlRegisterSingletonType<Utility>("Vedder.vesc.utility",1,0,"Utility",[](QQmlEngine*,QJSEngine*)->QObject*{return new Utility;});
qRegisterMetaType<MC_VALUES>();qRegisterMetaType<FW_RX_PARAMS>();qRegisterMetaType<BMS_VALUES>();
QmlVescInterface vesc;vesc.brokerConnected=broker;vesc.setLoadQmlUiOnConnect(false);vesc.ignoreCanChange(broker);
qmlRegisterSingletonInstance<QmlVescInterface>("Vedder.vesc.vescinterface",1,0,"VescIf",&vesc);
Utility util;require(Utility::configLoadLatest(&vesc),"Upstream configuration resources missing");
const auto identity=request.value("identity").toObject();FW_RX_PARAMS fw;
fw.major=identity.value("major").toInt();fw.minor=identity.value("minor").toInt();
fw.hw=identity.value("hardware").toString();fw.isTestFw=identity.value("test_firmware").toInt();
fw.uuid=QByteArray::fromHex(identity.value("uuid").toString().toLatin1());
vesc.brokerUuid=identity.value("uuid").toString();
fw.customConfigNum=identity.value("custom_configs").toInt();
fw.hwType=HW_TYPE(identity.value("hardware_type").toInt());
if(!standalone)vesc.commands()->fwVersionReceived(fw);
bool failed=false;QObject::connect(vesc.commands(),&Commands::deserializeConfigFailed,[&](bool,bool){failed=true;});
if(!standalone)for(const auto &kind:QStringList{"motor","application"}) {
auto packet=archivePacket(request,kind,kind=="motor"?COMM_GET_MCCONF:COMM_GET_APPCONF);
vesc.commands()->processPacket(packet);
}
require(!failed,"Snapshot configuration rejected");
const auto valuePacket=QByteArray::fromBase64(request.value("values").toString().toLatin1());
require(standalone||(!valuePacket.isEmpty()&&quint8(valuePacket[0])==COMM_GET_VALUES),"Telemetry snapshot missing");
QmlReadQueue reads(broker);QObject::connect(vesc.commands(),&Commands::dataToSend,[&](QByteArray &raw){reads.capture(raw);});
QQmlEngine engine;engine.setImportPathList({root+"/qml","qrc:/"});
engine.rootContext()->setContextProperty("VescIf",&vesc);
engine.rootContext()->setContextProperty("Utility",&util);
QQmlComponent component(&engine);component.setData(source,QUrl("qrc:/mobile/MissionCorePreview.qml"));
QElapsedTimer loading;loading.start();
while(component.isLoading()&&loading.elapsed()<1000)QCoreApplication::processEvents(QEventLoop::AllEvents,20);
if(component.isError())for(const auto &e:component.errors())messages.append(e.toString().left(320));
require(component.isReady(),"QML could not be loaded");
QQuickRenderControl renderControl;
QQuickWindow window(&renderControl);window.resize(width,height);window.setColor(QColor("#151515"));
window.contentItem()->setWidth(width);window.contentItem()->setHeight(height);
std::unique_ptr<QObject> object(component.create());require(bool(object),"QML could not be created");
auto item=qobject_cast<QQuickItem*>(object.get());
if(!item) {auto rootWindow=qobject_cast<QQuickWindow*>(object.get());require(rootWindow,"QML root must be Item or Window");rootWindow->hide();rootWindow->resize(width,height);item=rootWindow->contentItem();}
item->setParentItem(window.contentItem());item->setWidth(width);item->setHeight(height);
renderControl.initialize(nullptr);
QEventLoop loop;QTimer feed;QObject::connect(&feed,&QTimer::timeout,[&]{auto packet=valuePacket;vesc.commands()->processPacket(packet);});if(!standalone&&!broker)feed.start(100);
if(broker){auto packet=valuePacket;vesc.commands()->processPacket(packet);}
QTimer::singleShot(500,&loop,&QEventLoop::quit);loop.exec();
auto frame=[&]{
auto image=renderControl.grab();require(!image.isNull(),"Qt Quick returned an empty frame");
QByteArray png;QBuffer buffer(&png);buffer.open(QIODevice::WriteOnly);require(image.save(&buffer,"PNG"),"Cannot encode QML frame");
require(png.size()<=512*1024,"QML frame exceeds limit");
result.insert("png",QString::fromLatin1(png.toBase64()));result.insert("width",image.width());result.insert("height",image.height());
result.insert("source_sha256",QString::fromLatin1(QCryptographicHash::hash(source,QCryptographicHash::Sha256).toHex()));
result.insert("root_width",item->width());result.insert("root_height",item->height());
result.insert("discarded_commands",reads.blocked);result.insert("blocked_codes",reads.rejected());result.insert("read_requests",reads.take());result.insert("ok",true);
result.insert("interactive",interactive);result.insert("standalone",standalone);
QJsonArray warnings;for(const auto &m:messages.mid(0,16))warnings.append(m);result.insert("warnings",warnings);
};
auto write=[&]{QFile output;output.open(stdout,QIODevice::WriteOnly);output.write(QJsonDocument(result).toJson(QJsonDocument::Compact)+"\n");output.flush();};
frame();
if(interactive){
write();
QTimer idle,maximum;idle.setSingleShot(true);maximum.setSingleShot(true);
QObject::connect(&idle,&QTimer::timeout,&app,&QCoreApplication::quit);
QObject::connect(&maximum,&QTimer::timeout,&app,&QCoreApplication::quit);
idle.start(60000);maximum.start(300000);
require(fcntl(STDIN_FILENO,F_SETFL,fcntl(STDIN_FILENO,F_GETFL)|O_NONBLOCK)==0,"Cannot bound input pipe");
QSocketNotifier notifier(STDIN_FILENO,QSocketNotifier::Read);QByteArray pending;int requests=0;
QObject::connect(&notifier,&QSocketNotifier::activated,[&](int){
char bytes[8192];ssize_t count=::read(STDIN_FILENO,bytes,sizeof(bytes));
if(count==0){app.quit();return;}if(count<0)return;pending.append(bytes,int(count));
if(pending.size()>128*1024){app.quit();return;}
int split=pending.indexOf('\n');if(split<0)return;
auto message=QJsonDocument::fromJson(pending.left(split)).object();pending.remove(0,split+1);
notifier.setEnabled(false);
try{
require(pending.isEmpty()&&++requests<=240,"QML input bound exceeded");
const auto op=message.value("op").toString();
if(op=="close"){app.quit();return;}
require(op=="frame"&&message.value("events").isArray(),"Invalid QML operation");
if(message.contains("packets")) {
require(broker&&message.value("packets").isArray(),"Unexpected broker replies");
const auto packets=message.value("packets").toArray();require(packets.size()<=2,"Too many broker replies");
for(const auto &entry:packets) {
require(entry.isString(),"Invalid broker packet");
auto encoded=entry.toString().toLatin1();auto packet=QByteArray::fromBase64(encoded);
require(!packet.isEmpty()&&packet.size()<=32768&&packet.toBase64()==encoded&&qmlReadCode(quint8(packet[0])),"Invalid broker response");
vesc.commands()->processPacket(packet);
}
require(!failed,"Controller configuration rejected");
}
qmlInput(window,message.value("events").toArray());
QCoreApplication::processEvents(QEventLoop::ExcludeSocketNotifiers,20);
frame();write();idle.start(60000);notifier.setEnabled(true);
}catch(const std::exception &e){result.remove("png");result.insert("ok",false);result.insert("error",QString::fromUtf8(e.what()));write();app.quit();}
});
app.exec();return 0;
}
}catch(const std::exception &error){result.insert("ok",false);result.insert("error",QString::fromUtf8(error.what()));}
QJsonArray warnings;for(const auto &m:messages.mid(0,16))warnings.append(m);result.insert("warnings",warnings);
QFile output;output.open(stdout,QIODevice::WriteOnly);output.write(QJsonDocument(result).toJson(QJsonDocument::Compact)+"\n");output.flush();
return result.value("ok").toBool()?0:1;
}
#include "qml_vesc_interface.moc"
+66
View File
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Unprivileged Linux containment. A preview has no device, network, writable
// filesystem or process-execution authority. Fail closed if the kernel lacks it.
#pragma once
#include <linux/landlock.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <linux/audit.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <cerrno>
#include <vector>
#include <stdexcept>
#include <QStringList>
inline void confineQml(const QString &root) {
if (syscall(SYS_landlock_create_ruleset, nullptr, 0, LANDLOCK_CREATE_RULESET_VERSION) < 3)
throw std::runtime_error("QML preview needs Landlock ABI 3 or later");
const __u64 read = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
landlock_ruleset_attr attr{};
attr.handled_access_fs = (1ULL << 15) - 1; // ABI 3, including REFER/TRUNCATE
int rules = syscall(SYS_landlock_create_ruleset, &attr, sizeof(attr), 0);
if (rules < 0) throw std::runtime_error("Cannot create QML filesystem boundary");
const QStringList paths{root, "/usr/share/fonts", "/etc/fonts", "/etc/localtime", "/dev/urandom"};
for (const auto &path : paths) {
int fd = open(path.toLocal8Bit().constData(), O_PATH | O_CLOEXEC);
if (fd < 0) { if(path == root) {close(rules); throw std::runtime_error("QML runtime missing");} continue; }
struct stat st{}; fstat(fd, &st);
landlock_path_beneath_attr rule{}; rule.parent_fd=fd;
rule.allowed_access = S_ISDIR(st.st_mode) ? read : LANDLOCK_ACCESS_FS_READ_FILE;
int result=syscall(SYS_landlock_add_rule,rules,LANDLOCK_RULE_PATH_BENEATH,&rule,0);
close(fd);
if(result) {close(rules);throw std::runtime_error("Cannot admit QML runtime path");}
}
if(prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0) || syscall(SYS_landlock_restrict_self,rules,0)) {
close(rules);throw std::runtime_error("Cannot restrict QML filesystem");
}
close(rules);
std::vector<sock_filter> filter{
BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,arch)),
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,AUDIT_ARCH_X86_64,1,0),
BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS),
BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,nr)),
BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K,0x40000000,0,1),
BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS)};
for(int number : {SYS_socket,SYS_connect,SYS_bind,SYS_listen,SYS_accept,SYS_accept4,
SYS_execve,SYS_execveat,SYS_fork,SYS_vfork,SYS_ptrace,
SYS_process_vm_readv,SYS_process_vm_writev,SYS_mount,SYS_umount2,
SYS_bpf,SYS_ioctl,SYS_io_uring_setup,SYS_unshare,SYS_setns}) {
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,number,0,1));
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|EPERM));
}
// glibc falls back from clone3 to clone; only thread creation is admitted.
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_clone3,0,1));
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|ENOSYS));
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_clone,0,3));
filter.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(seccomp_data,args[0])));
filter.push_back(BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K,CLONE_THREAD,1,0));
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|EPERM));
filter.push_back(BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW));
sock_fprog program{static_cast<unsigned short>(filter.size()),filter.data()};
if(prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,&program)) throw std::runtime_error("Cannot restrict QML system calls");
}
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "vescinterface.h"
// Only the QML connection indicator is adapted. Upstream transport remains closed;
// Utility/Commands cannot acquire a USB descriptor or bypass the parent broker.
class QmlVescInterface : public VescInterface {
Q_OBJECT
public:
bool brokerConnected=false;
QString brokerUuid;
Q_INVOKABLE bool isPortConnected() { return brokerConnected; }
Q_INVOKABLE QString getConnectedPortName() {
return brokerConnected ? QString("Mission Core / USB / ")+brokerUuid : QString();
}
Q_INVOKABLE QString getConnectedUuid() { return brokerConnected?brokerUuid:QString(); }
};
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Bounded Sample Data receiver; Commands owns wire encoding and transport.
#pragma once
#include "config_export.h"
#include <QTimer>
#include <QElapsedTimer>
#include <QUuid>
#include <cmath>
static QJsonObject decodeSample(QByteArray raw, int sequence, int decimation) {
require(raw.size()==34 || raw.size()==38 || raw.size()==44,"Unknown Sample Data packet length");
const bool indexed=raw.size()==44, third=raw.size()!=34;
VByteArray b(raw);
int index=indexed?b.vbPopFrontInt16():sequence;
require(index>=0 && index<2000,"Sample index outside buffer");
QJsonObject row{{"index",index},{"indexed",indexed},{"third_current_measured",third}};
auto take=[&](const QString &key){double v=b.vbPopFrontDouble32Auto();require(std::isfinite(v),"Non-finite sample");row.insert(key,v);return v;};
double i1=take("i1"),i2=take("i2");
if(third)take("i3");else row.insert("i3",-(i1+i2));
for(const auto &key:{"v1","v2","v3","v0","current","switching_hz"})take(key);
const double hz=row.value("switching_hz").toDouble();
require(hz>0 && hz<=1000000,"Invalid sample frequency");
const quint8 status=b.vbPopFrontInt8(),phase=b.vbPopFrontInt8();
row.insert("commutation",status&7);row.insert("hall",(status>>3)&7);
row.insert("phase_deg",phase/250.0*360.0);
row.insert("dt_s",decimation/hz);
if(indexed)require(b.vbPopFrontInt32()==index,"Sample index trailer mismatch");
require(b.isEmpty(),"Unexpected sample trailer");
return row;
}
class NativeSamples {
public:
Commands *commands=nullptr;
QTimer timer;
QElapsedTimer lifetime,quiet;
QString id,state="idle",error;
QJsonArray rows;
int mode=0,count=0,decimation=1,expected=0,timeout=30,malformed=0;
bool active() const {return state=="armed" || state=="receiving" || state=="stored_wait";}
void attach(Commands *c) {
commands=c; timer.setInterval(100);
QObject::connect(c,&Commands::samplesReceived,[this](QByteArray raw){receive(raw);});
QObject::connect(&timer,&QTimer::timeout,[this]{
if(lifetime.isValid() && lifetime.elapsed()>=300000){if(active())off();rows={};state="expired";timer.stop();return;}
if(!active())return;
if(mode==7 && !rows.isEmpty() && quiet.elapsed()>=1000){off();state="unverified";return;}
if(lifetime.elapsed()>=timeout*1000){off();state=rows.isEmpty()?"timeout":"incomplete";}
});
}
void off(){commands->samplePrint(DEBUG_SAMPLING_OFF,0,1,false);}
QJsonObject status() const {
return {{"capture_id",id},{"state",state},{"received",rows.size()},{"expected",expected},
{"capacity",2000},{"mode",mode},{"count",count},{"decimation",decimation},
{"malformed",malformed},{"error",error},{"indexed",false},{"raw_supported",false},
{"third_current_measured",false},{"acknowledged",false},
{"elapsed_ms",lifetime.isValid()?double(lifetime.elapsed()):0},
{"provenance",mode==7?"controller_last_buffer":"requested_capture"}};
}
QJsonObject start(const QJsonObject &p) {
if(active())return {{"accepted",false},{"reason","Sample Data capture is already active"}};
if(quiet.isValid() && quiet.elapsed()<1000)return {{"accepted",false},{"reason","Previous Sample Data transfer is still draining"}};
auto integer=[&](const char *k,int lo,int hi){auto v=p.value(k);double n=v.toDouble(-1);require(v.isDouble()&&n==int(n)&&n>=lo&&n<=hi,"Invalid Sample Data argument");return int(n);};
mode=integer("mode",1,7);count=integer("count",1,2000);decimation=integer("decimation",1,255);timeout=integer("timeout_s",2,120);
require(!p.value("raw").toBool(),"FW5.02 does not support raw ADC sampling");
expected=mode==7?0:mode>=3?2000:count;
id="sample_"+QUuid::createUuid().toString(QUuid::Id128);rows={};error.clear();malformed=0;
state=(mode==5||mode==6)?"stored_wait":"armed";lifetime.start();quiet.invalidate();timer.start();
commands->samplePrint(debug_sampling_mode(mode),count,decimation,false);
auto result=status();result.insert("accepted",true);return result;
}
void receive(const QByteArray &raw) {
quiet.restart();if(!active())return;
try {
// Only the reviewed FW5.02 live profile is admitted. New formats
// are decoded in offline checks, never guessed from a live device.
require(raw.size()==34,"FW5.02 Sample Data layout mismatch");
require(rows.size()<2000,"Sample Data buffer exceeded");
rows.append(decodeSample(raw,rows.size(),decimation));state="receiving";
if(expected && rows.size()==expected)state="complete";
}catch(const std::exception &e){++malformed;error=QString::fromUtf8(e.what());off();state="incomplete";}
}
QJsonObject run(const QString &method,const QJsonObject &p) {
if(method=="sample_start")return start(p);
if(method=="sample_status" && !p.contains("capture_id"))return status();
if(p.value("capture_id").toString()!=id || id.isEmpty())return {{"state","expired"}};
if(method=="sample_stop" && active()){off();state="cancelled";}
if(method=="sample_fetch") {
if(state!="stored_wait")return {{"accepted",false},{"reason","No pending stored capture"}};
// No trigger-complete ACK exists; a returned older buffer must not
// be represented as a confirmed capture of this trigger.
mode=7;expected=0;state="armed";rows={};timeout=30;lifetime.restart();
commands->samplePrint(DEBUG_SAMPLING_SEND_LAST_SAMPLES,0,1,false);
}
auto result=status();
if(method=="sample_read"){
double offset=p.value("offset").toDouble(-1);require(offset==int(offset)&&offset>=0&&offset<=2000,"Invalid sample offset");
QJsonArray page;for(int i=int(offset);i<rows.size()&&page.size()<128;++i)page.append(rows[i]);
result.insert("rows",page);result.insert("offset",int(offset));
}
return result;
}
};
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "firmware_source.h"
#include <QEventLoop>
#include <QTimer>
// The original BM protocol identifies MCU families, not a board or its UUID.
// Restrict writes to declared main flash; peripheral/option/UICR regions are
// never accepted as an ordinary firmware image.
static QPair<quint32,int> swdRange(const QJsonObject &p) {
const int code=p.value("target_code").toInt(-1);
require(code>=1 && code<=13,"Unsupported SWD target family");
const bool nrf=code>=2 && code<=8;
const quint32 origin=nrf?0:0x08000000;
const int cap=code==2?128*1024:code==3||code==4||code==5||code==6?256*1024:code==7?512*1024:code==8?1024*1024:2*1024*1024;
const auto base=p.value("address").toDouble(-1),size=p.value("flash_bytes").toDouble(-1);
require(base>=origin && base<quint64(origin)+cap && base==quint32(base) && size>=256 && size<=cap && size==int(size) && base+size<=quint64(origin)+cap,"SWD range outside main flash");
require(p.value("pins")=="default" || p.value("pins")=="nrf5x","Unknown SWD pin mapping");
return {quint32(base),int(size)};
}
static int swdConnect(VescInterface &v,const QJsonObject &p) {
auto cmd=v.commands();
require(!cmd->isLimitedMode() || cmd->getLimitedCompatibilityCommands().contains(COMM_BM_MEM_READ),"SWD binary verification is unsupported by this programmer firmware");
QEventLoop loop;QTimer timeout;timeout.setSingleShot(true);QObject observer;
bool mapped=false;int target=-100;
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);
const auto mappedResult=[&](bool ok){mapped=ok;loop.quit();};
if(p.value("pins")=="nrf5x")QObject::connect(cmd,&Commands::bmMapPinsNrf5xRes,&observer,mappedResult);
else QObject::connect(cmd,&Commands::bmMapPinsDefaultRes,&observer,mappedResult);
timeout.start(3000);
if(p.value("pins")=="nrf5x")cmd->bmMapPinsNrf5x();else cmd->bmMapPinsDefault();
if(!mapped)loop.exec();require(mapped,"SWD pin mapping was not acknowledged");
QObject::connect(cmd,&Commands::bmConnRes,&observer,[&](int code){target=code;loop.quit();});
timeout.start(3000);cmd->bmConnect();if(target==-100)loop.exec();
require(target==p.value("target_code").toInt(-1),"Connected SWD target differs from the selected MCU family");
return target;
}
static QJsonObject uploadSwd(VescInterface &v,const QJsonObject &p,const QByteArray &image,bool &cancelled) {
const auto range=swdRange(p);require(image.size()<=range.second,"SWD image exceeds selected range");
require(!cancelled,"SWD cancelled before connect");
const int code=swdConnect(v,p);
require(v.commands()->bmReadMemWait(range.first,32).size()==32 && v.commands()->bmReadMemWait(range.first+quint32(image.size())-32,32).size()==32,"SWD image endpoints are not readable main flash");
require(!cancelled,"SWD cancelled before erase");
require(v.swdEraseFlash(),"SWD erase unconfirmed");
require(!cancelled,"SWD cancelled after erase");
require(v.swdUploadFw(image,range.first,true,true),"SWD write/readback failed");
require(!cancelled,"SWD cancelled before reboot");
require(v.swdReboot(),"SWD reboot unconfirmed");
return {{"target_code",code},{"binary_readback_verified",true},{"reboot_confirmed",true},{"boot_verified",false}};
}
+1
View File
@@ -0,0 +1 @@
bms-settings.xml: GPL-3.0-or-later; vedderb/vesc_bms_fw, commit 591d57dadb14d4392d4cf859a5187264a8aafed8, config/settings.xml. Offline schema/codec qualification only, not installed battery defaults.
@@ -0,0 +1,817 @@
<?xml version="1.0" encoding="UTF-8"?>
<ConfigParams>
<Params>
<config_name>
<longName>none</longName>
<type>3</type>
<transmittable>0</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;TODO&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine></cDefine>
<valString>main_config_t</valString>
<maxLen>0</maxLen>
</config_name>
<hw_name>
<longName>VESC BMS</longName>
<type>0</type>
<transmittable>0</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;This is the VESC BMS. Some hw-specific info will be added here.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine></cDefine>
</hw_name>
<controller_id>
<longName>BMS ID</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;BMS ID. Used to identify this VESC BMS on the CAN-bus.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CONTROLLER_ID</cDefine>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>255</maxInt>
<minInt>-1</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>104</valInt>
<suffix></suffix>
<vTx>1</vTx>
</controller_id>
<send_can_status_rate_hz>
<longName>CAN Status Rate</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Send status messages on the CAN-bus at this rate.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_SEND_CAN_STATUS_RATE_HZ</cDefine>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>2000</maxInt>
<minInt>0</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>10</valInt>
<suffix> Hz</suffix>
<vTx>5</vTx>
</send_can_status_rate_hz>
<can_baud_rate>
<longName>CAN Baud Rate</longName>
<type>4</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;CAN-bus baud rate.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CAN_BAUD_RATE</cDefine>
<valInt>2</valInt>
<enumNames>CAN_BAUD_125K</enumNames>
<enumNames>CAN_BAUD_250K</enumNames>
<enumNames>CAN_BAUD_500K</enumNames>
<enumNames>CAN_BAUD_1M</enumNames>
<enumNames>CAN_BAUD_10K</enumNames>
<enumNames>CAN_BAUD_20K</enumNames>
<enumNames>CAN_BAUD_50K</enumNames>
<enumNames>CAN_BAUD_75K</enumNames>
</can_baud_rate>
<balance_mode>
<longName>Balancing Mode</longName>
<type>4</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Cell Balancing Mode. Options:&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif'; font-weight:600;&quot;&gt;BALANCE_MODE_DISABLED&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Do not balance cells at all.&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif'; font-weight:600;&quot;&gt;BALANCE_MODE_CHARGING_ONLY&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Only balance while charging.&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif'; font-weight:600;&quot;&gt;BALANCE_MODE_DURING_AND_AFTER_CHARGING&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Balance cells during charging and after charging has finished. Balancing will stop as soon as the &lt;/span&gt;&lt;span style=&quot; font-family:'Sans Serif'; font-style:italic;&quot;&gt;balance_max_current&lt;/span&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt; is exceeded.&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif'; font-weight:600;&quot;&gt;BALANCE_MODE_ALWAYS&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:'Sans Serif';&quot;&gt;Always allow balancing.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_BALANCE_MODE</cDefine>
<valInt>2</valInt>
<enumNames>BALANCE_MODE_DISABLED</enumNames>
<enumNames>BALANCE_MODE_CHARGING_ONLY</enumNames>
<enumNames>BALANCE_MODE_DURING_AND_AFTER_CHARGING</enumNames>
<enumNames>BALANCE_MODE_ALWAYS</enumNames>
</balance_mode>
<cell_num>
<longName>Number of Cells</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Number of cells in series.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CELL_NUM</cDefine>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>1000</maxInt>
<minInt>0</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>12</valInt>
<suffix></suffix>
<vTx>4</vTx>
</cell_num>
<cell_first_index>
<longName>First Cell Index</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Channel of the first cell.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CELL_FIRST_INDEX</cDefine>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>1000</maxInt>
<minInt>0</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>0</valInt>
<suffix></suffix>
<vTx>4</vTx>
</cell_first_index>
<max_bal_ch>
<longName>Max Balance Channels</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Maximum number of simultaneous balancing channels.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_MAX_BAL_CH</cDefine>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>1000</maxInt>
<minInt>0</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>11</valInt>
<suffix></suffix>
<vTx>4</vTx>
</max_bal_ch>
<dist_bal>
<longName>Distributed Balancing</longName>
<type>5</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Enables distributed balancing between BMSes on the CAN-bus.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_DIST_BAL</cDefine>
<valInt>1</valInt>
</dist_bal>
<vc_balance_start>
<longName>Balance Starting Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Start balancing if cell voltage is this much above the minimum cell voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_BALANCE_START</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.001</stepDouble>
<valDouble>0.015</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_balance_start>
<vc_balance_end>
<longName>Balance End Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Stop balancing when cell voltage is this much above the minimum cell voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_BALANCE_END</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.001</stepDouble>
<valDouble>0.008</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_balance_end>
<vc_charge_start>
<longName>Charge Start Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Start charging when the maximum cell voltage is below this voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CHARGE_START</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>4.16</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_charge_start>
<vc_charge_end>
<longName>Charge End Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;End charging when the maximum cell voltage is above this voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CHARGE_END</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>4.21</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_charge_end>
<vc_charge_min>
<longName>Charge Minimum Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Only allow charging if all cells are above this voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_CHARGE_MIN</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>2</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_charge_min>
<vc_balance_min>
<longName>Balance Minimum Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Only allow balancing if all cells are above this voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_BALANCE_MIN</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>99</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>3.5</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</vc_balance_min>
<balance_max_current>
<longName>Balance Maximum Current</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Only allow balancing when the current magnitude is below this value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_BALANCE_MAX_CURRENT</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>3</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> A</suffix>
<vTx>9</vTx>
</balance_max_current>
<min_current_ah_wh_cnt>
<longName>Minimum Counter Current</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;The current must be above this magnitude for the Ah and Wh couters to run.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_MIN_CURRENT_AH_WH_CNT</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>0.8</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> A</suffix>
<vTx>9</vTx>
</min_current_ah_wh_cnt>
<min_current_sleep>
<longName>Minimum Sleep Current</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Enter sleep mode when the current magnitude is below this value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_MIN_CURRENT_SLEEP</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>0.5</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> A</suffix>
<vTx>9</vTx>
</min_current_sleep>
<v_charge_detect>
<longName>Charger Detect Threshold Voltage</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Start charging when the voltage at the charge port is above this voltage.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_V_CHARGE_DETECT</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>30</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> V</suffix>
<vTx>9</vTx>
</v_charge_detect>
<t_charge_max>
<longName>Charge Max Temp</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Disable charging when the cell temperature is above this value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_T_CHARGE_MAX</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>150</maxDouble>
<minDouble>-15</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>45</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> °C</suffix>
<vTx>7</vTx>
</t_charge_max>
<i_measure_mode>
<longName>Current Measurement Mode</longName>
<type>4</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Current measurement mode. Some BMS versions have optional current measurement, and can instead use the current reported by the VESCs on the CAN-bus.&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;BMS&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Use BMS current sensor. Might need configuration on hardware with an external PCB.&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;VESC&lt;/span&gt; &lt;span style=&quot; font-weight:600;&quot;&gt;CAN&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Use sum of currents reported by VESCs on the CAN-bus.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_I_MEASURE_MODE</cDefine>
<valInt>0</valInt>
<enumNames>BMS</enumNames>
<enumNames>VESC CAN</enumNames>
</i_measure_mode>
<ext_shunt_res>
<longName>Current Shunt Resistance</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Current Shunt Resistance.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_EXT_SHUNT_RES</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1000</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>100</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.1</stepDouble>
<valDouble>0.0002</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> mΩ</suffix>
<vTx>9</vTx>
</ext_shunt_res>
<ext_shunt_gain>
<longName>Current Shunt Amp Gain</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Current shunt amplifier gain.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_EXT_SHUNT_GAIN</cDefine>
<editorDecimalsDouble>3</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>10000</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>50</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix></suffix>
<vTx>9</vTx>
</ext_shunt_gain>
<ext_pch_r_top>
<longName>External Precharge R Div Top</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Precharge output top resistor value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_EXT_PCH_R_TOP</cDefine>
<editorDecimalsDouble>2</editorDecimalsDouble>
<editorScale>0.001</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>1e+07</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>520000</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> kΩ</suffix>
<vTx>9</vTx>
</ext_pch_r_top>
<ext_pch_r_bot>
<longName>External Precharge R Div Bottom</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Precharge output bottom resistor value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_EXT_PCH_R_BOTTOM</cDefine>
<editorDecimalsDouble>2</editorDecimalsDouble>
<editorScale>0.001</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>1e+07</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>10000</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> kΩ</suffix>
<vTx>9</vTx>
</ext_pch_r_bot>
<min_charge_current>
<longName>Min Charge Current</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Stop charging and disable charge port when the charge current goes below this value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_MIN_CHARGE_CURRENT</cDefine>
<editorDecimalsDouble>2</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.01</stepDouble>
<valDouble>0.5</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> A</suffix>
<vTx>9</vTx>
</min_charge_current>
<max_charge_current>
<longName>Max Charge Current</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Maximum allowed charge current.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_MAX_CHARGE_CURRENT</cDefine>
<editorDecimalsDouble>2</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>999</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>0.1</stepDouble>
<valDouble>16</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix> A</suffix>
<vTx>9</vTx>
</max_charge_current>
<sleep_timeout_reset_ms>
<longName>Sleep Timeout Reset Time</longName>
<type>2</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Go to sleep if no keep-awake event has occurred for longer time than this. Examples of keep-awake events are:&lt;/p&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;
&lt;ul style=&quot;margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;&quot;&gt;&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Balancing is active&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Values are polled over CAN or USB&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;USB cable plugged in&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Charging is active&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Other BMSes on the CAN-bus are charging or balancing&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;VESC status messages are received&lt;/li&gt;
&lt;li style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Current over &lt;span style=&quot; font-style:italic;&quot;&gt;min_current_sleep&lt;/span&gt; is drawn&lt;/li&gt;&lt;/ul&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_SLEEP_TIMEOUT_MS</cDefine>
<editorScale>0.001</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxInt>9999999</maxInt>
<minInt>0</minInt>
<showDisplay>0</showDisplay>
<stepInt>1</stepInt>
<valInt>240000</valInt>
<suffix> s</suffix>
<vTx>6</vTx>
</sleep_timeout_reset_ms>
<soc_filter_const>
<longName>SoC Filter Constant</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;State of Charge filter constant. Range 0.1 to 1 000 000. Lower values give more filtering. 1 000 000 disables filtering.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_SOC_FILTER_CONST</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1e+06</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>1</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>1e-05</valDouble>
<vTxDoubleScale>1</vTxDoubleScale>
<suffix></suffix>
<vTx>9</vTx>
</soc_filter_const>
<t_bal_lim_start>
<longName>Temp Bal Lim Start</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Start limiting the number of balancing channels at this temperature.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_T_BAL_LIM_START</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>200</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>60</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> °C</suffix>
<vTx>7</vTx>
</t_bal_lim_start>
<t_bal_lim_end>
<longName>Temp Bal Lim End</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Disable all balancing channels above this temperature.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_T_BAL_LIM_END</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>200</maxDouble>
<minDouble>0</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>75</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> °C</suffix>
<vTx>7</vTx>
</t_bal_lim_end>
<t_charge_min>
<longName>Charge Min Temp</longName>
<type>1</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Disable charging when the cell temperature is below this value.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_T_CHARGE_MIN</cDefine>
<editorDecimalsDouble>1</editorDecimalsDouble>
<editorScale>1</editorScale>
<editAsPercentage>0</editAsPercentage>
<maxDouble>150</maxDouble>
<minDouble>-45</minDouble>
<showDisplay>0</showDisplay>
<stepDouble>1</stepDouble>
<valDouble>0</valDouble>
<vTxDoubleScale>10</vTxDoubleScale>
<suffix> °C</suffix>
<vTx>7</vTx>
</t_charge_min>
<t_charge_mon_en>
<longName>Charge Temp Mon</longName>
<type>5</type>
<transmittable>1</transmittable>
<description>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Roboto'; ; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Enable temperature monitoring during charging. This can be disabled to allow charging when a temperature sensor is broken or missing.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</description>
<cDefine>CONF_T_CHARGE_MON_EN</cDefine>
<valInt>1</valInt>
</t_charge_mon_en>
</Params>
<SerOrder>
<ser>controller_id</ser>
<ser>send_can_status_rate_hz</ser>
<ser>can_baud_rate</ser>
<ser>max_bal_ch</ser>
<ser>dist_bal</ser>
<ser>balance_mode</ser>
<ser>cell_num</ser>
<ser>cell_first_index</ser>
<ser>vc_balance_start</ser>
<ser>vc_balance_end</ser>
<ser>vc_charge_start</ser>
<ser>vc_charge_end</ser>
<ser>vc_charge_min</ser>
<ser>vc_balance_min</ser>
<ser>balance_max_current</ser>
<ser>min_current_ah_wh_cnt</ser>
<ser>min_current_sleep</ser>
<ser>v_charge_detect</ser>
<ser>t_charge_max</ser>
<ser>i_measure_mode</ser>
<ser>ext_shunt_res</ser>
<ser>ext_shunt_gain</ser>
<ser>ext_pch_r_top</ser>
<ser>ext_pch_r_bot</ser>
<ser>min_charge_current</ser>
<ser>max_charge_current</ser>
<ser>sleep_timeout_reset_ms</ser>
<ser>soc_filter_const</ser>
<ser>t_bal_lim_start</ser>
<ser>t_bal_lim_end</ser>
<ser>t_charge_min</ser>
<ser>t_charge_mon_en</ser>
</SerOrder>
<Grouping>
<group>
<groupName>General</groupName>
<subgroup>
<subgroupName>General</subgroupName>
<subgroupParams>
<param>cell_num</param>
<param>cell_first_index</param>
<param>soc_filter_const</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>Charging</subgroupName>
<subgroupParams>
<param>vc_charge_start</param>
<param>vc_charge_end</param>
<param>vc_charge_min</param>
<param>v_charge_detect</param>
<param>t_charge_min</param>
<param>t_charge_max</param>
<param>t_charge_mon_en</param>
<param>min_charge_current</param>
<param>max_charge_current</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>Balancing</subgroupName>
<subgroupParams>
<param>balance_mode</param>
<param>vc_balance_start</param>
<param>vc_balance_end</param>
<param>vc_balance_min</param>
<param>balance_max_current</param>
<param>max_bal_ch</param>
<param>dist_bal</param>
<param>t_bal_lim_start</param>
<param>t_bal_lim_end</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>Sleep</subgroupName>
<subgroupParams>
<param>min_current_sleep</param>
<param>sleep_timeout_reset_ms</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>Counters</subgroupName>
<subgroupParams>
<param>min_current_ah_wh_cnt</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>Communication</subgroupName>
<subgroupParams>
<param>controller_id</param>
<param>send_can_status_rate_hz</param>
<param>can_baud_rate</param>
</subgroupParams>
</subgroup>
<subgroup>
<subgroupName>External</subgroupName>
<subgroupParams>
<param>i_measure_mode</param>
<param>ext_shunt_res</param>
<param>ext_shunt_gain</param>
<param>ext_pch_r_top</param>
<param>ext_pch_r_bot</param>
</subgroupParams>
</subgroup>
</group>
</Grouping>
</ConfigParams>
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "config_export.h"
#include <QEventLoop>
#include <QMetaProperty>
#include <QTimer>
// Decoding and firmware compatibility belong to Commands. This adapter only
// projects its typed result; it never builds or parses vendor packets.
template<typename T> static QJsonObject toolNumbers(const T &value) {
QJsonObject out;
for (int i=0; i<T::staticMetaObject.propertyCount(); ++i) {
const auto p=T::staticMetaObject.property(i);
const auto v=p.readOnGadget(&value);
if (v.type()==QVariant::Double || v.type()==QVariant::Int || v.type()==QVariant::String)
out.insert(QString::fromLatin1(p.name()),QJsonValue::fromVariant(v));
}
return out;
}
static QJsonObject readNativeTool(VescInterface &vesc, const QString &tool) {
auto *cmd=vesc.commands();
const QMap<QString,int> codes{{"adc",COMM_GET_DECODED_ADC},{"chuk",COMM_GET_DECODED_CHUK},
{"imu",COMM_GET_IMU_DATA},{"bms",COMM_BMS_GET_VALUES}};
require(codes.contains(tool),"Unknown peripheral tool");
if (!cmd->getLimitedCompatibilityCommands().contains(codes.value(tool)))
return {{"tool",tool},{"state","unsupported"}};
QEventLoop loop; QTimer timeout; timeout.setSingleShot(true); QObject observer;
QJsonObject values; bool received=false;
auto finish=[&](const QJsonObject &v){values=v;received=true;loop.quit();};
QObject::connect(cmd,&Commands::decodedAdcReceived,&observer,[&](double v,double volts,double v2,double volts2){
if(tool=="adc")finish({{"level_1",v},{"voltage_1_v",volts},{"level_2",v2},{"voltage_2_v",volts2}});
});
QObject::connect(cmd,&Commands::decodedChukReceived,&observer,[&](double v){if(tool=="chuk")finish({{"level",v}});});
QObject::connect(cmd,&Commands::valuesImuReceived,&observer,[&](IMU_VALUES v,unsigned int mask){
if(tool=="imu"){auto out=toolNumbers(v);out.insert("mask",double(mask));finish(out);}
});
QObject::connect(cmd,&Commands::bmsValuesRx,&observer,[&](BMS_VALUES v){
if(tool!="bms")return;
auto out=toolNumbers(v);QJsonArray cells,temps,balancing;
for(auto x:v.v_cells)cells.append(x);for(auto x:v.temps)temps.append(x);for(auto x:v.is_balancing)balancing.append(x);
out.insert("v_cells",cells);out.insert("temps",temps);out.insert("is_balancing",balancing);finish(out);
});
QObject::connect(&timeout,&QTimer::timeout,&loop,&QEventLoop::quit);timeout.start(2000);
if(tool=="adc")cmd->getDecodedAdc();
if(tool=="chuk")cmd->getDecodedChuk();
if(tool=="imu")cmd->getImuData(0xffff);
if(tool=="bms")cmd->bmsGetValues();
if(!received)loop.exec();
require(vesc.isPortConnected(),"Peripheral read disconnected");
return {{"tool",tool},{"state",received?"received":"no_response"},{"values",values}};
}
@@ -4,6 +4,7 @@ import hashlib
import json
from pathlib import Path
import zipfile
from engine_profile import load_profile, header
def build(output):
@@ -11,8 +12,33 @@ def build(output):
files = {"__main__.py": (root / "packaging/native_probe.py").read_bytes(),
"offline_main.cpp": (root / "native/offline_main.cpp").read_bytes(),
"config_export.h": (root / "native/config_export.h").read_bytes(),
"firmware_image.h": (root / "native/firmware_image.h").read_bytes(),
"firmware_source.h": (root / "native/firmware_source.h").read_bytes(),
"bms_native.h": (root / "native/bms_native.h").read_bytes(),
"custom_native.h": (root / "native/custom_native.h").read_bytes(),
"code_native.h": (root / "native/code_native.h").read_bytes(),
"package_native.h": (root / "native/package_native.h").read_bytes(),
"tools_native.h": (root / "native/tools_native.h").read_bytes(),
"swd_native.h": (root / "native/swd_native.h").read_bytes(),
"firmware_native.h": (root / "native/firmware_native.h").read_bytes(),
"config_edit.h": (root / "native/config_edit.h").read_bytes(),
"engine_main.cpp": (root / "native/engine_main.cpp").read_bytes(),
"native_bundle.py": (root / "packaging/native_bundle.py").read_bytes()}
files["bms-settings.xml"] = (root / "native/test-fixtures/bms-settings.xml").read_bytes()
files["native_extensions_check.py"] = (root / "packaging/native_extensions_check.py").read_bytes()
files["native_packages_check.py"] = (root / "packaging/native_packages_check.py").read_bytes()
files["package_archive.py"] = (root / "runtime/package_archive.py").read_bytes()
files["vesc_pkg_all.rcc"] = (root / "build/package-catalog/vesc_pkg_all.rcc").read_bytes()
for name in ("qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h"):
files[name] = (root / "native" / name).read_bytes()
files["native_broker_check.py"] = (root / "packaging/native_broker_check.py").read_bytes()
files["native_samples_check.py"] = (root / "packaging/native_samples_check.py").read_bytes()
files["qml_build.py"] = (root / "packaging/qml_build.py").read_bytes()
files["native_can_check.py"] = (root / "packaging/native_can_check.py").read_bytes()
profile = load_profile()
files["engine-profile.json"] = json.dumps(profile, sort_keys=True).encode()
files["engine_profile.py"] = (root / "packaging/engine_profile.py").read_bytes()
files["engine_profile.h"] = header(profile)
identity = hashlib.sha256(b"".join(k.encode() + v for k, v in sorted(files.items()))).hexdigest()[:24]
output.mkdir(parents=True, exist_ok=True)
path = output / ("mission-core-vesc-native-probe-" + identity + ".pyz")
@@ -0,0 +1,96 @@
{
"schema": "missioncore.vesc.engine-profile/v1",
"rpc_version": 1,
"upstream": {
"repository": "https://github.com/vedderb/vesc_tool",
"version": "7.00",
"commit": "01d5f10901116c311e3fb84d5a1541f663d3ce20",
"source_sha256": "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189"
},
"environment": "ubuntu-24.04-amd64",
"firmware_profiles": [
{
"major": 5,
"minor": 2,
"hardware_type": 0,
"test_firmware": 0,
"custom_configs": 0
}
],
"methods": [
"engine",
"query",
"diagnostic",
"configuration",
"procedure_result",
"lease",
"release",
"current",
"rpm",
"duty",
"duty_limited",
"limits",
"foc_start",
"hall_start",
"configuration_preview",
"configuration_apply",
"firmware_begin",
"firmware_chunk",
"firmware_seal",
"firmware_start",
"firmware_status",
"firmware_cancel",
"device_tool",
"bms_read",
"bms_command",
"firmware_target",
"firmware_snapshot",
"custom_read",
"custom_preview",
"custom_apply",
"code_pack",
"code_read",
"code_write",
"code_control",
"code_stats",
"package_unpack",
"code_snapshot",
"sample_start",
"sample_status",
"sample_fetch",
"sample_stop",
"sample_read",
"qml_read"
],
"firmware_formats": [
"bin",
"hex"
],
"bms_profiles": [
{
"major": 6,
"minor": 0
}
],
"bms_protocol_source": {
"repository": "https://github.com/vedderb/vesc_bms_fw",
"commit": "591d57dadb14d4392d4cf859a5187264a8aafed8"
},
"firmware_targets": [
"usb",
"can",
"swd"
],
"code_profiles": [
{
"major": 6,
"minor": 0,
"hardware_type": 0,
"test_firmware": 0
}
],
"control_transports": [
"usb",
"can"
]
}
+69
View File
@@ -0,0 +1,69 @@
"""Reviewed upstream pin and adapter contract; updates never imply hardware acceptance."""
import hashlib
import json
from pathlib import Path
import re
def load_profile(raw=None):
profile = json.loads(raw if raw is not None else Path(__file__).with_name("engine-profile.json").read_bytes())
if (profile.get("schema") != "missioncore.vesc.engine-profile/v1"
or profile.get("rpc_version") != 1 or type(profile["rpc_version"]) is not int
or profile.get("environment") != "ubuntu-24.04-amd64"):
raise ValueError("Unsupported native engine contract")
source = profile.get("upstream", {})
if (source.get("repository") != "https://github.com/vedderb/vesc_tool"
or not re.fullmatch(r"[0-9]+\.[0-9]{2}", source.get("version", ""))
or not re.fullmatch(r"[0-9a-f]{40}", source.get("commit", ""))
or not re.fullmatch(r"[0-9a-f]{64}", source.get("source_sha256", ""))):
raise ValueError("Upstream source must be pinned by commit and archive hash")
profiles = profile.get("firmware_profiles")
fields = {"major", "minor", "hardware_type", "test_firmware", "custom_configs"}
if not isinstance(profiles, list) or not 1 <= len(profiles) <= 64:
raise ValueError("Explicit bounded firmware profiles required")
for item in profiles:
if (not isinstance(item, dict) or set(item) != fields
or any(type(v) is not int or not 0 <= v <= 255 for v in item.values())):
raise ValueError("Invalid firmware acceptance profile")
methods = profile.get("methods")
if (not isinstance(methods, list) or not 1 <= len(methods) <= 128
or len(set(methods)) != len(methods)
or any(not isinstance(v, str) or not re.fullmatch(r"[a-z_]{1,48}", v) for v in methods)
or not {"engine", "query", "configuration"}.issubset(methods)):
raise ValueError("Invalid native operation inventory")
if profile.get("firmware_formats", ["bin"]) not in (["bin"], ["bin", "hex"]):
raise ValueError("Invalid firmware file formats")
if profile.get("firmware_targets",["usb"]) not in (["usb"],["usb","can","swd"]):raise ValueError("Invalid firmware transports")
if profile.get("control_transports", ["usb"]) not in (["usb"], ["usb", "can"]):
raise ValueError("Invalid control transports")
bms = profile.get("bms_profiles", [])
if not isinstance(bms,list) or len(bms)>16 or any(not isinstance(v,dict) or set(v)!={"major","minor"} or any(type(n) is not int or not 0<=n<=255 for n in v.values()) for v in bms):
raise ValueError("Explicit BMS command profiles required")
if bms:
source=profile.get("bms_protocol_source",{})
if source.get("repository")!="https://github.com/vedderb/vesc_bms_fw" or not re.fullmatch(r"[0-9a-f]{40}",source.get("commit","")):
raise ValueError("Pinned BMS protocol source required")
code = profile.get("code_profiles", [])
if code not in ([], [{"major":6,"minor":0,"hardware_type":0,"test_firmware":0}]): raise ValueError("Unreviewed code protocol profile")
return profile
def contract(profile):
raw = json.dumps(profile, sort_keys=True, separators=(",", ":")).encode()
return {"rpc_version": profile["rpc_version"], "profile_sha256": hashlib.sha256(raw).hexdigest(),
"control_transports": profile.get("control_transports", ["usb"]), "code_profiles":profile.get("code_profiles",[]), "firmware_profiles": profile["firmware_profiles"], "methods": profile["methods"],
"firmware_targets":profile.get("firmware_targets",["usb"]), "firmware_formats": profile.get("firmware_formats", ["bin"]), "bms_profiles": profile.get("bms_profiles", [])}
def header(profile):
data = {**profile, "contract": contract(profile)}
literal = json.dumps(json.dumps(data, sort_keys=True, separators=(",", ":")))
return ("// Generated from the reviewed engine profile; do not edit.\n#pragma once\n"
"#include <QJsonDocument>\n#include <QJsonArray>\n#include <QJsonObject>\n"
"static QJsonObject engineProfile() { return QJsonDocument::fromJson(QByteArray(" + literal + ")).object(); }\n"
"static bool nativeFirmwareQualified(int major, int minor, int type, int test, int custom) {\n"
" for (const auto &value : engineProfile().value(\"firmware_profiles\").toArray()) {\n"
" auto p = value.toObject(); if (p.value(\"major\").toInt() == major && p.value(\"minor\").toInt() == minor &&\n"
" p.value(\"hardware_type\").toInt() == type && p.value(\"test_firmware\").toInt() == test &&\n"
" p.value(\"custom_configs\").toInt() == custom) return true;\n"
" } return false;\n}\n").encode()
@@ -0,0 +1,37 @@
"""Restore reviewed official firmware blobs; never selects a moving upstream ref."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import urllib.request
def fetch(output):
manifest=json.loads(Path(__file__).with_name('firmware-catalog.json').read_text())
commit=manifest['commit']
if not re.fullmatch(r'[0-9a-f]{40}',commit) or len(manifest['items'])>512:
raise ValueError('Reviewed catalogue pin required')
output.mkdir(parents=True,exist_ok=True)
for item in manifest['items']:
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.bin',item['path']):
raise ValueError('Invalid upstream firmware path')
sha=item['sha256']
if not re.fullmatch(r'[0-9a-f]{64}',sha) or not 256<=item['bytes']<=2*1024**2:
raise ValueError('Invalid firmware size/digest')
path=output/(sha+'.bin')
if path.exists():
data=path.read_bytes()
else:
url='https://raw.githubusercontent.com/vedderb/vesc_fw_archive/'+commit+'/'+item['path']
with urllib.request.urlopen(url,timeout=30) as response:data=response.read(item['bytes']+1)
if len(data)!=item['bytes'] or hashlib.sha256(data).hexdigest()!=sha:
raise ValueError('Pinned firmware bytes changed')
if hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()!=item['git_blob']:
raise ValueError('Upstream Git blob changed')
if not path.exists():path.write_bytes(data)
return {'commit':commit,'images':len(manifest['items'])}
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--output',type=Path,required=True)
print(json.dumps(fetch(p.parse_args().output)))
@@ -0,0 +1,12 @@
"""Restore the reviewed catalogue bytes; never silently adopt new code."""
from pathlib import Path
import hashlib,json,urllib.request
def main():
root=Path(__file__).resolve().parents[1];pin=json.loads((root/'packaging/package-catalog.json').read_text())
target=root/'build/package-catalog/vesc_pkg_all.rcc'
if target.exists() and hashlib.sha256(target.read_bytes()).hexdigest()==pin['sha256']:return
with urllib.request.urlopen(pin['source'],timeout=30) as response:data=response.read(pin['bytes']+1)
if len(data)!=pin['bytes'] or hashlib.sha256(data).hexdigest()!=pin['sha256']:raise ValueError('Upstream catalogue changed; review and repin explicitly or restore the qualified artifact')
target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
if __name__=='__main__':main()
@@ -0,0 +1,13 @@
Official archived VESC firmware images, unmodified.
Repository: https://github.com/vedderb/vesc_fw_archive
Archive revision: 0030cfa9d6250331436b31a01f006fe0546bf6a6
Firmware version included: 5.02
The catalog records each upstream path, Git blob ID, size and SHA-256.
Upstream firmware source: https://github.com/vedderb/bldc/tree/5.02
Firmware license: GNU GPL version 3 or later (see firmware LICENSE).
No claim of locally reproduced binary/source equivalence is made. These are
upstream archived binaries; the manifest is not manufacturer authentication.
Archive selection does not flash a controller. Firmware updates require a
separate explicit operator action for a compatible board.
Rebuild the installer inputs with packaging/fetch_firmware_catalog.py using
the committed catalog manifest. Runtime downloads are not used.
@@ -0,0 +1,593 @@
{
"schema": "missioncore.vesc.firmware-catalog/v1",
"repository": "https://github.com/vedderb/vesc_fw_archive",
"commit": "0030cfa9d6250331436b31a01f006fe0546bf6a6",
"admitted_versions": [
"5.02"
],
"items": [
{
"id": "fwimg_75a855d02179b810b87e40b7a14002ee",
"path": "5.02/100_250/VESC_default.bin",
"git_blob": "c90ccf8657d3757c22a794e640f23423a08ae846",
"sha256": "cf2eb45caaf6b6514adf392e833c54774c910879d3a82b7fdf9e87369c5533b6",
"bytes": 393208,
"hardware": [
"100_250"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_4aefbbe67d1cfd47e6d5bede921b13e6",
"path": "5.02/100_250/VESC_default_no_hw_limits.bin",
"git_blob": "24bc5beaebd9193c7cd57703e65a4ed18f282998",
"sha256": "229bc4d414864df07ce8cb066c52957fd9ef285225d3ce45007c04c2e752ed0a",
"bytes": 393208,
"hardware": [
"100_250"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_3bf6f675f714c999b0acc2e511546958",
"path": "5.02/410_o_411_o_412/VESC_0005ohm.bin",
"git_blob": "893e8e9df2768b2c9a708f9565ede7c99b6b3f3b",
"sha256": "c2bd00715419ae4a502c085a5ae9b605bfbe8b70e9c9af6cf14e4e20111365e9",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_0005ohm.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_80183324bdf6fb609c5a81a28771b31b",
"path": "5.02/410_o_411_o_412/VESC_default.bin",
"git_blob": "8d9a8672aee647bb79e0932e38e27f6bc7361040",
"sha256": "70d491dd289569dd9d1d680a497a8aac66daaa09f9a0738fa8209ebc78b256cc",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_939bd113ef079cd9395fc0ea0f9b3186",
"path": "5.02/410_o_411_o_412/VESC_default_no_hw_limits.bin",
"git_blob": "80089b6b99015e0c8c5cebd51f3177dff855f89c",
"sha256": "d412b6996539cd366ee7d128e84be2c62615c50794b3d37e98c4e74ee05e856d",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_681a14ef42afe71a902081629d74b2ef",
"path": "5.02/46_o_47/VESC_0005ohm.bin",
"git_blob": "346277633899b3e6521ae81080450f578647165f",
"sha256": "8ca6965370105cd9ce19b75750c85c784d0978d2e8aa0435e853d03adbc4bd92",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_0005ohm.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_57c7db707659d6a3c83ca1b43f60f3ea",
"path": "5.02/46_o_47/VESC_33k.bin",
"git_blob": "935687e5287cf161b23451f9640c1ee025af784b",
"sha256": "b3c93169808237acbccd17f5edfaf7b3b7d5d804000d3452f226482fcca81807",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_33k.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_3be270d4c425948c504cbd7fe5483855",
"path": "5.02/46_o_47/VESC_default.bin",
"git_blob": "1e95afa5ca6a56f3dd2204d0700ad14399f3cd20",
"sha256": "8324b8f37666301aa35aa04aa9766b4a9d7b47ef675247c2d1621e40a45c1238",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_f08494a202c43657f17f1b1b730aa945",
"path": "5.02/48/VESC_default.bin",
"git_blob": "3ad4d01d29deecbfe6f2526471ce3a4ca616135c",
"sha256": "29cb80525dd88adeaa0bb0ca89fe31c47251df9a7d50607a95b2487cab2b4d78",
"bytes": 393208,
"hardware": [
"48"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_248e82b3658efdc981674300f3da5461",
"path": "5.02/60/VESC_default.bin",
"git_blob": "5c2e98823998fee69c46c0a72b803d37442069f5",
"sha256": "5f5c7c876d28e9454d8798b33bbb3844ece52e5ce3bbad2653a025f1c83e4f90",
"bytes": 393208,
"hardware": [
"60"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_579fc598378b6ebc98133bfebd67f43f",
"path": "5.02/60/VESC_default_no_hw_limits.bin",
"git_blob": "5c5f692fa0622207dab86b525a0517677d96d45b",
"sha256": "74ccc48aff7f95ec772d1dc8101b94f41f9f11e588c3afdb9a51d1f67d7cad2a",
"bytes": 393208,
"hardware": [
"60"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_e2e670e40ec08022f880ae6b742d6d01",
"path": "5.02/60_MK3/VESC_default.bin",
"git_blob": "784ad4cfb5e650a7ba0ff7105a21f23f4aa1b4d2",
"sha256": "055cd5d315d52225d5446e17c99c6c33d7e1e80c209d8b8b3832b533703f1a50",
"bytes": 393208,
"hardware": [
"60_MK3"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c33e1f3a783192f48410c1d920f10992",
"path": "5.02/60_MK3/VESC_default_no_hw_limits.bin",
"git_blob": "a532f14539ceab8b93f747523df8f5947236e4bb",
"sha256": "55f761c5da50e69d84516f29d8a7d8374be63aad4e25404a89edbdc981129ebb",
"bytes": 393208,
"hardware": [
"60_MK3"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_8279ca0cd0e0fd8c8ac7862759badf92",
"path": "5.02/60_MK4/VESC_default.bin",
"git_blob": "43d5946127e3adc87dffb16cf993334c74ac4fb7",
"sha256": "5ddfa85461e5dfe203e183c1b0bfdc392e5d8e310a675e61a5a8da971bd8d413",
"bytes": 393208,
"hardware": [
"60_MK4"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ceff40c3cb92c34ab9735d7e960ef978",
"path": "5.02/60_MK4/VESC_default_no_hw_limits.bin",
"git_blob": "f2bdf292c1b2ed5f3a012532b4d2aa94757fa31c",
"sha256": "24a93b4a0d3ab2ce5bc6e08129a4c81071f4e448e267b9f5629beed5272703bc",
"bytes": 393208,
"hardware": [
"60_MK4"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_2b9bc59a8361eead3e11da0889404c73",
"path": "5.02/60_MK5/VESC_default.bin",
"git_blob": "0650e356c0304fccd5fcc4ad4d826e65c666b934",
"sha256": "b7116ce5fbb739d2dfac6efdbd6b9e90fe5f9d552d482d65eebee4651dc6075e",
"bytes": 393208,
"hardware": [
"60_MK5"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c944ee5400afa5e02ef43a175d0603ab",
"path": "5.02/60_MK5/VESC_default_no_hw_limits.bin",
"git_blob": "22bc5b6fac1e188e1bfa93cd077f62833b8af38d",
"sha256": "d75fd10faf81d841811f35d5a49a41eb1bba2e80adf1c9f70e1626bb0f7582e0",
"bytes": 393208,
"hardware": [
"60_MK5"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_d2bd9fd4be5681db97f28095b7b69771",
"path": "5.02/75_300/VESC_default.bin",
"git_blob": "253d5be8030d0a7bb3805cf0acf88ae0c6b53ad1",
"sha256": "b646c7e5c8b6014062833c8a1c96126c2b7b729672579723848bc8f0a3aa68d5",
"bytes": 393208,
"hardware": [
"75_300"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c6729c906442486769f56f5ff2b43b87",
"path": "5.02/75_300/VESC_default_no_hw_limits.bin",
"git_blob": "c2308f8c2ec9e28ea3af88ead47ae4982ed524c0",
"sha256": "a19af872f4fc422da2bdc34d0ea330b787cc7c27392b4bededaf561db20ccb07",
"bytes": 393208,
"hardware": [
"75_300"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_b9ca797afd58d737be17a2f73b721018",
"path": "5.02/75_300_R2/VESC_default.bin",
"git_blob": "5b79daf0d41008ff7ccad72b00ff8d0dc24f187d",
"sha256": "52c3d9c8d1e7d5670d43d7976a0f02d68c356a666488bcb8d95228e321adf32a",
"bytes": 393208,
"hardware": [
"75_300_R2"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_80c2913ec89ac6673d2be4b247a0aa69",
"path": "5.02/75_300_R2/VESC_default_no_hw_limits.bin",
"git_blob": "ce5d05d2b73f78df5f5a8209588699ff1db90d79",
"sha256": "6d541051f2fcbf946e92db95a4cd573f2f94a3c5fb7cf4d638c9648038b143e9",
"bytes": 393208,
"hardware": [
"75_300_R2"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_2f2d894c2758153f6cf7941b3c928846",
"path": "5.02/75_300_R3/VESC_default.bin",
"git_blob": "b8bdb09c31fc396ba40668e02f1489d533d34f24",
"sha256": "9e1d3c2ccaa12067b604492ebfd1fea2c8768663e7b9b5c45711ad98ca347643",
"bytes": 393208,
"hardware": [
"75_300_R3"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_2e065e7221d31da73cb36d210b9dcc09",
"path": "5.02/75_300_R3/VESC_default_no_hw_limits.bin",
"git_blob": "368d51117b0f92b018a0e5edc82b169ebf5e9c92",
"sha256": "b317f748161d8667f6a36cbeb37e97b3ca959eaaa295aada4bffdc6b6a14946e",
"bytes": 393208,
"hardware": [
"75_300_R3"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_f9fd23f542101759c6cd3d86b1373a4b",
"path": "5.02/A200S_V21/VESC_default.bin",
"git_blob": "ea3af455b80c648cba90de9308a23dc5f94edd6d",
"sha256": "402af86fecd20118762f0d0bd39af63c4b94008deeb3a6500cd8456edd4766a0",
"bytes": 393208,
"hardware": [
"A200S_V21"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_8ae9a0f15636d664557b0143933c7df1",
"path": "5.02/A200S_V22/VESC_default.bin",
"git_blob": "f0cc0d5bbd3c3dca813821c3d80438a183ccf48e",
"sha256": "edab8fbe92aca9d99ac13ed786c690c859b4a74456362b55e566d7ac38547a65",
"bytes": 393208,
"hardware": [
"A200S_V22"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_392b962f7e97e92575391f102b022f39",
"path": "5.02/AXIOM/VESC_default.bin",
"git_blob": "cff1a12ceb7650aa3aeed879e9e946d8058df374",
"sha256": "9d365675f1edcf609efb5a17a80fa1cfd4f6bd2baa597512584e5a9f16587095",
"bytes": 393208,
"hardware": [
"AXIOM"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ed9bcf99fb6e822056f4aacc94586c3e",
"path": "5.02/DAS_RS/VESC_default.bin",
"git_blob": "8bab886fbbaf3b0fef51d1f55c62254df7b3833a",
"sha256": "8797f475aea54dda11ccea40039fabb40f8faf69ec4cbc64c896d70b3b06bb42",
"bytes": 393208,
"hardware": [
"DAS_RS"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_3c3d4fd4e1c0239a190fc561cef33ddf",
"path": "5.02/HD60/VESC_default.bin",
"git_blob": "6855adb297e6cefe443f7c656621bf9380dfb328",
"sha256": "af3eae52ff6f906cdcecf581c1f66297c09095a63ca700b4c6aa9a648b0cf7e0",
"bytes": 393208,
"hardware": [
"HD60"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_0b76cd76dc14492b1d0314b1b2599a0a",
"path": "5.02/HD60/VESC_default_no_hw_limits.bin",
"git_blob": "cce2905941e677ec21cfb5d37dcee54728f0a898",
"sha256": "1231a6cc61917e773295082ca796515aa6aee9fe5bb12119f94cdb40745d9e49",
"bytes": 393208,
"hardware": [
"HD60"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_25123e904a14be40712992047681f4b2",
"path": "5.02/HD75/VESC_default.bin",
"git_blob": "f2f46d242f0dfd7abf57dd4e7a19510f5b4bcc4a",
"sha256": "d3ce9be5a85ca7a613c85899412ec0cbc4c025c3168baa161ca43d2204bec4e6",
"bytes": 393208,
"hardware": [
"HD75"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_547e9963b050a1d412344d07bda659ed",
"path": "5.02/HD75/VESC_default_no_hw_limits.bin",
"git_blob": "50071916243efbaa6c67cc0bb26c0ae1cfae777a",
"sha256": "e015ec6c4502a3ef2475d77d9f72fb5ec007f08f7a70716f3f9bb74a069d5d84",
"bytes": 393208,
"hardware": [
"HD75"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_8445452db9e2c15e0edafc4232baf6a2",
"path": "5.02/LUNA_BBSHD/VESC_default.bin",
"git_blob": "8ddf65dca569be5b21466b2f1f450ce650a4fbac",
"sha256": "92e938a56a164681731a89957c16d62e6b86e85203f0d0ddcb920dcb9406c8c7",
"bytes": 393208,
"hardware": [
"LUNA_BBSHD"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_b037176c63f44af2d112be7c46b651ef",
"path": "5.02/STORMCORE_100D/VESC_default.bin",
"git_blob": "ca67541c042126b58c875fb6fb7b5d19bfa1ee23",
"sha256": "633cbeb6fa11bfefdc98ac1b6b2765fe080ec56a5272c8219b6e9422b6ee4f22",
"bytes": 393208,
"hardware": [
"STORMCORE_100D"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_510bc5346a26ab5abe00598b9e3a7a15",
"path": "5.02/STORMCORE_100D/VESC_default_no_hw_limits.bin",
"git_blob": "d2cb084eb6e2f10b4e33ab826b4d84ff2cb1bcb6",
"sha256": "66c19f693ac1018de5818fa7856629133ad4d389cab3366d202495c6ee4f352b",
"bytes": 393208,
"hardware": [
"STORMCORE_100D"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_3fb8cbee44e0ef14e11558f272d2a5ad",
"path": "5.02/STORMCORE_100S/VESC_default.bin",
"git_blob": "06adfb19ab9981c327aee4d6a71ae46c27778c65",
"sha256": "4167f6c34fa3c2267cee15f593b0b93d14fd7ae032049fb944e3f464c90b4434",
"bytes": 393208,
"hardware": [
"STORMCORE_100S"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_af09ed784286b4c5fa82baa72d43881e",
"path": "5.02/STORMCORE_100S/VESC_default_no_hw_limits.bin",
"git_blob": "12d545cb0afe8a282948cfd7288658e9d65f8a79",
"sha256": "afeada4f382a354a709bb7a2849bbab7bde8b8144479d2dcffabd870e8ba33e3",
"bytes": 393208,
"hardware": [
"STORMCORE_100S"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_c327a275325fe87b693611099625e451",
"path": "5.02/STORMCORE_60D/VESC_default.bin",
"git_blob": "25907b4cfcabf5277701d933ef837e7c991540bd",
"sha256": "3867b3f60ca650d8dd742d532b46f4475b347d6e623d9555a140e386caf2f453",
"bytes": 393208,
"hardware": [
"STORMCORE_60D"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_652b83aefe9aa2f1a2fb5246164c8414",
"path": "5.02/STORMCORE_60D/VESC_default_no_hw_limits.bin",
"git_blob": "b2a220c858eeb5b401fc18642d9f3ca938a691f9",
"sha256": "89945b83a12f3f91eeff2c42d115830bc9f30817d05c513b1f6cd99f1a1c786a",
"bytes": 393208,
"hardware": [
"STORMCORE_60D"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_cb2a8e9dc5d125f6b89db1da8edc7e2e",
"path": "5.02/UAVC_OMEGA/VESC_default.bin",
"git_blob": "cf9c8f8c8f951a02195f8405ab1fb287dc2b0bce",
"sha256": "d014be805e06237cca9057aae6e5ace96546905d6a0256633675e4a1fb9e3b77",
"bytes": 393208,
"hardware": [
"UAVC_OMEGA"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_21e86da15b810624c5c542ae425badd6",
"path": "5.02/UNITY/VESC_default.bin",
"git_blob": "ffe19f1f13bc6137aca8b78a5825b58ac43507a1",
"sha256": "17042fd9fb0f6455ff886eccb03ec2dced6d408d7895849eaa45f3b5420350ee",
"bytes": 393208,
"hardware": [
"UNITY"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ce34a332bbe40e7ada15fdb5bb4e6109",
"path": "5.02/UNITY/VESC_default_no_hw_limits.bin",
"git_blob": "d08e9d3892837078a251f8752ce4859ac496a51e",
"sha256": "3f6efc4ce7483c65d7005a25e7e503539c29ffbd09749616654aa9d78d6971aa",
"bytes": 393208,
"hardware": [
"UNITY"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
}
]
}
@@ -27,11 +27,14 @@ ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
RestrictAddressFamilies=AF_UNIX
# Native Tool and bridge communicate on loopback inside this private network.
RestrictAddressFamilies=AF_UNIX AF_INET
DevicePolicy=closed
DeviceAllow=char-ttyACM rw
MemoryMax=512M
MemoryMax=1G
TasksMax=64
LogRateLimitIntervalSec=30s
LogRateLimitBurst=60
[Install]
WantedBy=multi-user.target

Some files were not shown because too many files have changed in this diff Show More